-3

I am new to AVR programming, and I am trying to implement a sharp right turn using atmega8. I was able to implement the straight line path but cannot implement a sharp right turn. Here is my code:

`#include <avr/io.h>
#include<util/delay.h>

int main(void)
{
    DDRC=0b00000000;
    DDRB=0b11111111;
    int count=1,right=1;
    while(1)
    {
        if((PINC&=0b00011111)==0b00000000)
        {
            PORTB=0b00000110;
     }
    else if((PINC&=0b00011111)==0b00001110)
    {
        PORTB=0&00100111;
    }
    else if((PINC&=0b00011111)==0b00001100)
    {
        PORTB=0b00000111;
    }
    else if((PINC&=0b00011111)==0b00000110)
    {
        PORTB=0b00100110;
    }
    else if((PINC&=0b00011111)==0b00001111)
    {
        if(count)
        {
        PORTB=0b0010011;
        _delay_ms(200);
        count--;
        }       
        else if(((PINC&=0b00011111)==0b00000110)&&~(count))
        {
            PORTB=0B00000111;
        }           

    }
    else if((PINC&=0b00011111)==0b00011110)
    {
        if(right)
        {
            PORTB=0b0010011;
            _delay_ms(200);
            right--;
        }
        else if(((PINC&=0b00011111)==0b00000110)&&~(right))
        {
            PORTB=0B00100110;
        }

    }
    }   
}

This doesn't seem to work at all for right and left turns. Any idea where I am going wrong?

  • difficult to give an answer without understanding what kind of hardware you use ... how many sensors do you use ... 5? Instead of lot of if's try subtracting the actually read value from the "center value "01110" and work with the difference ... mind the states 10000 and 00001 though where the robot goes over the edge. – MikeD Sep 26 '14 at 07:31
  • that code is a mess. you should really `#define` some constants or declare some `inline` functions for checking states of Inputs (eg `static inline bool RightSensorSensesLine(){return PINC&0b00011111;} `. How should we understand your code with all these messy, equal looking binary literals without understanding the meaning of its bits? – vlad_tepesch Sep 26 '14 at 07:58

1 Answers1

1

Without understanding your Program (see my Comment above) iam guessing it is because you permanently write to your PIN-regsiters in the if-clauses.

PINC&=0b00011111 means:

  • read PINC-value
  • binary AND it with 0b00011111
  • write the result back to PINC

Depending on which AVR your code is running you toggle the output by writing a 1 to a PINX-register bit. If DDR is configured to input you toggle the pullups. This is true for the newer AVR-cores. For the old one its undefined behavior to write to the PIN-registers as they are defined as read-only.

vlad_tepesch
  • 6,681
  • 1
  • 38
  • 80