Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 11 ■ IOT PATTERNS: MACHINE TO MACHINE


else
{
// Turn lights on/off
turnLightsOnOff("OFF");
}
}


Control Lights


The fourth section of code, as provided in Listing 11-7 , defines the variables, constants,
and functions that are going to be used for controlling the LED.
This code switches the state of the LED based on the value of the action parameter.


Listing 11-7. Code for Controlling the LED


int ledPin = 3;


void turnLightsOnOff(String action)
{
// Check if lights are currently on or off
if(action == "ON")
{
//Turn lights on
Serial.println("[INFO] Turning lights on");
digitalWrite(ledPin, HIGH);
}
else
{
// Turn lights off
Serial.println("[INFO] Turning lights off");
digitalWrite(ledPin, LOW);
}
}


Standard Functions


The final code section is provided in Listing 11-8. It implements Arduino’s standard
setup() and loop() functions.
The setup() function initializes the serial port, connects to the internet, and
subscribes to the MQTT topic.
The MQTT broker has already been initialized and subscribed, so in loop()
function, you only need to wait for new messages from the MQTT broker.

Free download pdf