MAS 863: How to Make (Almost) Anything
Analog to Digital Converter
ADCSRA register...................................................................................................
7 ADEN: Analog Digital Enable. Writing this bit to one enables the ADC.
6 ADSC: ADC Start Conversion
2:0 ADC: Analog digital clock prescaler Select Bits *fig1
ADMUX register....................................................................................................
6 REFS0 : This bit selects the voltage reference for the ADC. (1 - internal 0 - VCC)
5 ADLAR: ADC Left Adjust Result *fig.2
1:0 MUX: (Multiplexing) Analog Channel Selection Bits *fig.3
Fig 3 Analog Channel Selection Bits
All the other settings can be default, except you have to manually define which ADC pin you are using. For example
:| (0 << MUX3) | (0 << MUX2) | (1 << MUX1) | (1 << MUX0); // ADC3
The combination can be checked through the datasheet; It vaires from different microcontroller.
default is 0, and you don't need to write the part if it's defalut. For example:
| (0 << MUX3) | (0 << MUX2) | (1 << MUX1) | (1 << MUX0);
is the same as
| (1 << MUX1) | (1 << MUX0);
Another tricky part is the way to interpret the data. The data was stored in ADCL and ADCH. In Neil's example, raw data is sent out and interpreted in Python later on; Instead, Matt had an example to interprete to data in C code in microcontroller.
1. ADC (analog reading) code in Neil's code example
// init A/D
ADMUX = (0 << REFS2) | (0 << REFS1) | (0 << REFS0) // Vcc ref
| (0 << ADLAR) // right adjust
| (0 << MUX3) | (0 << MUX2) | (1 << MUX1) | (1 << MUX0); // ADC3
ADCSRA = (1 << ADEN) // enable
| (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // prescaler /128
// initiate conversion
ADCSRA |= (1 << ADSC);
// wait for completion
while (ADCSRA & (1 << ADSC));
// send result
chr = ADCL;
put_char(&serial_port, serial_pin_out, chr);
char_delay();
chr = ADCH;
put_char(&serial_port, serial_pin_out, chr);
char_delay();