Adjusts smart light colors and intensity based on room mood via face AI Arduino
👤 Sharing: AI
```arduino
// Arduino Code for Smart Light Adjustment Based on Room Mood
// **Includes**
#include <Adafruit_NeoPixel.h> // Library for controlling NeoPixel LEDs
#include <SoftwareSerial.h> // Library for serial communication (for simulated Face-AI)
// **Configuration**
#define NUM_LEDS 16 // Number of LEDs in your NeoPixel strip
#define DATA_PIN 6 // Arduino pin connected to the NeoPixel data line
#define RX_PIN 2 // Arduino pin for receiving serial data (from simulated Face-AI)
#define TX_PIN 3 // Arduino pin for transmitting serial data (not used here, but necessary for SoftwareSerial)
// **Object Declarations**
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800); // Initialize NeoPixel object
SoftwareSerial faceAISerial(RX_PIN, TX_PIN); // Initialize SoftwareSerial for Face-AI communication
// **Global Variables**
int moodLevel = 0; // Represents the perceived mood (0-100). Simulated from Face-AI
int lastMoodLevel = -1; // Store the last mood level to prevent redundant updates.
// Function to map a mood value to a color and brightness level.
void moodToColor(int mood, int &red, int &green, int &blue, int &brightness) {
// Map mood (0-100) to color ranges and brightness. This is a simplified example.
// You can adjust these ranges to fine-tune the colors.
if (mood <= 25) { // Sad/Depressed (Cool Blues and low brightness)
red = 0;
green = 0;
blue = 255; // Light Blue
brightness = map(mood, 0, 25, 20, 70); // Lower brightness
} else if (mood <= 50) { // Neutral/Calm (Warm Whites and moderate brightness)
red = 255;
green = 240;
blue = 200; // Warm White
brightness = map(mood, 26, 50, 71, 150);
} else if (mood <= 75) { // Happy/Energetic (Bright Yellows and Greens)
red = 255;
green = 255;
blue = 0; // Yellow
brightness = map(mood, 51, 75, 151, 200);
} else { // Excited/Passionate (Warm Reds and High brightness)
red = 255;
green = 0;
blue = 0; // Red
brightness = map(mood, 76, 100, 201, 255); // Full brightness
}
// Ensure brightness remains within the valid range
brightness = constrain(brightness, 0, 255);
}
// Function to set all LEDs to a specific color and brightness.
void setColorAll(int red, int green, int blue, int brightness) {
for (int i = 0; i < NUM_LEDS; i++) {
strip.setPixelColor(i, strip.Color(red, green, blue));
}
strip.setBrightness(brightness); // Global brightness setting
strip.show();
}
void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
faceAISerial.begin(9600); // Initialize SoftwareSerial for Face-AI communication
strip.begin(); // Initialize NeoPixel strip
strip.show(); // Turn all LEDs off initially
Serial.println("Smart Light Initialized.");
}
void loop() {
// **Simulate Face-AI data**
// Check for incoming data from the simulated Face-AI
if (faceAISerial.available() > 0) {
String moodString = faceAISerial.readStringUntil('\n'); // Read the entire line until a newline character
moodString.trim(); // Remove leading/trailing whitespace
// Check if the string is not empty and can be converted to an integer.
if (moodString.length() > 0) {
int newMoodLevel = moodString.toInt(); // Convert the string to an integer
// Validate that the mood level is within the acceptable range (0-100).
if (newMoodLevel >= 0 && newMoodLevel <= 100) {
moodLevel = newMoodLevel;
Serial.print("Received Mood Level: ");
Serial.println(moodLevel);
} else {
Serial.println("Invalid Mood Level received. Must be between 0 and 100.");
}
} else {
Serial.println("Empty Mood Level received.");
}
}
// **Adjust LED Color Based on Mood Level**
if (moodLevel != lastMoodLevel) {
int red, green, blue, brightness;
moodToColor(moodLevel, red, green, blue, brightness);
setColorAll(red, green, blue, brightness);
Serial.print("Setting color: R=");
Serial.print(red);
Serial.print(" G=");
Serial.print(green);
Serial.print(" B=");
Serial.print(blue);
Serial.print(" Brightness=");
Serial.println(brightness);
lastMoodLevel = moodLevel; // Update the last mood level to prevent repeating updates.
}
delay(100); // Small delay to prevent overwhelming the serial port and Arduino.
}
```
**Explanation:**
1. **Includes:**
* `Adafruit_NeoPixel.h`: This library is essential for controlling the NeoPixel LED strip. You'll need to install it via the Arduino IDE's Library Manager. (Sketch -> Include Library -> Manage Libraries -> Search for "Adafruit NeoPixel")
* `SoftwareSerial.h`: This library allows you to create a second serial port on the Arduino. We use this to simulate communication with a "Face-AI" module that would theoretically be providing the mood level data.
2. **Configuration:**
* `NUM_LEDS`: Define the number of LEDs in your NeoPixel strip. Adjust this to match your physical setup.
* `DATA_PIN`: The Arduino pin connected to the data input of the NeoPixel strip. This is crucial.
* `RX_PIN` and `TX_PIN`: These are the pins used for the SoftwareSerial communication. `RX_PIN` receives data *from* the simulated Face-AI. `TX_PIN` sends data *to* the simulated Face-AI (though we don't actually send anything *to* it in this example).
3. **Object Declarations:**
* `Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);`: Creates an object named `strip` of the `Adafruit_NeoPixel` class. This object handles the control of your NeoPixel strip. The parameters are:
* `NUM_LEDS`: The number of LEDs.
* `DATA_PIN`: The data pin.
* `NEO_GRB + NEO_KHZ800`: Specifies the color order (Green, Red, Blue) and the communication frequency (800 kHz). This is a common setting, but check your NeoPixel's datasheet if you're not sure.
* `SoftwareSerial faceAISerial(RX_PIN, TX_PIN);`: Creates a `SoftwareSerial` object for serial communication with the (simulated) Face-AI.
4. **Global Variables:**
* `moodLevel`: An integer representing the perceived mood, ranging from 0 to 100. This value is *simulated* in this example, but in a real application, it would be received from an external sensor (like a face recognition system).
* `lastMoodLevel`: Stores the previously set mood level. This is used to avoid unnecessarily updating the LEDs if the mood hasn't changed.
5. **`moodToColor()` function:**
* This function is the core of the mood-to-color mapping. It takes the `mood` value (0-100) as input and sets the `red`, `green`, `blue`, and `brightness` values based on predefined mood ranges.
* It uses `if/else if/else` statements to map mood ranges to different color schemes:
* **Sad/Depressed:** Cool blues, low brightness.
* **Neutral/Calm:** Warm whites, moderate brightness.
* **Happy/Energetic:** Bright yellows and greens, higher brightness.
* **Excited/Passionate:** Warm reds, full brightness.
* `map(mood, range_min, range_max, target_min, target_max)`: This function re-maps a number from one range to another. For example, `map(mood, 0, 25, 20, 70)` maps the `mood` value (which is between 0 and 25 in the "Sad/Depressed" range) to a brightness value between 20 and 70. This creates a smooth transition in brightness as the mood changes within each range.
* `constrain(brightness, 0, 255);`: This ensures that the brightness value stays within the valid range (0-255).
6. **`setColorAll()` function:**
* This function takes the `red`, `green`, `blue`, and `brightness` values and sets all the LEDs in the NeoPixel strip to that color and brightness.
* `strip.setPixelColor(i, strip.Color(red, green, blue));`: Sets the color of the LED at index `i` to the specified RGB color.
* `strip.setBrightness(brightness);`: Sets the overall brightness of the entire strip. This is applied globally.
* `strip.show();`: This is the command that actually *sends* the color data to the NeoPixel strip, making the LEDs change color.
7. **`setup()` function:**
* `Serial.begin(9600);`: Initializes the main serial communication for debugging purposes. You can use the Serial Monitor in the Arduino IDE to see the output of `Serial.print()` statements.
* `faceAISerial.begin(9600);`: Initializes the SoftwareSerial communication for the simulated Face-AI.
* `strip.begin();`: Initializes the NeoPixel library. This *must* be called before you try to control the LEDs.
* `strip.show();`: Turns off all the LEDs initially.
8. **`loop()` function:**
* **Simulate Face-AI Data:**
* `if (faceAISerial.available() > 0)`: Checks if there is any data available to be read from the SoftwareSerial port (i.e., from the simulated Face-AI).
* `String moodString = faceAISerial.readStringUntil('\n');`: Reads the incoming data as a string until it encounters a newline character (`\n`). The simulated Face-AI is expected to send the mood level as a number followed by a newline.
* `moodString.trim();`: Removes any leading or trailing whitespace from the string (important to avoid parsing errors).
* `int newMoodLevel = moodString.toInt();`: Converts the string to an integer.
* **Input Validation:** The code includes crucial input validation:
* `if (moodString.length() > 0)`: Checks that the received string isn't empty.
* `if (newMoodLevel >= 0 && newMoodLevel <= 100)`: Checks that the converted integer is within the valid mood range (0-100).
* If the data is valid, `moodLevel` is updated with the new value, and a message is printed to the Serial Monitor.
* **Adjust LED Color Based on Mood Level:**
* `if (moodLevel != lastMoodLevel)`: This is the key optimization. The code only updates the LEDs if the mood level has actually changed since the last iteration.
* `moodToColor(moodLevel, red, green, blue, brightness);`: Calls the `moodToColor()` function to get the appropriate color and brightness values for the current mood.
* `setColorAll(red, green, blue, brightness);`: Calls the `setColorAll()` function to set the NeoPixel strip to the new color and brightness.
* `lastMoodLevel = moodLevel;`: Updates `lastMoodLevel` to the current `moodLevel` so that the LEDs are not unnecessarily updated next time around. This prevents flickering or other unwanted behavior.
* `delay(100);`: A small delay to prevent the Arduino from running too fast and potentially overwhelming the serial port or other processes.
**How to Use:**
1. **Connect the Hardware:**
* Connect the NeoPixel strip to your Arduino as follows:
* NeoPixel Data In (Din) to Arduino digital pin `DATA_PIN` (defined as 6 in this code).
* NeoPixel +5V to Arduino +5V (or an external 5V power supply ? *highly recommended* if you have a long strip).
* NeoPixel GND to Arduino GND.
* **Important Power Note:** If you have a long NeoPixel strip (more than a few LEDs), you *must* use an external 5V power supply for the NeoPixels. Do *not* power them directly from the Arduino's 5V pin, as it can't supply enough current and may damage the Arduino. Connect the GND of the external power supply to the Arduino's GND.
* (For the simulated Face-AI) If you're connecting a second Arduino to simulate the Face-AI, connect:
* Arduino #1 (main code) RX (pin 2) to Arduino #2 (Face-AI simulator) TX.
* Arduino #1 TX (pin 3) to Arduino #2 RX.
* Both Arduino GNDs together.
2. **Install Libraries:**
* Open the Arduino IDE.
* Go to Sketch -> Include Library -> Manage Libraries...
* Search for "Adafruit NeoPixel" and install the latest version.
3. **Upload the Code:**
* Copy the code into the Arduino IDE.
* Select the correct board and port in the Arduino IDE (Tools -> Board and Tools -> Port).
* Upload the code to your Arduino.
4. **Simulate the Face-AI (If you don't have actual Face-AI data):**
* To simulate the Face-AI, open the Serial Monitor in the Arduino IDE (Tools -> Serial Monitor).
* Make sure the baud rate in the Serial Monitor is set to 9600.
* Type a number between 0 and 100 (representing the mood level) in the Serial Monitor's input box, followed by pressing Enter. This simulates the Face-AI sending a mood level to the Arduino.
5. **Observe:** The NeoPixel strip should change color and brightness based on the mood level you enter.
**Example Face-AI Simulator (Arduino):**
Here's a simple Arduino sketch to simulate the Face-AI sending mood data:
```arduino
// Arduino Code to Simulate Face-AI mood data
#include <SoftwareSerial.h>
#define TX_PIN 10 // Arduino pin to transmit mood data
#define RX_PIN 11 // Arduino pin to receive data (not used in this simple example)
SoftwareSerial faceAISerial(RX_PIN, TX_PIN); // RX, TX
int moodLevel = 0;
void setup() {
Serial.begin(9600);
faceAISerial.begin(9600);
Serial.println("Face-AI Simulator Initialized.");
}
void loop() {
// Simulate mood fluctuations
moodLevel = random(0, 101); // Generate a random mood level (0-100)
faceAISerial.println(moodLevel); // Send mood data to the main Arduino
Serial.print("Simulated Mood: ");
Serial.println(moodLevel);
delay(2000); // Send a new mood every 2 seconds
}
```
* Connect this Arduino's TX pin (10) to the main Arduino's RX pin (2), and this Arduino's GND to the main Arduino's GND.
**Important Considerations:**
* **Real Face-AI:** This example uses a *simulation* of Face-AI. A real system would involve:
* A camera to capture images or video.
* Facial recognition software or a cloud-based service to analyze faces and estimate mood.
* A way to transmit the mood data (e.g., via serial communication, Wi-Fi, Bluetooth) to the Arduino.
* **Power:** As mentioned before, *always* use an external power supply for NeoPixels if you have more than a few LEDs.
* **Color Calibration:** The color ranges in the `moodToColor()` function are just examples. You'll likely need to adjust them to match your personal preferences and the characteristics of your NeoPixel strip.
* **Smoothing:** You might want to add smoothing or filtering to the mood data to prevent rapid and jarring color changes. You could use a moving average filter to smooth the `moodLevel` values.
* **Data format:** Consider a JSON format in your code to transmit from the simulated Face-AI. It provides more clarity and versatility to your code.
👁️ Viewed: 6
Comments