关于旋转编码器的问题

发布: 2009-12-24 10:12 | 作者: ITS2009 | 来源: StmFans思蜕盟 OPELC 自由电子联盟

  

编码器波形如下:

正向  A:____------____------____

          B:---____------____------____



反向  A:---____------____------____

          B:____------____------____

我写的程序如下:
//包含所需头文件
/*  MCU  atmega16 晶振11.0592
  外部中断INT0,下降沿触发中断
  串口通信 发送数据长度9,停止位1,baut=19200  */
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>




/*------宏定义------*/
#define uchar        unsigned char
#define uint        unsigned int
#define BIT(x)        (1<<(x))
#define NOP()        asm("nop")
#define WDR()         asm("wdr")

unsigned int counter=0,temp=0;
unsigned char director;
unsigned char readflag;


//端口初始化
void port_init(void)
{
   DDRA  = 0x00;
          PORTA = 0x00;
          DDRB  = 0x00;
          PORTB = 0x00;
   DDRC  = 0x00;
          PORTC = 0x00;
          DDRD  = 0x00;
          PORTD = 0x00;
       
}


//串口通信初始化
void usart_init(void)
{
        UCSRB = 0x00;//禁止中断
        UCSRA = 0x00;
        UCSRC = BIT(URSEL) | 0x16;
        UBRRL = 0x23;
        UBRRH = 0x00;
        UCSRB = 0x1C;
}

void uart_send(unsigned char i)        //发送1个字符子函数
{
    while(!(UCSRA&(1<<UDRE)));   //等待发送缓冲区为空
    UDR=i;
}

unsigned char uart_receive(void)        //接收1个字符子函数
{
    while(!(UCSRA&(1<<RXC)));    //等待接收数据
    return UDR;                  //返回接收到得数据
}

//外中断初始化
void int_init(void)
{
          MCUCR |= 0x02;
          MCUCSR|= 0x00;
          GICR  |= 0x40;

}


//外中断0服务程序
//#pragma interrupt_handler int0_isr:2
//void int0_isr(void)
SIGNAL(SIG_INTERRUPT0)
{
   counter++;
   director=PA0;
   uart_send(0x33);    //测试是否进入中断
        //外中断0
}

void delay_s()   //延时函数
{
   volatile unsigned long i,j;
   for(i=0;i<5;i++)
   {
       for(j=0;j<60000;j++);
   }
}

void init_devices(void)
{
          cli(); //禁止所有中断
          MCUCR  = 0x00;
          MCUCSR = 0x80;//禁止JTAG
          GICR   = 0x00;
          port_init();
          usart_init();
          int_init();
          sei();//开全局中断
}
//主函数
int main(void)
{
        init_devices();
        //在这继续添加你的代码
        while(1)
        {
         if(counter!=0)       //计数脉冲
     {
        temp=temp+counter;
        counter=0;
     }
     //以下判断是否旋转结束
     if((counter==0)&&(PA0==1))
      {
          uart_send(0x02);
         delay_s();//延时1s
         if((counter==0)&&(PA0==1))//旋转结束
         {
                uart_send(director);//director=1,为正转,反之则反
             uart_send(temp);
             }
      }
}
return 0;
}

当没有旋转或者旋转接受时,A和B都是高电平。A接INT0引脚,B接PA0,A用于计数脉冲,B用于判断旋转的方向
用串口调试观察,在中断里面能输出33,可是就是不输出脉冲个数和方向。请问while(1)下面程序中哪里出错?请各位过路的大侠多多指点谢谢大家
binglin (2009-12-24 10:53:43)
把判断是否旋转结束的代码改为如下试试

[url]    //以下判断是否旋转结束
     if(counter==0)
      {
          uart_send(0x02);
         delay_s();//延时1s
         if(counter==0)//旋转结束
         {
                uart_send(director);//director=1,为正转,反之则反
             uart_send(temp);
             }
      }[/url]
ITS2009 (2009-12-24 11:25:53)
好的,谢谢!我试试