CHAPTER 10 ■ IOT PATTERNS: MACHINE TO HUMAN
// Publish to MQTT Topic
if (pubSubClient.connected())
{
Serial.println("[INFO] Publishing to MQTT Broker");
pubSubClient.publish(topic, "Garbage level is HIGH, schedule pickup");
Serial.println("[INFO] Publish to MQTT Broker Complete");
}
else
{
Serial.println("[ERROR] Publish to MQTT Broker Failed");
}
pubSubClient.disconnect();
}
Standard Functions
The final code section is shown in Listing 10-4. It implements Arduino’s standard setup()
and loop() functions.
The setup() function initializes the serial port, sets the pin modes for the trigger and
echo pins, connects to the Internet, and calibrates the proximity sensor.
The loop() function simply needs to call readSensorData() at regular intervals.
Listing 10-4. Code for Standard Arduino Functions
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Set pin mode
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
// Connect Arduino to internet
connectToInternet();
// Calibrate sensor
calibrateSensor();
}