Atmega328p - Robot Sumo code not working?

Viewed 26

I use an Atmega328p, programmed with Atmel Studio 7.0, as a processing unit and two tcr5000 line sensors, one on the front of the robot and one on the back. To control the motors I use an L293D. When I test the code the robot even moves, but when the tcr5000 sensors detect the black colour it does not invert the direction of march as it was supposed to.

I have already checked and the voltage values that come out of the sensors are correct, voltages very close to 5V for the white colour and reduced voltages for the black colour, so the problem must be with the code.

The code I am using is the following:

#define F_CPU 16000000
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

uint8_t flagdadosrecebidos = 0;
uint8_t flagligado = 0;
uint8_t flagfe = 0;
uint8_t flagfd = 0;
uint8_t flagte = 0;
uint8_t flagtd = 0;
uint8_t flagatuarmotores = 0;
uint8_t i;
uint8_t ligado = 0;
int fe = 0;
int fd = 0;
int te = 0;
int td = 0;
int feito = 0;

unsigned int MaxSVal = 716;


void init(void)
{
    ADMUX  |= (1 << REFS0);
    ADCSRA |= (1 << ADEN)|(1 << ADPS2)|(1 << ADPS1)|(1<<ADPS0);
    
    DDRD |= (1<<PORTD3)|(1<<PORTD5)|(1<<PORTD6)|(1<<PORTD7);
    DDRB |= (1<<PORTB0)|(1<<PORTB3)|(1<<PORTB4)|(1<<PORTB5);
    TCCR2A |=(1 << COM2A1) | (1 << COM2B1) | (1 << WGM21) | (1 << WGM20);
    TCCR2B |= (1<<CS20);
    sei();
}

void ler_sl(void)
{
    ADMUX = 0B01000000;
    switch (ADMUX){ // vamos ler os valores recebidos nos pins analogicos para ver se estamos no branco ou no preto
        
        case(0B01000000): // ler o primeiro sensor que se vai encontrar em frente na esquerda
        ADCSRA |= (1 << ADSC);
        while ((ADCSRA & (1<<ADSC)) !=0)
        {
            if (ADCH < MaxSVal) // se estiver a ver preto ADCH > 175 a flag do sensor ativa e posteriormente alterara o comportamento das rodas
            {
                fe = 1;
                }else{
                fe = 0;
            }
        }
        ADMUX = 0B01000010;
        
        case(0B01000010): // ler o terceito sensor, traseira esquerda
        ADCSRA |= (1 << ADSC);
        while ((ADCSRA & (1<<ADSC)) !=0)
        {
            if (ADCH < MaxSVal)
            {
                td = 1;
                }else{
                td = 0;
            }
        }
        ADMUX = 0B01000000;
    }

}

void atuarmotores(void){
    if ((fe == 1))
    {
        PORTD = (1<<PORTD7);
        PORTB = (1<<PORTB4);
        OCR2A = 255;
        OCR2B = 255;
    }
    if ((td == 1))
    {
        PORTD = (1<<PORTD5);
        PORTB = (1<<PORTB5);
        OCR2A = 255;
        OCR2B = 255;
    }
}

int main(void)
{
    init();
    OCR2A = 255;
    OCR2B = 255;
    PORTD = (1<<PORTD5);
    PORTB = (1<<PORTB5);
    while (1)
    {

        ler_sl();
        atuarmotores();
    }
}
0 Answers
Related