Advertisement
igendel

ChatGPT Arduino Accelerating Blinky, Attempt #2

Jan 7th, 2023 (edited)
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Me: This doesn't work if the user presses the button while the delay is executing. */
  2.  
  3. /* ChatGPT: You are correct. If the button is pressed while the delay is executing, the code will not detect the button press until after the delay has finished.
  4.  
  5. One way to fix this issue is to use a timer to track the elapsed time since the last button press, rather than using a delay. This will allow the code to continue checking for button presses while the LED is blinking.
  6.  
  7. Here is an example of how this could be implemented: */
  8.  
  9.  
  10. const int buttonPin = 2;    // pin for the button
  11. const int ledPin = 13;      // pin for the LED
  12. int blinkInterval = 1000;   // interval at which to blink (milliseconds)
  13.  
  14. // variables for tracking the button state
  15. int buttonState = 0;    // current state of the button
  16. int lastButtonState = 0; // previous state of the button
  17.  
  18. // variable for tracking the elapsed time
  19. unsigned long previousMillis = 0;
  20.  
  21. void setup() {
  22.   // set the LED pin as output
  23.   pinMode(ledPin, OUTPUT);
  24.   // set the button pin as input
  25.   pinMode(buttonPin, INPUT);
  26. }
  27.  
  28. void loop() {
  29.   // read the button state
  30.   buttonState = digitalRead(buttonPin);
  31.   // check if the button state has changed
  32.   if (buttonState != lastButtonState) {
  33.     // check if the button is pressed
  34.     if (buttonState == HIGH) {
  35.       // decrease the blink interval
  36.       blinkInterval = max(blinkInterval - 100, 100);
  37.     }
  38.     // save the current button state as the last button state
  39.     lastButtonState = buttonState;
  40.   }
  41.   // get the current time
  42.   unsigned long currentMillis = millis();
  43.   // check if the elapsed time is greater than the blink interval
  44.   if (currentMillis - previousMillis >= blinkInterval) {
  45.     // turn the LED on
  46.     digitalWrite(ledPin, HIGH);
  47.     // save the current time as the previous time
  48.     previousMillis = currentMillis;
  49.   }
  50.   // check if the elapsed time is greater than half the blink interval
  51.   else if (currentMillis - previousMillis >= blinkInterval / 2) {
  52.     // turn the LED off
  53.     digitalWrite(ledPin, LOW);
  54.     // save the current time as the previous time
  55.     previousMillis = currentMillis;
  56.   }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement