My Arduino is reading information from my PC every second, but I also want a RGB LED to slowly fade through all the colours without being disrupted. But my Arduino cannot miss a reading either.
The PC triggers the reading, otherwise the Arduino won't look for a reading.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3f, 16, 2); // Adjust the I2C address if needed
unsigned long lastDataReceivedTime = 0;
const unsigned long backlightTimeout = 10000; // 10 seconds in milliseconds
// Define the pins for the RGB LED
const int redPin = 11; // Red LED connected to digital pin 9
const int greenPin = 9; // Green LED connected to digital pin 10
const int bluePin = 10; // Blue LED connected to digital pin 11
// Delay between color transitions
const int transitionDelay = 10; // Adjust this for the speed of the transition
unsigned long lastLEDTime = 0;
void setup() {
// Initialize the RGB pins as OUTPUT
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
digitalWrite(redPin, HIGH);
digitalWrite(greenPin, HIGH);
digitalWrite(bluePin, HIGH);
lcd.init();
lcd.clear();
Serial.begin(9600);
}
void loop() {
if (millis() - lastLEDTime >= transitionDelay) {
fadeFromToColor(0, 255, 255, 255, 0, 255); // Fade from Red to Green
fadeFromToColor(255, 0, 255, 255, 255, 0); // Fade from Green to Blue
fadeFromToColor(255, 255, 0, 0, 255, 255); // Fade from Blue to Red
lastLEDTime = millis();
}
if (Serial.available() > 0) {
lastDataReceivedTime = millis(); // Reset the timer
String cpuUsage = Serial.readStringUntil('\n');
String ramUsage = Serial.readStringUntil('\n');
String timeLog = Serial.readStringUntil('\n');
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(cpuUsage);
lcd.setCursor(0, 1);
lcd.print(ramUsage);
}
//else {
int sensorValue = analogRead(A0);
if (sensorValue < 300) {
lcd.noBacklight();
}
else {
if (millis() - lastDataReceivedTime >= backlightTimeout) {
lcd.noBacklight(); // Turn off the backlight
}
else {
lcd.backlight();
}
}
}
// Function to smoothly fade between two colors
void fadeFromToColor(int startRed, int startGreen, int startBlue, int endRed, int endGreen, int endBlue) {
for (int i = 0; i <= 255; i++) {
int redValue = map(i, 0, 255, startRed, endRed);
int greenValue = map(i, 0, 255, startGreen, endGreen);
int blueValue = map(i, 0, 255, startBlue, endBlue);
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
//delay(transitionDelay);
}
}
With that code the reading gets scrambled, and the LED goes through all the colours in a blink of an eye. I'm really lost with this.
This is a video for those interested:
386450645_6763448027075666_1721594536350718734_n.zip (985.9 KB)