// Define pin numbers
const int ledPin = 8; // LED connected to GPIO 8
const int ledPin1 = 5; // Additional LED connected to GPIO 5
const int ledPin2 = 6; // LED connected to GPIO 6
const int ledPin3 = 7; // LED connected to GPIO 7
const int relayPin = 1; // Relay connected to GPIO 1
const int buttonPin = 9; // Button connected to GPIO 9
const int voltagePin = 2; // Voltage sensor connected to GPIO 2
// Variable to store button state
int buttonState = 0;
void setup() {
// Initialize the LED pins as outputs
pinMode(ledPin, OUTPUT);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(ledPin3, OUTPUT);
// Initialize the relay pin as an output
pinMode(relayPin, OUTPUT);
// Initialize the button pin as an input
pinMode(buttonPin, INPUT); // Use internal pull-up resistor
// Initialize the voltage sensor pin as an input
pinMode(voltagePin, INPUT);
// Start with the LEDs and relay off
digitalWrite(ledPin, LOW);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(relayPin, LOW);
// Start the serial communication to send the voltage readings to the PC
Serial.begin(115200);
delay(1000); // Wait for serial monitor to open
}
void loop() {
// Read the state of the push button
buttonState = digitalRead(buttonPin);
// Read the voltage from the voltage sensor
int analogValue = analogRead(voltagePin);
// Convert the analog value to voltage
float voltage = analogValue * (3.3 / 4095.0);
// Print the voltage to the serial monitor
Serial.print("Voltage: ");
Serial.print(voltage);
Serial.println(" V");
// Calculate the battery percentage
float batteryPercentage = (voltage / 3.3) * 100;
// Check if the button is pressed
if (buttonState == HIGH)
{
// Flash the LED based on battery percentage
if (batteryPercentage >= 40 && batteryPercentage <= 100) {
digitalWrite(ledPin2, HIGH); // LED on GPIO 6
delay(500);
digitalWrite(ledPin2, LOW);
delay(500);
} else if (batteryPercentage >= 20 && batteryPercentage < 40) {
digitalWrite(ledPin1, HIGH); // LED on GPIO 5
delay(500);
digitalWrite(ledPin1, LOW);
delay(500);
} else if (batteryPercentage >= 5 && batteryPercentage < 20) {
digitalWrite(ledPin3, HIGH); // LED on GPIO 7
delay(500);
digitalWrite(ledPin3, LOW);
delay(500);
} else {
// Turn off all LEDs if battery percentage is not in specified range
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
}
// Blink the LED connected to GPIO 8
digitalWrite(ledPin, HIGH);
delay(500);
digitalWrite(ledPin, LOW);
delay(500);
// Turn on the relay
digitalWrite(relayPin, HIGH);
}
else
{
// Ensure all LEDs and relay are off when button is not pressed
digitalWrite(ledPin, LOW);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
digitalWrite(ledPin3, LOW);
digitalWrite(relayPin, LOW);
}
// Small delay to prevent flooding the serial monitor
delay(1000);
}
Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1