Building Arduino Projects for the Internet of Things

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

Listing 11-8. Code for Standard Arduino Functions


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


// Connect Arduino to internet
connectToInternet();


// Set LED pin mode
pinMode(ledPin, OUTPUT);


//Connect MQTT Broker
Serial.println("[INFO] Connecting to MQTT Broker");
if (pubSubClient.connect("arduinoClient"))
{
Serial.println("[INFO] Connection to MQTT Broker Successful");
pubSubClient.subscribe(topic);
}
else
{
Serial.println("[INFO] Connection to MQTT Broker Failed");
}
}


void loop()
{
// Wait for messages from MQTT broker
pubSubClient.loop();
}


Your Arduino code for the lighting control device is now complete.

The Final Product


To test the application, make sure both your devices—the light sensor device and the
lighting control device—are powered on and the code has already been deployed (see
Chapter 1 for the deployment process).
Open the Serial Monitor window for both of your devices. Figure  11-2 shows the
Serial Monitor window with log messages generated from the light sensor device. As soon
as you move this device from bright light to a dark area, it will publish a message to the
MQTT broker.

Free download pdf