lundi 27 février 2012

Read data from an optical fork or an encoder

PIC has a lot of interesting features and one of them is the amazing portb that can create hardware interruption in each variation.

the code above I used to read data from an optical fork.

The code is very simple:

every time there is a state change in one of the portb pin we enter the interrupt routine and we can do whatever we want to do there.

I used the timer 0 interruption just in case you want to do know the number of hardware interruption each period of time.

I used PIC18F4550 and 40Mhz oscillator.

int read=0;
int left=0;
int right=0;
int l =0;
int riL =0;
char txt[7];
void interrupt(){
if(TMR2IF_bit){
portd.RD4=~portd.RD4;
left=l;
l=0;
TMR2IF_bit=0;//never forget to put 0 int the flag after interruption
}
if(INTCON.RBIF==1){
portd.RD2=~portd.RD2;
l++;
read=portb;
INTCON.RBIF=0;
}
}
void init(){
portd=0X00;
trisd=0X00;
portb=0X00;
trisb=0XFF;
//initialisation de ports
intcon=0XC8;
//initialisation des interruption global(GIE,PIE,RBE)
t2con=0X07;
TMR2IE_bit=1;
//timer 2
uart1_init(9600);
}
void main() {
init();
while(1){
inttostr(left,txt);
uart1_write_text(txt);
uart1_write(10);
uart1_write(13);//pour la visualisation

};


}

Aucun commentaire:

Enregistrer un commentaire