Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 7 ■ IOT PATTERNS: ON-DEMAND CLIENTS


Read Sensor Data


The third section of the code, as provided in Listing 7-6 , defines the variables, constants,
and functions that are going to be used for reading sensor data.
The calibrateSensor() function waits for the proximity sensor to calibrate properly.
Once calibration is complete, the proximity sensor is active and can start detection. If you
do not give it enough time to calibrate, the proximity sensor might return incorrect readings.
The readSensorData() function generates a burst to detect if the parking spot is
empty. It triggers a burst on Digital Pin 2 by sending alternate signals—LOW, HIGH, and
LOW again. Then it reads the echo from Digital Pin 3 , which provides a distance of the
closest object. Finally, it checks if the echo value is less than the threshold. If it is, that
means an object is occupying the parking spot. Since this is just a prototype, the echo value
of 500 has been used, so when you use this sensor in real life you will need to adjust the
value by doing a few tests. If the parking spot is occupied, it calls publishSensorData(...)
with a OCCUPIED parameter; otherwise, it sends OPEN in the parameter.


Listing 7-6. Code for Detecting if Parking Spot Is Empty


int calibrationTime = 30;
#define TRIGPIN 2 // Pin to send trigger pulse
#define ECHOPIN 3 // Pin to receive echo pulse


void calibrateSensor()
{
//Give sensor some time to calibrate
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);
}


void readSensorData()
{
// Generating a burst to check for objects
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(10);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);

Free download pdf