This C code, Atmel Studio, is supposed to check pins 2 and 3 on PORTD which is connected to a 4 direction tilt sensor (Up, down, left, right) then lights up 4 different LEDs for each direction. LEDs are connected on PORTB.
code:
#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;
//
//}
i tried defining the LEDs and sensors first, but that didn't work so i tried reading from the pin directly But that wont work either and I don't understand why. This code results in the upper LED to be always ON. the sensor used is the 4 direction tilt sensor RPI-1031
The expression
(PIND & (1<<2))==1
will never be true. The result of(PIND & (1<<2))
will either be 0 or 4 (1<<2
). An easy way to avoid this issue is to always check for equal or not equal to zero, such as(PIND & (1<<2)) != 0
.