Esp32 programming help needed

Hi guys, im using esp32 withAdafruit SHTC3 sensor for temp and humidity. It has a push button on pin0.I am trying to get my program to read data on every second hit on the button (one hit reads, second doesnt, third reads and so on) but im stuck because this code reads data uncontrollably. What am I doing wrong?
#include "Adafruit_SHTC3.h"

Adafruit_SHTC3 shtc3 = Adafruit_SHTC3();

int tipkalo = 0;
int stanjeTipkala = 0;
int zadnjeStanjeTipkala = 0;
int brojac = 0;

float ocitaj_temp() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data
Serial.print("Temperature: ");
float temperatura = temp.temperature;
Serial.print(temperatura);
Serial.println(" degrees C");
return temperatura;
}

float ocitaj_vlagu() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp);
Serial.print("Humidity: ");
float vlaznost = humidity.relative_humidity;
Serial.print(vlaznost);
Serial.println("% rH");
return vlaznost;
}

void setup() {

Serial.begin(115200);
pinMode(tipkalo, INPUT);
Serial.println("SHTC3 test");
if (!shtc3.begin()) {
Serial.println("Couldn't find SHTC3");
while (1) delay(1);
}
Serial.println("Found SHTC3 sensor");
}

void loop() {
stanjeTipkala = digitalRead(tipkalo);
if (stanjeTipkala != zadnjeStanjeTipkala) {
if (stanjeTipkala == HIGH) {
brojac++;
Serial.print("Broj pritisaka:");
Serial.println(brojac);
}
delay(50);
}
zadnjeStanjeTipkala = stanjeTipkala;

if (brojac % 2 == 0) {

ocitaj_temp();
ocitaj_vlagu();

}
}

Hi i think issue could be button bounce, but i am not sure.

Use pinMode(tipkalo, INPUT_PULLUP); and debounce the button.
Search for example code for this.

it is very difficult to read your code - upload it using code tags </>
see how-to-get-the-best-out-of-this-forum

Please edit your post with < code > tag.

By the way if with pin0 you mean GPIO0, try with another one because this is used for set MCU in download mode and usually it's tied to a pull-up resistor.

Ok, so I am trying to write a code that will connect to wifi, and subscribe to two different topics. When it gets "start" message it will start to measure and publish temp and humidity readings every 15 seconds. When i write stop it needs to stop. And also I am trying to change the time interval in which sensors measure and publish via other topic. For example when I enter 6 in other topic it will record and publish every 6 seconds and so on. The problem that I am getting is that I cant get it to stop or anything other than start. If someone has any spare time will you please show me what am I doing wrong, am I missing something in loop. Thanks in advance.

#include "Adafruit_SHTC3.h"
#include <WiFi.h>
#include <PubSubClient.h>

Adafruit_SHTC3 shtc3 = Adafruit_SHTC3();
char payload[20];
char message[50];
long interval = 15000;

const char* ssid = "...";
const char* password = "...";
const char* mqtt_server = "broker.mqttdashboard.com";
WiFiClient espClient;
PubSubClient client(espClient);

void startPublishing() {
  while (strcmp((char*) payload, "stop") != 0) {
    
    float varT = ocitaj_temp();
    float varH = ocitaj_vlagu();
    client.publish("home255", (String(varT) + "*" + String(varH)).c_str());
    
    delay(interval);

    if (strcmp((char*) payload, "stop") == 0) {
      break;
    }
  }
}

void stopPublishing() {
  strcpy(payload, "stop");
}


void setup_wifi() {

  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  payload[length] = '\0';
  if (strcmp(topic, "home255") == 0) {
    if (strcmp((char*) payload, "start") == 0) {
      startPublishing();
    } else if (strcmp((char*) payload, "stop") == 0) {
      stopPublishing();
    }
  } else if (strcmp(topic, "time255") == 0) {
    int newInterval = atoi((char*) payload);
    if (newInterval > 0) {
      interval = newInterval * 1000;
    }
  }
}


void reconnect() {


  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("home255");
      Serial.println("Pretplatio se na temu: home255");
      client.subscribe("time255");
      Serial.println("Pretplatio se na temu: time255");

    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}



float ocitaj_temp() {
  sensors_event_t humidity, temp;

  shtc3.getEvent(&humidity, &temp);  // populate temp and humidity objects with fresh data
  Serial.print("Temperature: ");
  float temperatura = temp.temperature;
  Serial.print(temperatura);
  Serial.println(" degrees C");
  return temperatura;
}

float ocitaj_vlagu() {
  sensors_event_t humidity, temp;

  shtc3.getEvent(&humidity, &temp);
  Serial.print("Humidity: ");
  float vlaznost = humidity.relative_humidity;
  Serial.print(vlaznost);
  Serial.println("% rH");
  return vlaznost;
}

