OpenHAB, MQTT, Arduino and ESP8266: Part 5.2: Combined Switch and Sensor module based on Arduino

The following series of posts will document my journey to full Home Automation using the MQTT protocol, all custom hardware (Arduino and ESP8266 based), and all tied together using OpenHAB

Part 1: Setting up the server / environment

Part 2: Publish, Subscribe, Command, State, and WTFs

Part 3: Hardware: Arduino with Ethernet Shield

Part 4: Hardware: ESP8266 with NodeMCU firmware

Part 5: Hardware: Sensors

Part 5.1: Graphing Sensor Data

Part 5.2: Combined Switch and Sensor

Part 6: OpenHAB Automation Rules

This is a very quick post just to jot down a very simple mashup of Part 3 and Part 5. The sketch below listens for MQTT messages to switch, at every second, but only sends temperature updates every 5 seconds… Good tradeoff = always available to switch immediately, yet still low bandwidth since it doesnt send a temp update on each cycle of the loop:

Another twist here is that I added a physical button on D7 that also turns the device on/off and then publishes the state back to MQTT -> openhab so the virtual switch status matches what the physical is doing