Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 5 ■ IOT PATTERNS: REALTIME CLIENTS


Listing 5-3 provides the code for the calibrateSensor() function , which waits for
the motion sensor to calibrate properly. The sensor can take between 5 and 15 seconds
to calibrate, so the code allows 30 seconds for sensor to calibrate. Once calibration is
complete, the motion sensor is active and can start detection. If you do not give it enough
time to calibrate, the motion sensor might return incorrect readings.


Listing 5-3. Function to Calibrate the Motion Sensor


void calibrateSensor()
{
pinMode(pirPin, INPUT);
digitalWrite(pirPin, LOW);


Serial.println("[INFO] Calibrating Sensor ");


for(int i = 0; i < calibrationTime; i++)
{
Serial.print(".");
delay(1000);
}


Serial.println("");
Serial.println("[INFO] Calibration Complete");
Serial.println("[INFO] Sensor Active");
delay(50);
}


T h e readSensorData() function in Listing 5-4 reads data from Digital Pin 3 and the
result is either HIGH or LOW. HIGH means motion was detected and LOW means there was no
motion or the motion stopped. The additional condition if(lockLow) is there to avoid
publishing too many messages to the MQTT broker for the same motion.


Listing 5-4. Code for Reading Motion Sensor Data


void readSensorData()
{
if(digitalRead(pirPin) == HIGH)
{
if(lockLow)
{
lockLow = false;
Serial.print("[INFO] Activity Detected @ ");
Serial.print(millis()/1000);
Serial.print(" secs");
Serial.println("");

Free download pdf