void setup() {

  Serial.begin(115200);
  Serial.println("SHTC3 test");
  if (!shtc3.begin()) {
    Serial.println("Couldn't find SHTC3");
    while (1) delay(1);
  }
  Serial.println("Found SHTC3 sensor");
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}


void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

could you have additional character such as line terminators in the text string?
try strncmp() to check the exact number of characters

  } else if (strncmp((char*) payload, "stop",4) == 0) {
  

What does payload[length] = '\0'; do to the received data?

void IRAM_ATTR mqttCallback(char* topic, byte * payload, unsigned int length)
{
  memset( x_message.payload, '\0', payloadSize ); // clear payload char buffer
  x_message.topic = ""; //clear topic string buffer
  x_message.topic = topic; //store new topic
  memcpy( x_message.payload, payload, length );//store the payload data
  xQueueOverwrite( xQ_Message, (void *) &x_message );// send data to queue
} // void mqttCallback(char* topic, byte* payload, unsigned int length)

I do my parsing in another task instead of parsing in the receive task.

a parsing task

void fparseMQTT( void *pvParameters )
{
  struct stu_message px_message;
  for (;;)
  {
    if ( xQueueReceive(xQ_Message, &px_message, portMAX_DELAY) == pdTRUE )
    {
      xSemaphoreTake( sema_mqttOK, portMAX_DELAY );
      mqttOK = 0;
      xSemaphoreGive( sema_mqttOK );
      if (px_message.topic == topicAQIndex )
      {

      }
      if ( px_message.topic == topicPower )
      {
        log_i( "%s", String(px_message.payload) );
      }
      if ( px_message.topic == topicOutsidePressure )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.oPressure = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicOutsideHumidity )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.oHumidity = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicOutsideTemperature )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.oTemperature = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicRemainingMoisture_0 )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.RM0  = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicWindSpeed )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.WS = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicWindDirection )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.WD = "";
        x_eData.WD = String(px_message.payload);
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicRainfall )
      {
        xSemaphoreTake( sema_eData, portMAX_DELAY );
        x_eData.RF = String(px_message.payload).toFloat();
        xSemaphoreGive ( sema_eData );
      }
      if ( px_message.topic == topicWSVolts )
      {
        x_eData.WSV = String(px_message.payload).toFloat();
        //log_i( "%f", x_eData.WSV );
      }
      //      if ( px_message.topic == topicWSCurrent )
      //      {
      //        x_eData.WSC = String(px_message.payload).toFloat();
      //      }
      //      if ( px_message.topic == topicWSPower )
      //      {
      //        x_eData.WSP = String(px_message.payload).toFloat();
      //      }
      if ( px_message.topic == topicDPnWI )
      {
        xQueueSend( xQ_WindChillDewPoint, (void *) &px_message, 1 );
      }
      if ( String(px_message.topic) == topicOK )
      {
        if ( !TimeSet)
        {
          String temp = "";
          temp.reserve(50);
          temp.concat( String(px_message.payload[0]) );
          temp.concat( String(px_message.payload[1]) );
          temp.concat( String(px_message.payload[2]) );
          temp.concat( String(px_message.payload[3]) );
          int year =  temp.toInt();
          temp = "";
          temp.concat( String(px_message.payload[5]) + String(px_message.payload[6]) );
          int month =  temp.toInt();
          temp =  "";
          temp.concat(String(px_message.payload[8]) + String(px_message.payload[9]) );
          int day =  temp.toInt();
          temp = "";
          temp.concat( String(px_message.payload[11]) + String(px_message.payload[12]) );
          int hour =  temp.toInt();
          temp = "";
          temp.concat( String(px_message.payload[14]) + String(px_message.payload[15]) );
          int min =  temp.toInt();
          rtc.setTime( 0, min, hour, day, month, year );
          log_i( "rtc  %s Year %d month %d day %d", rtc.getTime(), rtc.getYear(), (rtc.getMonth() + 1), rtc.getDay() );
          TimeSet = true;
        }
      }
    } //if ( xQueueReceive(xQ_Message, &px_message, portMAX_DELAY) == pdTRUE )
  } //for(;;)
  vTaskDelete( NULL );
} // void fparseMQTT( void *pvParameters )

Help needed. Hi guys, i am having trouble with my project. I want my sensor to start sending and publishing data every 15 seconds when message "start" is published on topic, and to stop when I type "stop". What am I doing wrong?

#include "Adafruit_SHTC3.h"
#include <WiFi.h>
#include <PubSubClient.h>

Adafruit_SHTC3 shtc3 = Adafruit_SHTC3();
long lastMsg = 0;
char msg[50];
int value = 0;

const char* ssid = "...";
const char* password = "...";
const char* mqtt_server = "broker.mqttdashboard.com";
WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

