Code Example

int RightVal = 0;           // variable to store the value read
int LeftVal = 0;            // variable to store the value read 
boolean sw1;     // variable to store the read value
boolean sw2;


void Forward(){ 
PORTD = B00100100;/* Go Forward*/
delay(10);
}

void TurnRight(){
PORTD = B00010100;  /* Turn Right*/  
delay(800);
PORTD = B00000000;  /* Briefly Stop*/ 
delay(5);
}

void TurnLeft(){
PORTD = B00101000;  /* Turn Left*/  
delay(500);
PORTD = B00000000;  /* Briefly Stop*/ 
delay(5);
}

void setup()
{
DDRD = DDRD | B11111100; //Data Direction Register for Port D
DDRB = DDRB | B00000011; //Data Direction Register for Port B
/* This is the same as written above
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT); 
  pinMode(4, OUTPUT); 
  pinMode(5, OUTPUT); 
  pinMode(6, OUTPUT); 
  pinMode(7, OUTPUT); 
  pinMode(8, OUTPUT); 
  pinMode(9, OUTPUT);
  pinMode(10, INPUT); 
  pinMode(11, INPUT); 
  */

}
 
void loop()
{
      RightVal = analogRead(0);    // read the input pin 0
      LeftVal = analogRead(1);     // read the input pin 1
      sw1=digitalRead(10);
      sw2=digitalRead(11);

      if (sw2 == false){
          TurnRight();
          } 

      if (sw1 == false){
          TurnLeft();
          } 
      
      if (RightVal > 400){
          PORTB = B00000001;
          TurnLeft();
          } 

      if (LeftVal > 400 ){
          PORTB = B00000010;        
          TurnRight();
          } 

      if (RightVal <= 401 && LeftVal <= 401){
          PORTB = B00000000;
          Forward();
          }  
          }