Building Arduino Projects for the Internet of Things

(Steven Felgate) #1
CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE

// Publish to MQTT Topic
if (pubSubClient.connected())
{
Serial.println("[INFO] Publishing to MQTT Broker");
if(lightLevel == "LOW")
{
Serial.println("[INFO] Light Level is LOW");
pubSubClient.publish(topic, "LOW");
}
else
{
Serial.println("[INFO] Light Level is HIGH");
pubSubClient.publish(topic, "HIGH");
}


Serial.println("[INFO] Publish to MQTT Broker Complete");
}
else
{
Serial.println("[ERROR] Publish to MQTT Broker Failed");
}


pubSubClient.disconnect();


}


Standard Functions


The final section is provided in Listing 11-4. It implements Arduino’s standard setup()
and loop() functions.
The setup() function initializes the serial port and connects to the Internet.
The loop() function calls readSensorData() only, as it internally calls the
publishSensorData() function when light levels are low.


Listing 11-4. Code for Standard Arduino Functions


void setup()
{
// Initialize serial port
Serial.begin(9600);


// Connect Arduino to internet
connectToInternet();
}

Free download pdf