Skip to content

Instantly share code, notes, and snippets.

@tahayparker
Created May 14, 2026 10:28
Show Gist options
  • Select an option

  • Save tahayparker/0c2f1cea309f3fe0517cbdb9921974d8 to your computer and use it in GitHub Desktop.

Select an option

Save tahayparker/0c2f1cea309f3fe0517cbdb9921974d8 to your computer and use it in GitHub Desktop.
#define F_CPU 1000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <stdint.h>
#include <stdio.h>
// 2400 baud @ 1 MHz: UBRR = F_CPU/(16*BAUD) - 1 = 25
#define UBRR_VAL 25
void serial_init(void)
{
UCSRA = 0x00;
UCSRB = (1 << TXEN);
UCSRC = (1 << URSEL) | (1 << UCSZ1) | (1 << UCSZ0); // async, 8N1
UBRRL = UBRR_VAL;
UBRRH = 0x00;
}
int serial_send(char c, FILE *stream)
{
while (!(UCSRA & (1 << UDRE)));
UDR = c;
return 0;
}
FILE uart_out = FDEV_SETUP_STREAM(serial_send, NULL, _FDEV_SETUP_WRITE);
void adc_init(void)
{
DDRA &= ~(1 << DDA6); // PA6 as input
PORTA &= ~(1 << PA6); // no pull-up
ADMUX = (1 << REFS0) | (1 << MUX1) | (1 << MUX0); // AVcc ref, ADC6
ADCSRA = (1 << ADEN) | (1 << ADPS1) | (1 << ADPS0); // enable, /8 prescaler
}
uint16_t adc_read(void)
{
ADCSRA |= (1 << ADSC);
while (ADCSRA & (1 << ADSC));
uint8_t low = ADCL;
uint8_t high = ADCH;
return ((uint16_t)high << 8) | low;
}
int main(void)
{
serial_init();
stdout = &uart_out;
adc_init();
adc_read(); // discard first result
uint16_t digital;
uint32_t mv;
while (1)
{
digital = adc_read();
mv = ((uint32_t)digital * 5000UL) / 1024UL;
printf("ADC Digital Value = %4u | Input Voltage = %4lu mV\r\n",
digital, (unsigned long)mv);
_delay_ms(500);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment