请教菜鸟问题

发布: 2009-12-24 15:55 | 作者: 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); //测试是否进入中断
}

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)
     {
   
         delay_s();//延时1s
         if(counter==0)//旋转结束
         {
                   uart_send(director);//director=1,为正转,反之则反
             uart_send(temp);//发送脉冲的个数
         }
     }
          }
          return 0;
}
当没有旋转或者旋转接受时,A和B都是高电平。A接INT0引脚,B接PA0,A用于计数脉冲,B用于判断旋转的方向
用串口调试观察,在中断里面能输出33,输出的方向director 总是为00.即使把方向线B拔下,输出的方向derector还是为00.请问while(1)下面程序中哪里出错?请各位过路的大侠多多指点谢谢大家
ITS2009 (2009-12-24 17:07:52)
哭,怎么办啊?过路大侠帮帮你!
jasonjee (2009-12-24 20:00:21)
中断是电平中断还是边沿中断?
你的方法,单边沿中断才能用,双边沿或者电平中断,肯定出错
ITS2009 (2009-12-24 21:31:58)
2楼的,首先感谢你回我的帖子,我是用单边沿中断啊!我用A的下降沿中断,B只是接一个普通的IO口,并没有用作其他的。请问这是什么问题!