2

I'm trying to use the Arduio Uno in pure C because I can't use the Arduino IDE for my senior design project. I've succeeded in getting the serial communication to work, the digital outputs/inputs, and the analog inputs, to an extent. I'm getting a reading off the analog input, but most of them are 20,000+, which is way to high. This is supposedly a 10 bit ADC, and I'm only trying to use 8 bits. Why is my resulting read 100X what the highest supposedly is?

void init_aio(){
      DIDR0 = 0x00;           //Digital input disabled on all ADC ports
      PRR &= ~(1<<PRADC);     //ADC turned on
      ADMUX = 0x60;           //AVcc, right adjusted, ADC0 pin
      ADCSRA = 0xcF;          //ADC Enabled, no auto trigger, Iterrupt enabled, 128 prescaller
}

int read_analog(){
    reading = APin0;
    ADCSRA |= 1<<ADSC; //conversion start
    reading = abs(reading);
    return reading;
}

The only thing I can think of is that I'm using "int reading_str = itoa(reading, buffer, 10);" to make it a printable value. When I print reading directly, it prints garbage to the terminal. (char buffer[100]; is what buffer is)

The Uno uses an Atmega328P: www.atmel.com/Images/doc8161.pdf‎

Thanks for any help.

2
  • Try masking to 10 bits, i.e. value & 0x3FF; the top 6 bits may not be initialised to zero. You can then check if the input is as expected by tying the analog pin to ground. Commented Oct 22, 2013 at 15:15
  • Awesome! That was it. Thanks a lot! Want to make this an answer to get a vote? Commented Oct 22, 2013 at 15:18

1 Answer 1

1

The top bits of the ADC aren't zero-initialised, so you need to manually mask them away:

reading &= 0x3FF; // binary 0000001111111111, i.e. ten bits for ADC

You can then verify that this is correct by tying your analog pin to ground and Vref respectively, and checking that the resulting values match expectations.

In case anyone else runs into the same problem, using a different implementation of reading the ADC, ensure that your endianness and bit-ordering are correct.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.