It seems there are inconsistencies and possible errors within your code related to handling the range of mappedValue and mapping it appropriately to LED control. From your description, you've mapped your potentiometer's output from 65 to 337, but your code checks for thresholds above these values (e.g., 400, 333). Also, you want to divide your input range into parts to control six LEDs, which isn't correctly set up in the code you've given.
Here is a revised version of your update_leds function that correctly handles the range of mappedValue you specified. The function will proportionally turn on an increasing number of LEDs as the mappedValue increases:
#include <avr/io.h>
#include <stdint.h>
// Constants for LED bit positions in PORTD
#define led1 PD0
#define led2 PD1
#define led3 PD2
#define led4 PD3
#define led5 PD4
#define led6 PD5
// Function to turn off all LEDs
void turn_off_all_leds() {
PORTD &= ~((1<<led1) | (1<<led2) | (1<<led3) | (1<<led4) | (1<<led5) | (1<<led6));
}
// Function to update LEDs based on the mapped potentiometer value
void update_leds(uint16_t mappedValue) {
turn_off_all_leds();
// Calculate range divisions, assuming your desired range is 65 to 337
uint16_t range = 337 - 65;
uint16_t step = range / 6; // Divide the range by the number of LEDs
// Update LEDs based on mappedValue using step intervals
if (mappedFactor >= 5 * step + 65) {
PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4) | (1<<led5) | (1<<led6);
} else if (mappedFactor >= 4 * step + 65) {
PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4) | (1<<led5);
} else if (mappedFactor >= 3 * step + 65) {
PORTD |= (1<<led1) | (1<<led2) | (1<<led3) | (1<<led4);
} else if (mappedFactor >= 2 * step + 65) {
PORTD |= (1<<led1) | (1<<led2) | (1<<led3);
} else if (mappedFactor >= step + 65) {
PORTD |= (1<<led1) | (1<<led2);
} else {
PORTD |= (1<<led1);
}
}
Key Points and Changes:
- Corrected Range and Division: I adjusted the
if and else if conditions to suit scaled values from 65 to 337, dividing the range into equal parts corresponding to the number of LEDs.
- Updated Definitions: Constants (
led1, led2, etc.) define which bits of PORTD control each LED. Ensure these are set according to your hardware setup.
- Efficiency: The
turn_off_all_leds function clears previous LED states before setting new ones.
Make sure your port definitions (PD0, PD1, etc.) are assigned correctly to match how your LEDs are connected to your microcontroller. Also, ensure that the PORTD and pins are configured correctly for output elsewhere in your initialization code (possibly not shown here).