C语言 我可以在这段代码中做些什么改变来使它工作?

n6lpvg4x  于 2023-01-01  发布在  其他
关注(0)|答案(2)|浏览(117)

此C代码,Atmel Studio,应该检查连接到4个方向倾斜传感器(上,下,左,右)的PORTD上的引脚2和3,然后为每个方向点亮4个不同的LED。LED连接在PORTB上。
代码:

#include <avr/io.h>

#include <util/delay.h>

#ifndef F_CPU
#define F_CPU   16000000UL
#endif



//// define input sensor on PORT D
//
//#define tilt_S1 (PIND&(1<<2))
//#define tilt_S2 (PIND&(1<<3))
//
////define output LEDs on PORT B
//
//#define LED_U (PINB&(1<<0))
//#define LED_D (PINB&(1<<1))
//#define LED_L (PINB&(1<<2))
//#define LED_R (PINB&(1<<3))



int main(void)
{
    DDRD =0x00; //port d as input
    DDRB =0xFF; //port b as out
    
    
    while (1)
    {
        //int pos = GetTiltPos();     //get current sensor position
        
        
        if ( ( (PIND & (1<<2))==0 ) && ((PIND & (1<<3))==0 ) )  //Up (North) [S1=0, S2=0]
        {
            PORTB |=  1<<PINB0;    //up   turn on TOP led only
            PORTB &= ~(1<<PINB1); //down
            PORTB &= ~(1<<PINB2); //left 
            PORTB &= ~(1<<PINB3);  //right
        }
        
        
        else if (((PIND & (1<<2))==1 ) && ((PIND & (1<<3))==0 ))   //Left (West)  [
        {
            PORTB &=  ~(1<<PINB0);    //up   
            PORTB &=  ~(1<<PINB1);    //down
            PORTB |=   1<<PINB2;       //left       turn on LEFT led only
            PORTB &=  ~(1<<PINB3);    //right
        }
        
        else if (((PIND & (1<<2))==0) && ((PIND & (1<<3))==1))    //Right (East)
        {
            PORTB &= (~(1<<PINB0));    //up   
            PORTB &= (~(1<<PINB1));    //down
            PORTB &= (~(1<<PINB2));    //left
            PORTB |=  (1<<PINB3);       //right    turn on RIGHT led only
        }
        else if ( ((PIND & (1<<2))==1 ) && ((PIND & (1<<3))==1 ) )     //Down (South)
        {
            PORTB &= ~(1<<PINB0);      //up   
            PORTB |=   1<<PINB1;         //down    turn on BOTTOM led only
            PORTB &= ~(1<<PINB2);      //left
            PORTB &= ~(1<<PINB3);      //right
        }
        
    }
}

//int GetTiltPos()   //function to determine position of sensor
//{
    //int S1 = 1<<PIND2;
    //int S2 = 1<<PIND3;
    //int R = ((S1<<1)| S2) ;
    //return R;
//
//}

我尝试先定义LED和传感器,但不起作用,所以我尝试直接从引脚读取,但也不起作用,我不明白为什么。此代码导致上部LED始终打开。使用的传感器是4方向倾斜传感器RPI-1031

zqdjd7g9

zqdjd7g91#

表达式(PIND & (1<<2))==1永远不会为真。(PIND & (1<<2))的结果将为0或8(1<<2)。避免此问题的简单方法是始终检查是否等于零,例如(PIND & (1<<2)) != 0

9udxz4iz

9udxz4iz2#

1.您从PINB读取,而不是从**PIND**读取(例如:(PINB & (1<<2)))- i应为(PIND & (1<<2))
1.您没有将端口D设置为输入,因为|=并不像您想象的那样工作

DDRD |=0x00; //port d as input

此行不执行任何操作。如果要将寄存器清零,则需要:

DDRD = 0;

或者如果您只需要将寄存器上的某些位清零(例如位1、3和5)

DDRD &= ~((1 << 1) || (1 << 3) | (1 << 5));

相关问题