Hey everyone, I’m new to the Photon and of course, unfamiliar with many of its functionalites.
As the above tittle suggests, I’m trying to create a code for detecting button presses and changing the blinking rate without using any blocking code, but the program I came up with is not working. I’m hoping if you guys could spot any logical errors in my code. I suspect that is the problem, and a simple one too, it’s just I can’t find it out myself.
Here is my code:
int led = D7;
int button = D3; // This is the input button (use an internal pull-down resistor)
int LedFreqState = 0; // set to 0 for 0.50 Hz, set to 1 for 0.25 Hz
int prevButton = LOW; // state variable to store if button was HIGH or LOW last time
bool LED_state = FALSE;
unsigned long int timeToToggleLED = 0;
void setup() {
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
Serial.begin(9600); // Use Serial port for debugging
}
void loop() {
unsigned long int currentTime = millis();
int curButton = digitalRead(button);
if(curButton == HIGH && prevButton == LOW){
// a transition happened -- the user has just pressed the button
Serial.println("Button press detected."); //Debugging printout
// change the state of the LED blinking rate
LedFreqState++;
if(LedFreqState > 2){
LedFreqState = 0;
}
prevButton = curButton;
Serial.println("LedFreqState is: ");
Serial.println(LedFreqState);
}
if(LedFreqState == 0)
{
if(currentTime > timeToToggleLED){
// Time to Toggle!
LED_state = !LED_state;
digitalWrite(led, LED_state);
// Calculate and store the next time to toggle the LED
timeToToggleLED += 1000;
}
}
else if(LedFreqState == 1)
{
if(currentTime > timeToToggleLED){
// Time to Toggle!
LED_state = !LED_state;
digitalWrite(led, LED_state);
// Calculate and store the next time to toggle the LED
timeToToggleLED += 2000;
}
}
else if (LedFreqState == 2)
{
if(currentTime > timeToToggleLED){
// Time to Toggle!
LED_state = !LED_state;
digitalWrite(led, LED_state);
// Calculate and store the next time to toggle the LED
timeToToggleLED += 500;
}
}
}
I’m trying to create 3 different blinking rates, which are 0.25Hz, 0.5Hz and 1Hz.
Can anyone help me out here?
Thanks so much!