Full program — ADC, PWM and UART
Integrating AVR peripherals
In this practical you will combine three peripherals into one embedded C application. A potentiometer provides an analogue voltage, the ADC digitises it, Timer0 uses the reading to control LED brightness, and the USART reports the measurements to a serial terminal.
You will also separate the programme into a header, an implementation file and a main programme, then extend the design through four independent exercises.
Practical Checklist
{{%track-checklist}}
1. From Arduino abstractions to peripheral registers
The Arduino implementation combines three operations in a few function calls:
const int analogPin = A0;
const int pwmPin = 6;
void setup() {
pinMode(pwmPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int adcValue = analogRead(analogPin);
int pwmValue = map(adcValue, 0, 1023, 0, 255);
analogWrite(pwmPin, pwmValue);
Serial.print("ADC Value: ");
Serial.print(adcValue);
Serial.print(" | PWM Value: ");
Serial.println(pwmValue);
delay(250);
}
| Arduino operation | Register-level equivalent |
|---|---|
analogRead(A0) | Select ADC0 in ADMUX, start conversion with ADSC, read ADC |
analogWrite(6, value) | Configure Timer0 in TCCR0A/B; write OCR0A |
Serial.begin(9600) | Configure UBRR0H/L, UCSR0B and UCSR0C |
Serial.print(...) | Wait for UDRE0, then write bytes to UDR0 |
2. Create the multi-file project
-
Create the project directory and enter it.
mkdir -p ~/embeddedC/adc2pwm cd ~/embeddedC/adc2pwm -
Create three source files and a Makefile.
touch adc2pwm.c header.c header.h Makefile- adc2pwm/
- adc2pwm.c
- header.c
- header.h
- Makefile
- adc2pwm/
3. Define the peripheral interface in header.h
-
Enter the following code into
header.h.#ifndef ADC2PWM_HEADER_H #define ADC2PWM_HEADER_H #include <stdint.h> #ifndef F_CPU #define F_CPU 16000000UL #endif #define UART_BAUD 9600UL #define UART_UBRR (F_CPU / (16UL * UART_BAUD) - 1UL) void UART_Init(void); void UART_Print(const char *text); void ADC_Init(void); uint16_t ADC_Read(uint8_t channel); void PWM_Init(void); #endif
4. Implement the peripheral functions in header.c
-
Add the UART, ADC and PWM functions to
header.c.#include "header.h" #include <avr/io.h> void UART_Init(void) { UCSR0A = 0; // Normal asynchronous speed (U2X0 = 0) UBRR0H = (uint8_t)(UART_UBRR >> 8); UBRR0L = (uint8_t)UART_UBRR; UCSR0C = (1 << UCSZ01) | (1 << UCSZ00); // 8N1 UCSR0B = (1 << TXEN0); // Transmit only } void UART_Print(const char *text) { while (*text != '\0') { while ((UCSR0A & (1 << UDRE0)) == 0) { // Wait for an empty transmit data buffer. } UDR0 = (uint8_t)*text++; } } void ADC_Init(void) { ADMUX = (1 << REFS0); // AVcc reference, ADC0 ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // ADC clock / 128 } uint16_t ADC_Read(uint8_t channel) { ADMUX = (ADMUX & 0xF0) | (channel & 0x0F); ADCSRA |= (1 << ADSC); while (ADCSRA & (1 << ADSC)) { // Wait for the conversion to complete. } return ADC; // Combined 10-bit result (ADCL then ADCH) } void PWM_Init(void) { DDRD |= (1 << DDD6); // Pin PD6 is OC0A / Arduino D6 OCR0A = 0; TCCR0A = (1 << COM0A1) | (1 << WGM01) | (1 << WGM00); TCCR0B = (1 << CS01) | (1 << CS00); // /64 Fast PWM }
5. Combine ADC, PWM and UART in adc2pwm.c
-
Write the main programme in
adc2pwm.c.#include "header.h" #include <avr/io.h> #include <stdlib.h> #include <util/delay.h> int main(void) { char buffer[10]; UART_Init(); ADC_Init(); PWM_Init(); while (1) { uint16_t adc_value = ADC_Read(0); uint8_t pwm_value = (uint8_t) (((uint32_t)adc_value * 255UL) / 1023UL); OCR0A = pwm_value; UART_Print("ADC Value: "); utoa(adc_value, buffer, 10); UART_Print(buffer); UART_Print(" | PWM Value: "); utoa(pwm_value, buffer, 10); UART_Print(buffer); UART_Print("\r\n"); _delay_ms(250); } }
6. Create the Makefile, build and upload
-
Add the following to
Makefile. Each recipe command must begin with an actual Tab character, not spaces.MCU = atmega328p F_CPU = 16000000UL TARGET = adc2pwm CC = avr-gcc OBJCOPY = avr-objcopy AVRDUDE = avrdude CFLAGS = -Os -Wall -Wextra -mmcu=$(MCU) -DF_CPU=$(F_CPU) SOURCES = adc2pwm.c header.c OBJECTS = $(SOURCES:.c=.o) # Change the configuration path and COM port for your computer. AVRDUDECONFIG = C:/ProgramData/arduino-ide-v2/Local/Arduino15/packages/arduino/tools/avrdude/8.0.0-arduino1/etc/avrdude.conf PORT = COM6 BAUD = 115200 .PHONY: all upload clean all: $(TARGET).hex $(TARGET).hex: $(TARGET).elf $(OBJCOPY) -O ihex -R .eeprom $< $@ $(TARGET).elf: $(OBJECTS) $(CC) $(CFLAGS) -o $@ $^ %.o: %.c header.h $(CC) $(CFLAGS) -c -o $@ $< upload: $(TARGET).hex $(AVRDUDE) -C "$(AVRDUDECONFIG)" -c arduino -p $(MCU) -P $(PORT) -b $(BAUD) -U flash:w:$(TARGET).hex:i clean: rm -f $(OBJECTS) $(TARGET).elf $(TARGET).hex -
Confirm the serial port, then build the application.
Get-CimInstance Win32_SerialPort | Select-Object DeviceID,Name
wmic path Win32_SerialPort get Caption,Name,DeviceIDwmicmay not be installed on newer Windows releases; use PowerShell if unavailable.
make clean makeCheck that the resulting
adc2pwm.hexexists before uploading. -
Close any serial monitor using the port, upload the firmware, then reconnect at 9600 baud, 8N1.
make upload
-
Exptected output
ADC Value: 0 | PWM Value: 0 ADC Value: 256 | PWM Value: 63 ADC Value: 512 | PWM Value: 127 ADC Value: 768 | PWM Value: 191 ADC Value: 1023 | PWM Value: 255
7. Independent exercises
Try each extension before opening its reference solution. The examples build on the baseline header.h, header.c and adc2pwm.c; where appropriate, the solution shows only the functions or loop that must change.
Exercise 1 — Vary PWM frequency with ADC input
-
Update the main loop to select the prescaler from the ADC range.
-
Change only the
CS02:CS00clock-select bits inTCCR0B. -
Print the selected prescaler and approximate frequency, then compare what you observe on an oscilloscope or logic analyser.
Use
if / else if / elseto divide ADC readings into the four ranges. For Timer0, the relevant clock-select masks are:(1 << CS02) | (1 << CS00) // /1024 (1 << CS02) // /256 (1 << CS01) | (1 << CS00) // /64 (1 << CS01) // /8Keep the duty-cycle setting fixed if you want to isolate frequency changes: e.g., set
OCR0A = 127.Replace the baseline main loop with the following approach (retain its existing initialisation and
bufferdeclaration):while (1) { uint16_t adc_value = ADC_Read(0); uint16_t prescaler; const char *frequency; if (adc_value < 256) { TCCR0B = (1 << CS02) | (1 << CS00); prescaler = 1024; frequency = "61.04"; } else if (adc_value < 512) { TCCR0B = (1 << CS02); prescaler = 256; frequency = "244.14"; } else if (adc_value < 768) { TCCR0B = (1 << CS01) | (1 << CS00); prescaler = 64; frequency = "976.56"; } else { TCCR0B = (1 << CS01); prescaler = 8; frequency = "7812.50"; } OCR0A = 127; // Keep duty approximately constant. UART_Print("Prescaler: "); utoa(prescaler, buffer, 10); UART_Print(buffer); UART_Print(" | Frequency (Hz): "); UART_Print(frequency); UART_Print("\r\n"); _delay_ms(250); }
Exercise 2 — Control PWM using UART commands
-
Enable the UART receiver and read incoming characters.
-
Decide how to avoid the ADC loop immediately overwriting any manual PWM change.
-
Test repeated
+and-commands, including the upper and lower limits.In
UART_Init(), enableRXEN0as well asTXEN0. TheRXC0flag indicates an unread received byte:if (UCSR0A & (1 << RXC0)) { char command = (char)UDR0; // Interpret command here. }One design is to switch into manual mode on
+or-, witharestoring ADC-controlled automatic mode.First, change
UART_Init()inheader.c:UCSR0B = (1 << RXEN0) | (1 << TXEN0);Then replace the baseline
while (1)loop inadc2pwm.cwith:uint8_t pwm_value = 0; uint8_t automatic = 1; while (1) { uint16_t adc_value = ADC_Read(0); if (UCSR0A & (1 << RXC0)) { char command = (char)UDR0; if (command == '+') { automatic = 0; pwm_value = pwm_value > 245 ? 255 : pwm_value + 10; } else if (command == '-') { automatic = 0; pwm_value = pwm_value < 10 ? 0 : pwm_value - 10; } else if (command == 'a') { automatic = 1; } } if (automatic) { pwm_value = (uint8_t) (((uint32_t)adc_value * 255UL) / 1023UL); } OCR0A = pwm_value; UART_Print(automatic ? "AUTO" : "MANUAL"); UART_Print(" | PWM: "); utoa(pwm_value, buffer, 10); UART_Print(buffer); UART_Print("\r\n"); _delay_ms(50); }This reuses the original function declarations and initialisation. Commands are polled once per loop, so fast bursts can overrun the UART receive buffer; interrupts or more frequent polling would improve reliability.
Exercise 3 — Two ADC channels and two PWM outputs
-
Configure PD5 as an output and enable non-inverting OC0B in
TCCR0A. -
Read ADC0 and ADC1 in turn, then update
OCR0AandOCR0B. -
Observe whether the two LEDs respond independently.
Timer0 has two compare channels, A and B, but they share one timer frequency. To enable OC0B, add
(1 << COM0B1)toTCCR0Aand setDDRDbitDDD5.The ADC's
MUXbits select the input channel. If switching between sources with substantial impedance differences, allow settling or discard a conversion after changing the channel.Change
PWM_Init()inheader.cto:void PWM_Init(void) { DDRD |= (1 << DDD6) | (1 << DDD5); OCR0A = 0; OCR0B = 0; TCCR0A = (1 << COM0A1) | (1 << COM0B1) | (1 << WGM01) | (1 << WGM00); TCCR0B = (1 << CS01) | (1 << CS00); }For this exercise, if the input channels are changed, discard the first reading after switching channels:
uint16_t ADC_Read(uint8_t channel) { uint8_t selection = channel & 0x0F; if ((ADMUX & 0x0F) != selection) { ADMUX = (ADMUX & 0xF0) | selection; ADCSRA |= (1 << ADSC); while (ADCSRA & (1 << ADSC)) { } (void)ADC; // Discard reading after channel change. } ADCSRA |= (1 << ADSC); while (ADCSRA & (1 << ADSC)) { } return ADC; }Replace the baseline main loop with:
while (1) { uint16_t adc0 = ADC_Read(0); uint16_t adc1 = ADC_Read(1); uint8_t pwm0 = (uint8_t)(((uint32_t)adc0 * 255UL) / 1023UL); uint8_t pwm1 = (uint8_t)(((uint32_t)adc1 * 255UL) / 1023UL); OCR0A = pwm0; OCR0B = pwm1; UART_Print("ADC0="); utoa(adc0, buffer, 10); UART_Print(buffer); UART_Print(" PWM0="); utoa(pwm0, buffer, 10); UART_Print(buffer); UART_Print(" | ADC1="); utoa(adc1, buffer, 10); UART_Print(buffer); UART_Print(" PWM1="); utoa(pwm1, buffer, 10); UART_Print(buffer); UART_Print("\r\n"); _delay_ms(250); }
Exercise 4 — Internal temperature sensor controls brightness
-
Configure
ADMUXto use the internal reference and temperature-sensor channel. -
Allow the reference to settle and discard an initial conversion before taking measurements.
-
Calculate a rough temperature using the example reference of ADC = 352 at 25°C and approximately one ADC count per °C.
-
Map the estimated temperature to an LED brightness range, and print the reading once per second.
The internal temperature-sensor setting uses
REFS1:REFS0 = 11andMUX3:0 = 1000. For the illustrative linear approximation:\[ T_{estimate}(^\circ\mathrm{C}) \approx 25 + (ADC - 352) \]
Choose a practical brightness mapping, such as 20°C → 0 and 40°C → 255, with clamping outside this range. The mapping is an application decision, not a datasheet requirement.
Replace
ADC_Init()inheader.cwith:void ADC_Init(void) { ADMUX = (1 << REFS1) | (1 << REFS0) | (1 << MUX3); ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); }In
adc2pwm.c, replace the main loop with this temperature-oriented logic. The existingbuffer,UART_Init(),ADC_Init()andPWM_Init()remain in place. The delay library is already included:_delay_ms(2); // Reference settling (illustrative). (void)ADC_Read(8); // Discard first conversion. while (1) { uint16_t raw = ADC_Read(8); int16_t temperature = (int16_t)raw - 352 + 25; // Map 20–40 C to 0–255; clamp the result. int32_t level = ((int32_t)temperature - 20) * 255 / 20; if (level < 0) level = 0; if (level > 255) level = 255; OCR0A = (uint8_t)level; UART_Print("Estimated temperature: "); itoa(temperature, buffer, 10); UART_Print(buffer); UART_Print(" C | PWM: "); utoa((uint8_t)level, buffer, 10); UART_Print(buffer); UART_Print("\r\n"); _delay_ms(1000); }