Author Topic: ESP32: Unresponsive code  (Read 682 times)

0 Members and 1 Guest are viewing this topic.

Offline mwesternTopic starter

  • Newbie
  • Posts: 5
  • Country: us
ESP32: Unresponsive code
« on: October 22, 2020, 06:40:16 pm »
I have written some code for a flashlight I am trying to work on. I have attached it below. Currently it will upload on the board but when I am testing it nothing happens. Just curious if anybody would like to look at the code for me and let me know if you think it is the code or my board. Thanks.
 

Offline mskeete

  • Contributor
  • Posts: 33
  • Country: gb
Re: ESP32: Unresponsive code
« Reply #1 on: October 23, 2020, 05:34:54 pm »
you only read the state of the botton once. You need to update your variable in the while loo or ditch the varible altogether

//loop function
void loop(void)
{
  const int Button = 16; //GPIO 17
  int Button_state = digitalRead(Button);
  pinMode(Button, INPUT);//Set Button to be input -- does this need to be in the loop?
  if(Button_state == LOW){
    timer1 = millis();
    timer2 = millis();
    while(Button_state == LOW){ // while(digitalRead(Button) == LOW){
      Button_state = digitalRead(Button); // added this line. Alternatively, change the while statement as in the comment
      timer2 = millis();
    }
    Hold_time = timer2 - timer1;
    passOn(Hold_time);
  }
}

Changes tested with Notepad compiler :)
 

Offline TomS_

  • Frequent Contributor
  • **
  • Posts: 834
  • Country: gb
Re: ESP32: Unresponsive code
« Reply #2 on: October 24, 2020, 10:57:43 am »
You definitely do not need to:

1. Read the button state in the setup function
2. Reconfigure the button pin as an input in the loop function

And as mskeete says, you only read the button once when entering into the loop function, and then loop forever if the state was low, but never check the state of it again - so if the button was pressed you will never exit that while loop and it will appear to be unresponsive as a result.

You can also use a #define to create a compile time variable to hold the button pin number so that you do not need to declare it in multiple locations throughout your code - a maintenance nightmare!
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf