Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 6 ■ IOT PATTERNS: REMOTE CONTROL


void callback(char topic, byte payload, unsigned int length)
{
// Print payload
String payloadContent = String((char *)payload);
Serial.println("[INFO] Payload: " + payloadContent);


// Turn lights on/off
turnLightsOnOff();
}


C o n t r o l L i g h t s


The fourth section of the code defines variables, constants, and functions that are going
to be used for controlling the LED.
The code provided in Listing 6-14 checks if the LED is already on or off and simply
switches the state of the LED. If the value of the digital port 3 is HIGH, that means LED is
on. In that case, it’s changed to LOW, which turns the LED off.


Listing 6-14. Code for Controlling LED Light


int ledPin = 3;


void turnLightsOnOff()
{
// Check if lights are currently on or off
if(digitalRead(ledPin) == LOW)
{
//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


Finally, the code in the fifth and final section is shown in Listing 6-15. It implements
Arduino’s standard setup() and loop() functions.
In the setup() function, the code 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