Over the past week, I figured out how to make lights fade on and using sensors. So naturally, I went a completely different direction. I created a little game that generates a random value between 0-255 and lights up an LED with that value (0 being LOW and 255 being HIGH). The user must then control a photoreceptor so that it falls within a range of the generated value. If they are too high, a red light will come on (HOT) and if they are too low, a blue light will come on (COLD). If they fall within the range, they will be rewarded with a yellow light.
In this game’s production, I fell into some interesting problems and came up with solutions for a few of them. One was that the loop would go so fast that it would constantly be generating new values, thus rendering the game useless. However, I think this would make a great EXTREME MODE for the truly daring player. I fixed this by adding a button. The loop would only generate a new number if the button was pressed.
Here are my video and code 😀
const int ledPinR = 2;
const int ledPinG = 3;
const int ledPinB = 4;
const int ledPinWIN = 6;
int ledRState = LOW;
int ledGState = 0;
int ledBState = LOW;
int ledWINState = LOW;
int button = 7;
int buttonState = 0;
int randNumber = random(1,255);
void setup() {
pinMode(ledPinR, OUTPUT);
pinMode(ledPinG, OUTPUT);
pinMode(ledPinB, OUTPUT);
pinMode(ledPinWIN, OUTPUT);
pinMode(button, INPUT);
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
if (buttonState == HIGH){
randNumber = random(1,255);
}
Serial.println(randNumber);
ledGState = randNumber;
int lightValue = analogRead(A0);
if (lightValue < ledGState + 250){
ledBState = !ledBState;
ledRState = LOW;
ledWINState = LOW;
}
if (lightValue > ledGState + 400){
ledRState = !ledRState;
ledBState = LOW;
ledWINState = LOW;
}
if (lightValue >= (ledGState + 250) && lightValue <= (ledGState + 400)){
ledWINState = HIGH;
// if in x range, start a timer, once timer is 3 seconds, do whatever
}
digitalWrite(ledPinR, ledRState);
analogWrite(ledPinG, ledGState);
digitalWrite(ledPinB, ledBState);
digitalWrite(ledPinWIN, ledWINState);
buttonState = digitalRead(button);
}