I want to print the RGB values to serial monitor only once when i push a button. When i push the button the values prints all the time and do not stop. How can i do that?
Here is my code:
int RedLED = 3; // the PWM pin the LED is attached to
int GreenLED = 5;
int BlueLED = 6;
int button = 1;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// declare LED pin to be an output:
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
pinMode(button, INPUT_PULLUP);
}
// the loop routine runs over and over again forever:
void loop() {
int buttonValue = digitalRead(button);
// reads the input on analog pin A0 (value between 0 and 1023)
int R = analogRead(A0);
int G = analogRead(A1);
int B = analogRead(A2);
// scales it to brightness (value between 0 and 255)
int brightness1 = map(R, 0, 1023, 0, 255);
int brightness2 = map(G, 0, 1023, 0, 255);
int brightness3 = map(B, 0, 1023, 0, 255);
// sets the brightness LED that connects to pin 3
analogWrite(RedLED, brightness1);
analogWrite(GreenLED, brightness2);
analogWrite(BlueLED, brightness3);
if (buttonValue == 0){
Serial.print("R: ");
Serial.println(brightness1);
Serial.print("G: ");
Serial.println(brightness2);
Serial.print("B: ");
Serial.println(brightness3);
}
else{
}
}
One more question regards to this project after i added an 1602 LCD displat for displaying the values on.
When i push the button and sends the values to the LCD i get "254" when i turn the potentiometer to the brightest value, and "054" when i turn the potentiometers off.
Serial monitor shows also "254" as max value, but shows "0" when the led is off.
Here is my last code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
int RedLED = 3;
int GreenLED = 5;
int BlueLED = 6;
int button = 1;
int buttonState = 0;
int lastButtonState = 0;
void setup() {
lcd.init();
Serial.begin(9600);
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
pinMode(button, INPUT_PULLUP);
lcd.backlight();
}
void loop() {
buttonState = digitalRead(button);
int R = analogRead(A0);
int G = analogRead(A1);
int B = analogRead(A2);
int brightness1 = map(R, 0, 1023, 0, 255);
int brightness2 = map(G, 0, 1023, 0, 255);
int brightness3 = map(B, 0, 1023, 0, 255);
analogWrite(RedLED, brightness1);
analogWrite(GreenLED, brightness2);
analogWrite(BlueLED, brightness3);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
Serial.print("R:");
Serial.println(brightness1);
Serial.print("G: ");
Serial.println(brightness2);
Serial.print("B: ");
Serial.println(brightness3);
lcd.setCursor(5, 0);
lcd.print("R:");
lcd.setCursor(7, 0);
lcd.print(brightness1);
lcd.setCursor(0, 1);
lcd.print("G:");
lcd.setCursor(2, 1);
lcd.print(brightness2);
lcd.setCursor(11, 1);
lcd.print("B:");
lcd.setCursor(13, 1);
lcd.print(brightness3);
}
else {
}
delay(100);
lastButtonState = buttonState;
}
}