Hello, everyone!
I'm writing code using the millis() function. I think the code is twisted because I'm not good at coding yet and I don't understand millis(). The code below provides an inclination through the 9-axis sensor and outputs different strings and LEDs depending on the left and right slopes.
What I want to do is, for example, tilt to the left, the functions below are implemented.
-
Left LED illuminated for 1 second (if tilted to the left continuously, it remains on until switching to another direction).)
-
Switching to the right before 1 second (not yet before LED goes off) turns the left LED off immediately and performs the right LED action.
+3. LED Immediate Switching only applies when tilting left or right. For example, if you tilt to the left and then place it in a flat state, the left LED turns on and then turns off after a second.
It's kind of like this, but I couldn't express it properly with code...
If I upload this code, you will only repeat the on/off toggle when it is within the specified value range.
//Based on the x-axis slope.
if(val_x < -30 && State == 0) // right on
{
State = 1;
unsigned long previousMillis = millis();
Serial.println("갸LED ON");
digitalWrite(right_led, HIGH);
digitalWrite(left_led, LOW);
}
else if(val_x > 30 && State == 0) // left on
{
State = 1;
unsigned long previousMillis = millis();
Serial.println("왼쪽 LED ON");
digitalWrite(left_led, HIGH);
digitalWrite(right_led, LOW);
}
else
{
State = 0;
}
if( millis() >= previousMillis + 1000 && State == 0)//OFF
{
digitalWrite(left_led, LOW);
digitalWrite(right_led, LOW);
Serial.println("LED OFF");
}
I would really appreciate it if you could tell me about my problem!
Thank you.