#include <Servo.h> // Included as per package allowance
// Define pin assignments:
const int ledPin = 6; // PWM output for led1
const int potPin = A0; // Analog input from pot1
// Bar-graph segment pins mapped to digital pins for bargraph1 (segments A1-A10)
const int barPins[10] = {22, 23, 24, 25, 26, 27, 28, 29, 30, 31};
// Variables used for LED blinking at 0.25 Hz (2 sec on, 2 sec off)
unsigned long lastBlinkTime = 0;
bool blinkState = false;
void setup() {
// Initialize led1 pin.
pinMode(ledPin, OUTPUT);
analogWrite(ledPin, 0); // initially off
// Initialize bar graph segment pins and turn them off.
for (int i = 0; i < 10; i++) {
pinMode(barPins[i], OUTPUT);
digitalWrite(barPins[i], LOW);
}
}
void loop() {
// Read the potentiometer value (0-1023)
int potValue = analogRead(potPin);
// Determine how many segments to light:
// 0-102 means 0 segments; 103-204 means 1 segment; ...; 921-1023 means 10 segments.
int numSegments = 0;
if (potValue <= 102) {
numSegments = 0;
} else {
numSegments = ((potValue - 103) / 102) + 1; // integer division produces the appropriate count
if (numSegments > 10) {
numSegments = 10;
}
}
// Update the bar graph: turn on the first numSegments, turn off remaining segments.
for (int i = 0; i < 10; i++) {
if (i < numSegments) {
digitalWrite(barPins[i], HIGH);
} else {
digitalWrite(barPins[i], LOW);
}
}
// Control the LED behavior
// If the potentiometer is at its maximum value then blink the LED.
if (potValue == 1023) {
unsigned long currentMillis = millis();
// Check if it’s time to toggle the LED (every 2000 milliseconds)
if (currentMillis - lastBlinkTime >= 2000) {
lastBlinkTime = currentMillis;
blinkState = !blinkState;
digitalWrite(ledPin, blinkState ? HIGH : LOW);
}
} else {
// If not at maximum pot value, then use analogWrite to set LED brightness proportionally
// Reset blinking timer in case we were blinking previously.
lastBlinkTime = millis();
int brightness = map(potValue, 0, 1023, 0, 255);
analogWrite(ledPin, brightness);
}
}