randomSeed(micros());

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Check if the message is "start"
if (strcmp(topic, "home255") == 0 && strcmp((char*)payload, "start") == 0) {
long now = millis();
if (now - lastMsg > 15000) {
lastMsg = now;
++value;

  float varT = ocitaj_temp();
  float varH = ocitaj_vlagu();
  client.publish("home255", (String(varT) + "*" + String(varH)).c_str());
}

}

// Check if the message is "stop"
if (strcmp(topic, "home255") == 0 && strcmp((char*)payload, "stop") == 0) {
// Do nothing and stop publishing data
}
}
void reconnect() {

while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.subscribe("home255");
Serial.println("Pretplatio se na temu: home255");
client.subscribe("time255");
Serial.println("Pretplatio se na temu: time255");

} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  delay(5000);
}

}
}

float ocitaj_temp() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data
Serial.print("Temperature: ");
float temperatura = temp.temperature;
Serial.print(temperatura);
Serial.println(" degrees C");
return temperatura;
}

float ocitaj_vlagu() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp);
Serial.print("Humidity: ");
float vlaznost = humidity.relative_humidity;
Serial.print(vlaznost);
Serial.println("% rH");
return vlaznost;
}

void setup() {

Serial.begin(115200);
Serial.println("SHTC3 test");
if (!shtc3.begin()) {
Serial.println("Couldn't find SHTC3");
while (1) delay(1);
}
Serial.println("Found SHTC3 sensor");
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}

Nobody can tell! You forgot to tell what does happen.

By the way, read this topic telling how to post code, not text like You did.

Link: How to get the best out of this forum - Using Arduino / Installation & Troubleshooting - Arduino Forum

Sorry I am very new at this. Here is updated version of the code:

Pred-formatirani text#include "Adafruit_SHTC3.h"
#include <WiFi.h>
#include <PubSubClient.h>

Adafruit_SHTC3 shtc3 = Adafruit_SHTC3();
long lastMsg = 0;
char msg[50];
int value = 0;

const char* ssid = "...";
const char* password = "...";
const char* mqtt_server = "broker.mqttdashboard.com";
WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {

delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

randomSeed(micros());

Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("]: ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();

// Check if the message is "start"
if (strcmp(topic, "home255") == 0 && strcmp((char*)payload, "start") == 0) {
// Set the last published time to the current time
long lastPublishTime = millis();

// Loop until a "stop" message is received
while (true) {
  // Check if the current time is greater than the last published time plus 15 seconds
  if (millis() - lastPublishTime > 15000) {
    // Publish the sensor data and update the last published time
    float varT = ocitaj_temp();
    float varH = ocitaj_vlagu();
    client.publish("home255", (String(varT) + "*" + String(varH)).c_str());
    lastPublishTime = millis();
  }

  // Check for incoming messages
  client.loop();

  // Check if a "stop" message is received
  if (strcmp(topic, "home255") == 0 && strcmp((char*)payload, "stop") == 0) {
    // Break out of the loop and stop publishing sensor data
    break;
  }
}

}
}
void reconnect() {

while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
client.subscribe("home255");
Serial.println("Pretplatio se na temu: home255");
client.subscribe("time255");
Serial.println("Pretplatio se na temu: time255");

} else {
  Serial.print("failed, rc=");
  Serial.print(client.state());
  Serial.println(" try again in 5 seconds");
  delay(5000);
}

}
}

float ocitaj_temp() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp); // populate temp and humidity objects with fresh data
Serial.print("Temperature: ");
float temperatura = temp.temperature;
Serial.print(temperatura);
Serial.println(" degrees C");
return temperatura;
}

float ocitaj_vlagu() {
sensors_event_t humidity, temp;

shtc3.getEvent(&humidity, &temp);
Serial.print("Humidity: ");
float vlaznost = humidity.relative_humidity;
Serial.print(vlaznost);
Serial.println("% rH");
return vlaznost;
}

void setup() {

Serial.begin(115200);
Serial.println("SHTC3 test");
if (!shtc3.begin()) {
Serial.println("Couldn't find SHTC3");
while (1) delay(1);
}
Serial.println("Found SHTC3 sensor");
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}Pred-formatirani text

I got it to read data and publish it every 15 seconds, but it doesnt stop when I type "stop" at the topic.

Everybody start as new. Read Your post and look at the code. It's still text.
Read the link given, note "Autoformat" and "code tags". That makes the code much more easy to read.
Reading "text"... No, helpers can use their time for more interesting things. Here assembling a digitally controlled rotating table for the mill is more interesting as it looks.

Your two or more topics on the same or similar subject have been merged.

Please do not duplicate your questions as doing so wastes the time and effort of the volunteers trying to help you as they are then answering the same thing in different places.

Please create one topic only for your question and choose the forum category carefully. If you have multiple questions about the same project then please ask your questions in the one topic as the answers to one question provide useful context for the others, and also you won’t have to keep explaining your project repeatedly.

Repeated duplicate posting could result in a temporary or permanent ban from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.