Controlling LEDs with POT using atmega32
subratasarkar20
c_cpp
a year ago
1.3 kB
13
Indexable
/*
* ADC.cpp
*
* Created: 07-10-2024 12:17:59
* Author : subrs
*/
#include <avr/io.h>
void ADC_Init()
{
ADMUX = (1 << REFS0); // AVCC as reference, ADC0 selected
ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1); // Enable ADC, set prescaler to 64 (for 1MHz clock)
}
uint16_t ADC_Read(uint8_t channel)
{
ADMUX = (ADMUX & 0xF8) | (channel << MUX0); // Select the ADC channel (in this case, channel 0 for the potentiometer)
ADCSRA |= (1 << ADSC); // Start conversion
while (ADCSRA & (1 << ADSC)); // Wait for conversion to complete
return ADC; // Return the ADC result (10-bit value)
}
void LEDs_On(uint8_t num_leds)
{
// Turn on num_leds LEDs by setting PORTB
// If num_leds is 3, for example, 0b00000111 will be written to PORTB
PORTB = (1 << num_leds) - 1;
}
int main(void)
{
ADC_Init(); // Initialize ADC and set PORTB as output for the LEDs
DDRB = 0xFF; // Set all PORTB pins as output
uint16_t adc_value;
uint8_t led_count;
while (1)
{
adc_value = ADC_Read(0); // Read the ADC value from the potentiometer (channel 0)
// Map the ADC value (0 - 1023) to the number of LEDs (0 - 8)
led_count = adc_value / 146; // Divide 1024 by 8 to get 8 levels (128 steps per LED)
LEDs_On(led_count);
}
}
Editor is loading...
Leave a Comment