Code:
#include <18f4431.h>
#include <def_4431.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP//,NOBROWNOUT,NOPUT,NOCPD,NODEBUG,NOFCMEN,NOCPB,NOPWMPIN,STVREN
#use delay(clock=4000000)
#use fast_io(a)
#use fast_io(d)
#use fast_io(c)
#use fast_io(e)
#include <lcd.c>
#define use_portd_lcd true
int16 duty_cycle0=0;
int16 velocity=0;
int16 dem=0;
void display_lcd();
void Read_QEI(); //doc QEI
#INT_PWMTB
void interrupt_pwmtb()
{
dem++;
if(dem==3000)
{dem=0;
Read_QEI();
}
}
void main()
{
set_tris_b(0); // port B la xuat
portb=0;
set_tris_c(0);
portc=0xff;
set_tris_d(0);
portd=0;
set_tris_a(0xff);
porta=0xff;
//setup LCD
lcd_init();
display_lcd();
//setup power PWM
PTCON1=0b10000000; // dung che do ngat time base
SETUP_POWER_PWM(PWM_CLOCK_DIV_64|PWM_FREE_RUN,1,0,1249,0,1,0);//5khz hay chu ki là 200ms
SETUP_POWER_PWM_PINS(PWM_COMPLEMENTARY,PWM_COMPLEMENTARY,PWM_OFF,PWM_OFF);
SET_POWER_PWM0_DUTY(0);
duty_cycle0=250;
//setup QEI
MAXCNTL=0xFF;
MAXCNTH=0xFF;
POSCNTH = 0x00;
POSCNTL = 0x00;
QEICON = 0b10101000;
DFLTCON = 0b00010011;//filter tren chan QEA clock devider 1:16
//interrupts
enable_interrupts(INT_PWMTB);
enable_interrupts(global);
while(1)
{
display_lcd();
SET_POWER_PWM0_DUTY(duty_cycle0);
SET_POWER_PWM2_DUTY(duty_cycle0);
if(RC1==0)
{
delay_ms(50);
if(RC1==0)
{
if(duty_cycle0==500)duty_cycle0=500;
else duty_cycle0=duty_cycle0+5;
}
}
if(RC2==0)
{
delay_ms(50);
if(RC2==0)
{
if(duty_cycle0==250)duty_cycle0=250;
else duty_cycle0=duty_cycle0-5;
}
}
}
}
void display_lcd()
{
lcd_gotoxy(1,1);
printf(lcd_putc,"duty=%lu",duty_cycle0);
lcd_gotoxy(10,1);
printf(lcd_putc,"%lu",dem);
lcd_gotoxy(1,2);
printf(lcd_putc,"V=%lu",velocity/2);
}
void Read_QEI() //doc QEI
{
velocity = make16(POSCNTH,POSCNTL);
POSCNTH = 0x0;
POSCNTL = 0x0;
}
đây là đoạn code em dùng để test thử.mục đích ban đầu chỉ là muốn tính và hiển thị số xung trên chân QÉA.
khi em để hở chân này.giá trị hiển thị rất lớn cỡ mấy chục ngàn.khi em cho nó xuống mass thì có trở về 0 nhưng chỉ cần rung jump 1 tí là lại nhảy lên.
em nối nó vào 1 nút nhấn có điện trở kéo nguồn .nhấn thì xuống mass còn bình thường thì đo là 5v.nó cũng ko chính xác tí nào.nhưng nếu em đổi dùng ngắt ngoài thì chính xác.
em nghĩ do phần cứng nhiều hơn.anh xem giúp em nhé!!