So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By PeterM7
#89727 I have been struggling to get the wemos to handle button presses from a number of buttons. I am building a remote control unit using MQTT.
my code to read the buttons was just a series of if statements, but the Wemos kept crashing so I changed it to a do-while loop.

Now the problem is that it just seems to use the initialisation of the payload, and not send what I want. I am hoping that if I post it here someone can advise me of how to get out of this dilemna. Here is the code for this.
String ButtonReading()
{
String payload = "NULL";
do
{
if(digitalRead(ButtonUp) == PRESSED)
{
String payload = "forward";
Button_State = PRESSED;
}

if(digitalRead(ButtonDown) == PRESSED)
{
String payload = "backwards";
Button_State = PRESSED;
}

if(digitalRead(ButtonLeft) == PRESSED)
{
String payload = "left";
Button_State = PRESSED;
}

if(digitalRead(ButtonStop) == PRESSED)
{
String payload = "stop";
Button_State = PRESSED;
}
delay (500);
}
while (Button_State == NOT_PRESSED);
return payload;
}

and the bit that acts on it:
void loop() {
// confirm still connected to mqtt server
if (!client.connected()) {
Serial.println("reconnecting");
reconnect();
}
client.loop();
Serial.println("Read buttons");
String payload = ButtonReading();
// lcd.setCursor(1,2);
// lcd.print("payload: ");
// lcd.setCursor(10,2);
// lcd.print(payload);
if (Button_State == PRESSED)
{
lcd.setCursor(1,2); // Display
lcd.print("payload: ");
lcd.setCursor(10,2); // Display
lcd.print(payload);
long now = millis();
if (now - lastMsg > timeBetweenMessages )
{
lastMsg = now;
++value;
String pubTopic = topic ;
client.publish( (char*) pubTopic.c_str() , (char*) payload.c_str(), true );
}
Button_State = NOT_PRESSED ;
Serial.println("button cleared");
// lcd.clear();
delay(0);
}
delay(0.2);
}

Some extra bits are for debugging purposes.
Thanks for any help.
User avatar
By PeterM7
#89738 I have got it working reliably. I didn't use the debounce library.
This worked, but could possibly still do with soem tidying up:


String ButtonReading()
{
String payload = "NULL";
do
{
if(digitalRead(ButtonUp) == PRESSED)
{
String payload = "forward";
Button_State = PRESSED;
return payload;
}

if(digitalRead(ButtonDown) == PRESSED)
{
String payload = "backwards";
Button_State = PRESSED;
return payload;
}

if(digitalRead(ButtonLeft) == PRESSED)
{
String payload = "left";
Button_State = PRESSED;
return payload;
}

if(digitalRead(ButtonStop) == PRESSED)
{
String payload = "stop";
Button_State = PRESSED;
return payload;
}
delay (500);
}
while (Button_State != PRESSED);
// return payload;
}