I use the following code … for the PIR sensor, if reads GPIO 14 on a SonOff(which is ESP8266 based) which is connected to the PIR, as for the MQTT just use and modify the example code, it’s the same for most use cases. A good example would be KmanOzs SonOff code on this forum (https://github.com/KmanOz/Sonoff-HomeAssistant)
void pir_readPIR()
{
char log[LOGSZ];
pirval = digitalRead(PIR_PIN); // read input value
if (pirval == HIGH)
{ // check if the input is HIGH
if (pirState == LOW)
{
digitalWrite(LED, LOW); // turn LED ON
// we have just turned on
addLog("Motion detected!");
digitalWrite(RELAY,HIGH); // turn relay on
sprintf(log, "on");
addLog(log);
// Publish the Relay state to HA
mqttClient.publish(MQTT::Publish(PUB_PREFIX"/"MQTT_TOPIC,log).set_retain().set_qos(1));
ESP.wdtFeed();
// We only want to turn on light on the output change, not state
pirState = HIGH;
}
}
else
{
if (pirState == HIGH)
{
digitalWrite(LED, HIGH); // turn LED OFF
// we have just turned off
addLog("Motion detected Ended!");
digitalWrite(RELAY,LOW); // turn relay off
sprintf(log, "off");
addLog(log);
// Publish the Relay state to HA
mqttClient.publish(MQTT::Publish(PUB_PREFIX"/"MQTT_TOPIC,log).set_retain().set_qos(1));
ESP.wdtFeed();
// We only want to turn on the light on the output change, not state
pirState = LOW;
}
}
}