Code to convert wavelength to RGB value.
The formula used in the code for converting wavelength to RGB values is based on the principle of additive color mixing, which states that by adding red, green, and blue light in varying intensities, any color can be created. In this formula, the wavelength of the light is used to calculate the intensities of the red, green, and blue light needed to create that color.
The formula used in the code involves a series of conditional statements that assign values to the R, G, and B variables based on the range of the input wavelength. The formula is as follows:
If the wavelength is less than 380 or greater than 780, return 0 (out of range).
If the wavelength is between 380 and 440, set R to -(wavelength – 440) / (440 – 380), G to 0, and B to 1.
If the wavelength is between 440 and 490, set R to 0, G to (wavelength – 440) / (490 – 440), and B to 1.
If the wavelength is between 490 and 510, set R to 0, G to 1, and B to -(wavelength – 510) / (510 – 490).
If the wavelength is between 510 and 580, set R to (wavelength – 510) / (580 – 510), G to 1, and B to 0.
If the wavelength is between 580 and 645, set R to 1, G to -(wavelength – 645) / (645 – 580), and B to 0.
If the wavelength is between 645 and 780, set R to 1, G to 0, and B to 0.
The values of R, G, and B are then adjusted by a gamma value of 0.8 and a factor of 0.1. Finally, the RGB values are returned as integers between 0 and 255 by using the formula 255 * Math.pow(colorValue, gamma), where colorValue is the value of R, G, or B.
This is the scan view from wavelength to RGB
Wavelength to RGB Converter
Wavelength to RGB Converter
const int redPin = 3;
const int greenPin = 5;
const int bluePin = 6;
const int ldrPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int wavelength = 380; // Start at 380nm
while (wavelength <= 780) { // Scan up to 780nm
// Convert wavelength to RGB values
int redValue = getRGBValue(wavelength, 'R');
int greenValue = getRGBValue(wavelength, 'G');
int blueValue = getRGBValue(wavelength, 'B');
// Set RGB LED values
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
// Read LDR sensor value and print to serial monitor
int ldrValue = analogRead(ldrPin);
Serial.print("Wavelength: ");
Serial.print(wavelength);
Serial.print("nm, LDR Value: ");
Serial.println(ldrValue);
wavelength++; // Increment wavelength
delay(100); // Delay for stability
}
}
// Convert wavelength to RGB values
int getRGBValue(int wavelength, char color) {
double gamma = 0.8;
double factor = 0.1;
double R, G, B;
if (wavelength < 380 || wavelength > 780) {
return 0;
}
if (wavelength >= 380 && wavelength < 440) { R = -(wavelength - 440) / (440 - 380); G = 0; B = 1; } else if (wavelength >= 440 && wavelength < 490) { R = 0; G = (wavelength - 440) / (490 - 440); B = 1; } else if (wavelength >= 490 && wavelength < 510) { R = 0; G = 1; B = -(wavelength - 510) / (510 - 490); } else if (wavelength >= 510 && wavelength < 580) { R = (wavelength - 510) / (580 - 510); G = 1; B = 0; } else if (wavelength >= 580 && wavelength < 645) { R = 1; G = -(wavelength - 645) / (645 - 580); B = 0.0; } else if (wavelength >= 645 && wavelength < 781) {
R = 1;
G = 0;
B = 0;
}
if (color == 'R') {
return 255 * pow(R, gamma);
} else if (color == 'G') {
return 255 * pow(G, gamma);
} else if (color == 'B') {
return 255 * pow(B, gamma);
}
}
Spectrophotometer Arduino IDE code
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
const int ldrPin = A0;
void setup() {
Serial.begin(9600);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(ldrPin, INPUT);
}
void loop() {
if (Serial.available() >= 3) {
int red = Serial.read();
int green = Serial.read();
int blue = Serial.read();
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
int lightLevel = analogRead(ldrPin);
Serial.println("Light level: " + String(lightLevel));
}
}
In the above code, the redPin, greenPin, and bluePin constants define the digital pins connected to the red, green, and blue leads of the RGB LED, respectively. The setup() function sets the baud rate of the serial communication to 9600 and configures the pins as outputs. The loop() function continuously checks for available serial data and sets the intensity of each color according to the values entered in the serial console. In the code, the Serial.available() function is used to check if there is data available in the serial buffer to be read. If Serial.available() >= 3, it means that there are at least three characters (numbers between 0 and 255) in the buffer. The code then reads three values using the Serial.read() function and stores them in the variables red, green, and blue. Each Serial.read() call returns the next character in the buffer, so the first call returns the first number entered, the second call returns the second number, and so on. In this code, it is assumed that the values entered in the serial console are separated by commas, and that each value represents the intensity of one of the RGB colors. The code sets the intensity of each color by writing the corresponding value to the analog pin using the analogWrite() function. This code allows the user to enter three values separated by commas in the serial console, and then changes the color of the RGB LED accordingly. An LDR is connected to analog pin A0. The setup() function sets the baud rate of the serial communication to 9600, configures the pins for the RGB LED as outputs, and the pin for the LDR as an input. The loop() function after setting the intensity of the RGB LED, it also measures the light level using the LDR. The analogRead() function is used to read the analog voltage on the LDR pin and convert it to a digital value between 0 and 1023. The light level is then printed to the serial console using the Serial.println() function.
PROCESSING AND ARDUINO
To use Processing with Arduino, you need to follow these steps:
- Install the Arduino software on your computer.
- Connect your Arduino board to your computer using a USB cable.
- Install the Processing software on your computer.
- In Processing, go to Sketch > Import Library > Add Library, and search for the "Arduino" library. Install the library.
- In the Processing sketch, import the Arduino library with the following code:
import processing.serial.*;
- In the setup() function of your Processing sketch, initialize the serial communication with the following code:
Serial myPort = new Serial(this, "COM3", 9600);
(replace "COM3" with the name of the serial port your Arduino board is connected to). - Use the
myPort.write()
function to send data from Processing to Arduino and themyPort.read()
function to receive data from Arduino in Processing. - Upload the standard Firmata sketch to your Arduino board using the Arduino software.
- In the Processing sketch, use the
Arduino
object to communicate with the Firmata sketch running on the Arduino board.
Note: The details of the code will depend on the specific project you are working on, but these steps provide a general outline for using Processing with Arduino.
Blinking code in Processing
Here is an example of a Processing sketch that blinks an LED connected to pin 13 on an Arduino board:
import processing.serial.*;
Serial myPort;
ledPin = 13;
void setup(){
size(200,200);
myPort = new Serial(this,"COM3",9600);
myPort.write("13");
}
void draw(){
if (myPort.available() > 0) {
int inByte = myPort.read();
if(inByte == 1) {
myPort.write("0");
} else {
myPort.write("1");
}
}
}
This code initializes the serial communication with the Arduino board, sets the LED pin, and in the draw()
function alternates between writing a 1 and a 0 to the LED pin on each iteration of the loop. To use this code, you'll need to have the Arduino software and the Arduino library for Processing installed and have a standard Firmata sketch uploaded to the Arduino board.
Spectrophotometer Processing 3 code
import processing.serial.*;
Serial myPort;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
int lightLevel = 0;
void setup() {
size(200, 200);
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
}
void draw() {
if (myPort.available() >= 3) {
redValue = myPort.read();
greenValue = myPort.read();
blueValue = myPort.read();
background(redValue, greenValue, blueValue);
lightLevel = myPort.read();
fill(255);
text("Light level: " + lightLevel, 10, 20);
}
}
In this code, the Serial library is imported and a Serial object is created using the first available serial port. In the setup() function, the size() function is used to set the size of the window, and the Serial.list() function is used to get a list of available serial ports. The first available serial port is selected and a new Serial object is created with a baud rate of 9600.
In the draw()
function, the code checks if there is data available in the serial buffer. If there are at least three characters in the buffer, the code reads the three values representing the intensities of the RGB colors and sets the background color of the window using the background()
function. The code also reads the light level from the buffer and displays it on the window using the fill()
and text()
functions. This code allows the user to control the RGB LED and read the light level using the Arduino and Processing software.
Spectrophotometer Processing 4 code (Windows)
import processing.serial.*;
Serial myPort;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
int lightLevel = 0;
void setup() {
size(200, 200);
String[] portList = Serial.list();
for (int i = 0; i < portList.length; i++) {
if (portList[i].contains("COM")) {
myPort = new Serial(this, portList[i], 9600);
break;
}
}
}
void draw() {
if (myPort.available() >= 3) {
redValue = myPort.read();
greenValue = myPort.read();
blueValue = myPort.read();
background(redValue, greenValue, blueValue);
lightLevel = myPort.read();
fill(255);
text("Light level: " + lightLevel, 10, 20);
}
}
For Processing 4, the Serial.list() method has been changed to Serial.list()[] to get an array of available serial ports, and the code uses a for loop to search for the port that contains COM (Windows port) or "cu.usbmodem" (which is typically the name of the serial port used by an Arduino board on a Mac computer).
Add sliders with controlP5
import processing.serial.*;
import controlP5.*;
Serial myPort;
ControlP5 cp5;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
int lightLevel = 0;
void setup() {
size(400, 400);
String[] portList = Serial.list();
for (int i = 0; i < portList.length; i++) {
if (portList[i].contains("COM")) {
myPort = new Serial(this, portList[i], 9600);
break;
}
}
cp5 = new ControlP5(this);
cp5.addSlider("redValue")
.setPosition(50, 50)
.setRange(0, 255)
.setValue(0)
.setWidth(300)
.setColorValue(color(255, 0, 0));
cp5.addSlider("greenValue")
.setPosition(50, 100)
.setRange(0, 255)
.setValue(0)
.setWidth(300)
.setColorValue(color(0, 255, 0));
cp5.addSlider("blueValue")
.setPosition(50, 150)
.setRange(0, 255)
.setValue(0)
.setWidth(300)
.setColorValue(color(0, 0, 255));
}
void draw() {
background(redValue, greenValue, blueValue);
if (myPort.available() >= 1) {
lightLevel = myPort.read();
}
fill(255);
text("Red value: " + redValue, 50, 200);
text("Green value: " + greenValue, 50, 220);
text("Blue value: " + blueValue, 50, 240);
text("Light level: " + lightLevel, 50, 260);
}
In this code, the ControlP5 library is imported, and an instance of the ControlP5 class is created in the setup function. Three sliders are added to the GUI using the addSlider method, each with its own range, width, and color. The background function uses the values of the redValue, greenValue, and blueValue variables to set the background color. The lightLevel variable is updated if data is available from the serial port. The corresponding values for redValue, greenValue, blueValue, and lightLevel are displayed on the screen using the text function.This code should work in Processing 4 and should provide the same functionality as the previous code, but with the added ability to control the RGB LED using sliders and to see the corresponding values and the LDR values in the GUI.
LDR moves a paddle
import processing.serial.*;
Serial mySerial;
int sensorValue;
int paddleX;
int paddleWidth = 80;
int paddleHeight = 20;
void setup() {
size(800, 600);
mySerial = new Serial(this, "COM3", 9600);
mySerial.bufferUntil('\n');
}
void draw() {
background(255);
fill(0);
rect(paddleX, height - paddleHeight, paddleWidth, paddleHeight);
}
void serialEvent(Serial mySerial) {
String inString = mySerial.readStringUntil('\n');
if (inString != null) {
inString = trim(inString);
sensorValue = int(inString);
paddleX = map(sensorValue, 0, 1023, 0, width - paddleWidth);
}
}
In this example, the Processing sketch receives data from the LDR sensor over a serial connection and updates the sensorValue
variable with the latest reading. The paddleX
position is then updated based on the sensorValue
using the map()
function to map the range of sensor values (0 to 1023) to the range of possible paddle positions (0 to width - paddleWidth
). Finally, the paddle is drawn as a filled rectangle using the rect()
function.
Simplest pong game
import processing.serial.*;
Serial myPort;
int val;
int paddleY = 200;
int ballX = 100;
int ballY = 100;
int ballSpeedX = 5;
int ballSpeedY = 5;
void setup() {
size(400, 400);
myPort = new Serial(this, Serial.list()[0], 9600);
myPort.bufferUntil('\n');
}
void draw() {
background(255);
// Read data from the LDR sensor
if (myPort.available() > 0) {
val = myPort.readStringUntil('\n').trim().toInt();
paddleY = map(val, 0, 1023, 0, height-100);
}
// Draw the paddle
fill(0);
rect(width-20, paddleY, 10, 100);
// Move the ball
ballX = ballX + ballSpeedX;
ballY = ballY + ballSpeedY;
// Bounce the ball when it hits the edges of the screen
if (ballX > width || ballX < 0) {
ballSpeedX = -ballSpeedX;
}
if (ballY > height || ballY < 0) {
ballSpeedY = -ballSpeedY;
}
// Check if the ball hits the paddle
if (ballX > width-30 && ballY > paddleY && ballY < paddleY + 100) {
ballSpeedX = -ballSpeedX;
}
// Draw the ball
fill(255, 0, 0);
ellipse(ballX, ballY, 20, 20);
}
This code assumes that you have a working LDR sensor connected to your computer via a serial port, and that the sensor is sending data in the range of 0 to 1023, with higher values indicating more light. The code maps the LDR sensor readings to the paddle's Y position, so that the paddle will move up or down as the light level changes. The ball will bounce off the edges of the screen and the paddle, changing direction each time it hits an obstacle.
Read LDR with Python
import time
import board
import analogio
ldr = analogio.AnalogIn(board.A0)
def get_ldr_value():
return ldr.value
while True:
print("LDR Value:", get_ldr_value())
time.sleep(1)