![]() |
|
Tài trợ cho PIC Vietnam |
|
Ðiều Chỉnh | Xếp Bài |
![]() |
#3 |
Nhập môn đệ tử
Tham gia ngày: Apr 2011
Bài gửi: 7
: |
Cuối cùng cũng mày mò ra cách dùng ngắt TIMER0. Trong đoạn code này chỉ cần thay đổi thông số Center là nó sẽ quay theo những góc khác nhau. Ở hàm Main có thay đổi Center bằng cách gán lần lượt với 3 biến. Nó sẽ quay trái-giữa-phải-giữa-...
Cách nối dây rất đơn giản, chỉ cần nối dây đỏ của Servo với (+) nguồn, dây đen với (-) nguồn, còn dây vàng nối với chân RA0 của PIC. Nếu bạn muốn nối dây vàng với chân khác của PIC thì chỉ cần thay đổi trong hàm ngắt và thiết lập chân đó thành chân xuất là ok. Code:
#include <16F877A.H> #include <def_877a.h> #device *=16 ADC=8 #FUSES NOWDT, HS, NOPUT, NOPROTECT, NODEBUG, BROWNOUT, NOLVP, NOCPD, NOWRT #use delay(clock=20000000) #define MAX_VALUE 200 #define Right MAX_VALUE-35 //quay phai -23 #define Center MAX_VALUE-17 // quay trai -17 #define Left MAX_VALUE-1 //o giua -11 unsigned char pulse_max=0; unsigned char pulse_top=0; unsigned char top_value=0; #INT_TIMER0 void interrupt_timer0() { set_timer0(56); pulse_max++; pulse_top++; if (pulse_max >= MAX_VALUE) { pulse_max=0; pulse_top=0; RA0=0; // Turn off RC2 } if (pulse_top == top_value) { RA0=1; // Turn On RC2 } } /* TIMER0 period = [(TMR0 + 1)] x 4 x Tosc x (TIMER0 prescaler value) second Init TIMER0: Period: Fosc/4 x Prescaler x TMR0 */ void main() { trisa=0x00; trisd=0xff; portC = 0x00; //trisd=0x00; //portd=0; top_value = Center; enable_interrupts(global); enable_interrupts(int_timer0); setup_timer_0(RTCC_INTERNAL|RTCC_DIV_2); set_timer0(156); top_value=Center;/* while(1) { switch(portd){ case 1: top_value=Right; delay_ms(100); top_value=Center; break; case 2: top_value=Left; delay_ms(100); top_value=Center; break; case 4: top_value=Center; break; default: break; }*/ while(1){ top_value=Right; delay_ms(1000); top_value=Center; delay_ms(1000); top_value=Left; delay_ms(1000); top_value=Center; delay_ms(1000); } } thay đổi nội dung bởi: lvdinh_tvtsth, 03-10-2012 lúc 12:50 PM. |
![]() |
![]() |
|
|