Building Arduino Projects for the Internet of Things

(Steven Felgate) #1

CHAPTER 10 ■ IOT PATTERNS: MACHINE TO HUMAN


The readSensorData() function generates a burst to detect garbage level in the can.
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 the distance between the
sensor and the garbage. Finally, it checks if the distance is less than a threshold, and if it
is, that means the garbage can is close to being full and a pickup needs to be scheduled.
Since this is just a prototype, the echo value of 700 has been used. When you use this
sensor in real life, you need to adjust the value by doing a few tests. If the garbage level is
above the threshold, then call publishSensorData(...) with HIGH.


Listing 10-2. Code for Detecting the Garbage Level


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);


// Distance Calculation
float distance = pulseIn(ECHOPIN, HIGH);


Serial.println("[INFO] Garbage Level: " + String(distance));

Free download pdf