0
\$\begingroup\$

The problem is that I am unable to read from multiple ADC channels (atmega8-au). The code works fine if only one channel is used eg. ADC0, however, if the second channel ADC1 is used then the value of readADC1 is equal to readADC0.

What should I do this to fix the problem? Might it be related to resetting the ADMUX bits?

The related code:

#include <avr/io.h>

unsigned int threshold = 900;
volatile unsigned int sensor_left = 0;
volatile unsigned int sensor_center = 0;
volatile unsigned int sensor_right = 0;

void init()
{
    DDRD |= 1 << PORTD0;
    DDRD |= 1 << PORTD1;

    ADCSRA |= (1 << ADEN);
    ADCSRA |= (1 << ADPS2) | (0 << ADPS1) | (0 << ADPS0); //1MHz / 16 = 62.5kHz
}

unsigned int readADC0()
{
    ADMUX |= (0 << REFS1) | (1 << REFS0);
    ADMUX |= (0 << ADLAR);
    ADMUX |= (0 << MUX3) | (0 << MUX2) | (0 << MUX1) | (0 << MUX0);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC));
    return ADC;
}

unsigned int readADC1()
{
    ADMUX |= (0 << REFS1) | (1 << REFS0);
    ADMUX |= (0 << ADLAR);
    ADMUX |= (0 << MUX3) | (0 << MUX2) | (0 << MUX1) | (1 << MUX0);
    ADCSRA |= (1 << ADSC);
    while (ADCSRA & (1 << ADSC));
    return ADC;
}

int main(int argc, char* argv)
{
    init();

    while (1) {    
        sensor_left = readADC1();
        sensor_center = readADC0(); //false results if enabled

        if (sensor_left < threshold) {
            PORTD |= 1 << PORTD0;
        } else {
            PORTD &= ~(1 << PORTD0);
        }

        if (sensor_center < threshold) {
            PORTD |= 1 << PORTD1;
        } else {
            PORTD &= ~(1 << PORTD1);
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ And we are just supposed to guess what hardware is involved? \$\endgroup\$ – PlasmaHH Apr 21 '17 at 9:48
  • \$\begingroup\$ Updated, it's atmega8-au @PlasmaHH \$\endgroup\$ – sitilge Apr 21 '17 at 9:50
1
\$\begingroup\$

I think the issue is the way you set the value of ADMUX. By using |= you are not able to set the value of a bit to 0, only to 1. So when you want to set the value of the bit MUX0 to 0 it is still 1 from the previous assignment (1 | 0 == 1). Try setting each bit to the desired value (for this you cat find tons of tutorials online about bitwise operations: http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all ).

\$\endgroup\$
  • \$\begingroup\$ Ahh, my bad. That logical or got me :D thank you for the correction. \$\endgroup\$ – sitilge Apr 21 '17 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.