The focus theme is on the biodiversity and positive impact by Sigfox Foundation, and in the area of protecting the green resources in the city.
Problem StatementCurrently, town councils monitor the tree status through manual checking process. The checking process is tedious as there are few thousand of tress around the city. Thus there are accidents happened that the tree falling happened due to lack of checking.
From the research and consultation with tree expect in our school, we concluded that the main two factors of tree falling are tree stem stability and also the the moisture at the root. We would like to design a tree movement sensing system that will be attached to the tree stem and soil near the root. The sensors will sense the movement of the tree throughout the day and send to cloud through Sigfox for analysis.
At the same time, cloud will analyse the movement of the trees. Based on both data, the cloud will be able to conclude if the particular tree risk of falling percentage and send the alert whenever the risk is more than the predefined threshold. The supervisor will then send a team to perform checking on the tree for possible danger or problem.
This solution will definitely help to town councils to manage risk of tree falling that might endanger the property and human life through preventive measurement. It will also help to save time and improve the efficiency of manpower as they do not have to travel around to check on trees that might not fall and focus on the trees that will fall.
Proposed SolutionWe are using two type of sensors for the project. Tree tilting and soil moisture sensors. Both sensor nodes are integrated with Zigbee RF modules for local communication purpose as the typical height of the tree is more than 3 metres. It is not feasible to lay a wire to join both sensor nodes together in term of signal noise and also wiring. We are using the Zigbee RF modules that we found on the school project shelves.
We explain the data flow of the sensors here.
Firstly, the moisture sensor node that measures the soil moisture within range of 0-100%. The moisture sensor node communicates with tree tilting sensor node through ZigBee RF modules as it is far away from tree tilting sensor node. The tilt sensor node will measure the moving of tree stem and temperature. It is also acts as gateway to receive data from moisture sensor.
Then the tilt sensor node will send the collected data to Sigfox backend through Pycom module that acts as Sigfox transmitter. Sigfox Cloud Callback will forward the data to external Thingspeak cloud for data storing and analysis.
In Thingspeak dashboard, we will then visualize the sensor value and analyze the tree sensor data (Movement in angles and soil moisture value). After threshold rules setting through analysis, Thingspeak will send alerts to Twitter or Email, to alert users of the abnormalities of the tree whenever happened.
Sensor 01 - Accelerometer & GyroscopeSensor Selection
As we need to measure the movement in 3 axis, there is a need to search for a gyro sensor. After research, we have selected the MPU6050. MPU6050 is a MEMS accelerometer and a MEMS gyro in a single chip. It is very accurate, as it contains 16-bits analog to digital conversion hardware for each channel. It captures the x, y, and z channel at the same time. The sensor uses the I2C-bus to interface with the Arduino.
The sensor is selected among the various type available sensors due to its resources is widely available and easily purchase at any electronics shop. We are using the MPU6050 library from Jeff Rowberg as he has done an excellent job to make the reading stable and accurate with the help of on-board Digital Motion Processor™ (DMP). It can also be installed from Arduino Library Manager.
Connection Diagram
Arduino 5V -> MPU6050 VCC
Arduino GND -> MPU6050 GND
Arduino A5 -> MPU6050 SCL
Arduino A4 -> MPU6050 SDA
Arduino D2 -> MPU6050 INT
Testing Program
MPU6050_DMP6 example program is used for functionality check of the sensor. It can be installed either from examples or download from the github. We are using pitch/roll/yaw angles output format as it is needed to measure the movement of tree stem under normal condition.
#define OUTPUT_READABLE_YAWPITCHROLL
We also modify the output to make it more readable
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
// Serial.print("ypr\t");
float y,p,r;
y=ypr[0]* 180/M_PI;
p=ypr[1]* 180/M_PI;
r=ypr[2]* 180/M_PI;
Serial.print("Yaw: ");
Serial.print(y);
Serial.print("Pitch: ");
Serial.print(p);
Serial.print("Roll: ");
Serial.println(r);
#endif
Below is the Arduino first testing result of the sensor.
Calibration
During first output of the sensor, we realize that there is a need to calibrate the MPU6050 for better accuracy. We have found the guide provided by Tanishqon inscrutable and tested it. A program named imu_zerois used It helps us to find the necessary offset value needed for the testing program.
The offset values are used to replaced the offset value at MPU6050_DMP6 example program.
// supply your own gyro offsets here, scaled for min sensitivity
mpu.setXGyroOffset(-153);//220
mpu.setYGyroOffset(35);//76
mpu.setZGyroOffset(-4);//-85
mpu.setXAccelOffset(-3076); // 1688 factory default for my test chip
mpu.setYAccelOffset(224);
mpu.setZAccelOffset(3076);
Testing through 3D simulation
The raw value of the sensor output is not easily visualize. Thus we have explored the usage Processing 3D feature to accept and display the data in 3D format. With information from Aritro blog at Hackathon website, we managed to create a 3D simulation for the sensors.
Modification needed on the MPU_DM6 program.
#ifdef OUTPUT_READABLE_YAWPITCHROLL
// display Euler angles in degrees
mpu.dmpGetQuaternion(&q, fifoBuffer);
mpu.dmpGetGravity(&gravity, &q);
mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
// Serial.print("ypr\t");
float y,p,r;
y=ypr[0]* 180/M_PI;
p=ypr[1]* 180/M_PI;
r=ypr[2]* 180/M_PI;
Serial.print(y );
Serial.print("/");
Serial.print(p );
Serial.print("/");
Serial.println(r );
#endif
Install the processing software from here.
Source code for 3D processing
We have found the first 3D processing program the reference from Dejan. Below is the modified version to show the status of the sensor sensing in 3D format.
/*
Arduino and MPU6050 IMU - 3D Visualization Example
by Dejan, https://howtomechatronics.com
*/
import processing.serial.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
Serial myPort;
String data="";
float roll, pitch,yaw;
int interval = 0;
void setup() {
size (1200, 1000, P3D);
myPort = new Serial(this, "COM6", 115200); // starts the serial communication
//myPort.write('r');
myPort.bufferUntil('\n');
}
void draw() {
if (millis() - interval > 1000) {
// resend single character to trigger DMP init/start
// in case the MPU is halted/reset while applet is running
myPort.write('r');
interval = millis();
}
//translate(width/2, height/2, 0);
translate(width/2, height/2, 0);
background(10);
textSize(30);
text("Roll: " + int(roll) + " Pitch: " + int(pitch) + " Yaw: " + int(yaw), -100, 300);
// Rotate the object
rotateX(radians(-pitch));
rotateZ(radians(roll));
rotateY(radians(yaw));
// 3D 0bject
textSize(30);
fill(127,255,0);
//box (400, 100, 120); // Draw box
cylinder(50,50,300,50);
textSize(25);
fill(0, 0, 0);
text("Tree Tilting Sensor Ver 1.0", 0, 50, 120);
//delay(10);
//println("ypr:\t" + angleX + "\t" + angleY); // Print3 the values to check whether we are getting proper values
}
// Read data from the Serial Port
void serialEvent (Serial myPort) {
// reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
data = myPort.readStringUntil('\n');
print(data);
// if you got any bytes other than the linefeed:
if (data != null) {
data = trim(data);
// split the string at "/"
String items[] = split(data, '/');
if (items.length > 1) {
// Roll,Pitch in degrees
roll = float(items[0]);
pitch = float(items[1]);
yaw = float(items[2]);
}
}
}
void cylinder(float bottom, float top, float h, int sides)
{
pushMatrix();
translate(0,h/2,0);
float angle;
float[] x = new float[sides+1];
float[] z = new float[sides+1];
float[] x2 = new float[sides+1];
float[] z2 = new float[sides+1];
//get the x and z position on a circle for all the sides
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x[i] = sin(angle) * bottom;
z[i] = cos(angle) * bottom;
}
for(int i=0; i < x.length; i++){
angle = TWO_PI / (sides) * i;
x2[i] = sin(angle) * top;
z2[i] = cos(angle) * top;
}
//draw the bottom of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, -h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
}
endShape();
//draw the center of the cylinder
beginShape(QUAD_STRIP);
for(int i=0; i < x.length; i++){
vertex(x[i], -h/2, z[i]);
vertex(x2[i], h/2, z2[i]);
}
endShape();
//draw the top of the cylinder
beginShape(TRIANGLE_FAN);
vertex(0, h/2, 0);
for(int i=0; i < x.length; i++){
vertex(x2[i], h/2, z2[i]);
}
endShape();
popMatrix();
}
We are happy with the final result. It is easier for us to visualize and also modify the Arduino program to test the reliability of the sensor now.
What is capacitive moisture sensor?
Devashish has shared the advantages of the capacitive moisture sensor compared to resistive sensor in his blog. We agreed and proceed to use the capacitive sensor for the project.
Connection Diagram
Arduino 5V -> Sensor VCC
Arduino GND -> Sensor GND
Arduino A0 -> Sensor Signal
First testing code
void setup() {
Serial.begin(9600); // open serial port, set the baud rate as 9600 bps
}
void loop() {
int val;
val = analogRead(0); //connect sensor to Analog 0
Serial.println(val); //print the value to serial port
delay(100);
}
Calibration of capacitive moisture sensor
DFrobots has provided a details explanation on the calibration of the capacitive sensors. the information is available here.
Capacitive Moisture Sensor's Calibration
1. Run the first testing program from above.
2. Record the sensor value when the probe is exposed to the air as "Value 1". This is the boundary value of dry soil “Humidity: 0%RH”.
3. Take a cup of water and insert the probe into it no further than the red line in the diagram.
4. Record the sensor value when the probe is exposed to the water as "Value 2". This is the boundary value of moist soil “Humidity: 100%RH”
Replace below variable with the finding
const int AirValue = 520; //you need to replace this value with Value_1
const int WaterValue = 260; //you need to replace this value with Value_2
Final Soil Sensor Arduino Program
/***************************************************
/* This example reads Capacitive Soil Moisture Sensor.
Created 2015-10-21
By berinie Chen <bernie.chen@dfrobot.com>
GNU Lesser General Public License.
See <http://www.gnu.org/licenses/> for details.
All above must be included in any redistribution
****************************************************/
/***********Notice and Trouble shooting***************
1.Connection and Diagram can be found here: https://www.dfrobot.com/wiki/index.php?title=Capacitive_Soil_Moisture_Sensor_SKU:SEN0193
2.This code is tested on Arduino Uno.
3.Sensor is connect to Analog 0 port.
****************************************************/
const int AirValue = 520; //you need to replace this value with Value_1
const int WaterValue = 260; //you need to replace this value with Value_2
int intervals = (AirValue - WaterValue)/3;
int soilMoistureValue = 0;
void setup() {
Serial.begin(9600); // open serial port, set the baud rate to 9600 bps
}
void loop() {
soilMoistureValue = analogRead(A0); //put Sensor insert into soil
if(soilMoistureValue > WaterValue && soilMoistureValue < (WaterValue + intervals))
{
Serial.println("Very Wet");
}
else if(soilMoistureValue > (WaterValue + intervals) && soilMoistureValue < (AirValue - intervals))
{
Serial.println("Wet");
}
else if(soilMoistureValue < AirValue && soilMoistureValue > (AirValue - intervals))
{
Serial.println("Dry");
}
delay(100);
}
Zigbee RF ModulesXbee Zigbee Modules are used for interconnection between moisture and tilting sensors. We have learn the connectivity and programming of Xbee from codebender_cc website.
Below codes are used for moisture sensor node to send data to the tilting sensor node. Tilting sensor then will send the consolidated sensors data to cloud through Pycom Sigfox transmitter.
Connection Diagram for Arduino to Zigbee Modules
As the Xbee RF module works in 3.3V and Arduino works in 5V, we connect both DIN and DOUT line through a series 220 ohm resistors to Arduino pins for over-voltage circuit protection. Theoretically a voltage level shifter should be used, but we skipped this due to time constraint.
Arduino 3.3V - > Xbee VIN
Arduino GND - > Xbee GND
Arduino D6-> Xbee Dout
Arduino D7 -> Xbee Din
Testing Code Xbee Communication
Transmitter Code
#include "SoftwareSerial.h"
//Software Serial for XBEE
SoftwareSerial Serial1(6,7); // RX, TX
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial1.print("x");
Serial.print("x");
delay(5000);
}
Receiver Code
#include "SoftwareSerial.h"
//Software Serial for XBEE
SoftwareSerial Serial1(6,7); // RX, TX
unsigned char input;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
while(Serial1.available())
{
input=Serial.read(); //Get data from XBEE
Serial.print(input); //Print received data
}
}
Final Transmitter Code (Located at Moisture Sensor Node)
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6,7); // RX, TX
int soilMoistureValue = 0;
unsigned char mapSoilMoistureValue=0;
unsigned char buff[3];
#define LED1 4
void setup() {
Serial.begin(9600); // open serial port, set the baud rate to 9600 bps
Serial1.begin(9600);
pinMode(LED1, OUTPUT);
blinkLED(5);
Serial.println("Moisture Sensor Node v1.0");
}
void blinkLED(byte cnt)
{
for(int i=0; i<cnt; i++)
{
digitalWrite(LED1,HIGH);
delay(50);
digitalWrite(LED1,LOW);
delay(50);
}
}
void loop() {
soilMoistureValue = analogRead(A0); //put Sensor insert into soil
mapSoilMoistureValue=map(soilMoistureValue,0,1023,0,255);
//Send to nodes through Xbee
buff[0]=0x66;
buff[1]=mapSoilMoistureValue;
Serial1.write(buff[0]);
Serial1.write(buff[1]);
//Local Printout for debug
Serial.print("Sent: ");
Serial.print(buff[0]);
Serial.print(", ");
Serial.println(buff[1]);
blinkLED(5);
delay(5000);
}
Final Receiver Code (Located at Tilting Sensor Node)
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6,7); // RX, TX
int mapSoilMoistureValue=0;
char buff[10];
#define LED1 4
void setup() {
Serial.begin(9600); // open serial port, set the baud rate to 9600 bps
Serial1.begin(9600);
pinMode(LED1, OUTPUT);
blinkLED(5);
Serial.println("Tilting Sensor Node v1.0");
}
void blinkLED(byte cnt)
{
for(int i=0; i<cnt; i++)
{
digitalWrite(LED1,HIGH);
delay(50);
digitalWrite(LED1,LOW);
delay(50);
}
}
void loop() {
while(Serial1.available()>=2)
{
buff[0]=Serial1.read();
buff[1]=Serial1.read();
if(buff[0]==0x66)
{
mapSoilMoistureValue=buff[1];
Serial.print("Rec: ");
Serial.println(mapSoilMoistureValue);
}
}
}
Pycomp Sigfox Transmitter ModuleSigfox is a Low Power Wide Area Network protocol that enables remote devices to connect using ultra-narrow band (UNB) technology. It operates over large distances compared to WiFi and Bluetooth connection protocols. The protocol is bi-directional, 12 bytes messages can both be sent up to and down from the Sigfox servers up to 140 messages a day.
Pycom Sify Module is a reliable Sigfox transmitter module that sponsored by competition organizer for our project. However the one sent to us was faulty and hence, we have to buy another set from local store. The code used is micro-python and visual studio code is needed to download the program to pycom. The Pycom set up and programming guide can be referred at here. It is suite our application as typical tree locations do not have access to Internet connection.
Sigfox backend registration also is needed to enable the connection to sigfox. The Pycom manufacturer provides free Sigfox subscription for one year.
Pycom SiPy pinouts
Below is the first program we used for the connectivity testing to Sigfox.
from network import Sigfox
import socket
# init Sigfox for RCZ4 (Singapore)
sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ4)
# create a Sigfox socket
s = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
# make the socket blocking
s.setblocking(True)
# configure it as uplink only
s.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)
# send some bytes
s.send(bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]))
# Closes the sigfox socket
s.close()time.sleep(5)
Hooray. We have done the first Pycom connection to Sigfox with the guidance provided by jankrupa's blog and classmates.
Due to to the voltage compatibility issues of Pycom module to typical 5V Arduino sensors, we have decided to use it as a Sigfox transmitter instead. It is connected to our existing Arduino Uno board through serial communication protocol. This will speed up the code development process on the sensor nodes. We have found the sample Arduino serial communication code from here.
Pycom Connection to Arduino Uno
As the Pycom is working in 3.3V and Arduino works in 5V, we connect both TX1 and RX1 line through a series 220 ohm resistors to Arduino pins for circuit protection. Theoretically a voltage level shifter should be used, but we skipped this due to time constraint.
Arduino 5V -> pycom VIN
Arduino GND -> pycom GND
Arduino TX-> pycom RX1
Arduino RX-> pycom TX1
Testing Program for Arduino <=> Pycom Serial Communication
Arduino Code
#include <SoftwareSerial.h>
String serialReadback = "";
void setup() {
Serial.begin(9600);
}
void loop() {
String sMeasTemp = "";
byte temp_Hbyte = 0;
byte temp_Lbyte = 0;
int random_offset = random(1, 10);
byte x_Val = 20 + random_offset;
byte y_Val = 125 - random_offset;
byte z_Val = 200 + random_offset;
byte moist_Val = 224 - random_offset;
float meas_temp = 0.0;
meas_temp = 23.45 + (random_offset/10.0);
temp_Hbyte = floor(meas_temp);
temp_Lbyte = (meas_temp - temp_Hbyte) * 100;
sMeasTemp += temp_Hbyte;
sMeasTemp += ",";
sMeasTemp += temp_Lbyte;
sMeasTemp += ",";
sMeasTemp += x_Val;
sMeasTemp += ",";
sMeasTemp += y_Val;
sMeasTemp += ",";
sMeasTemp += z_Val;
sMeasTemp += ",";
sMeasTemp += moist_Val;
unoSerial.print(sMeasTemp);
while(unoSerial.available() < 0); //Wait for Ack from pycom module
delay(10000);//Send every 10 secs
}
Pycom Python Code
from machine import UART # Tx and Rx (``P3`` and ``P4``)
from network import Sigfox
import binascii
import socket
import time
import pycom
import sys
pycom.heartbeat(False)
#init Sigfox for RCZ4 (Asia)
sigfox = Sigfox(mode=Sigfox.SIGFOX,rcz=Sigfox.RCZ4)
uart1 = UART(1, baudrate=9600)
uart1.init(9600,bits=8,parity=None, stop=1, pins = ('P3', 'P4'), timeout_chars=20)
#uart1.write('1,34,56') #serial write to uno
while True:
try:
recv=uart1.readline() #
print("Recv : %s" %(recv))
if recv != None:
print("Enter if.")
#print Sigfox DeviceID
print(binascii.hexlify(sigfox.id()))
# print Sigfox PAC number
print(binascii.hexlify(sigfox.pac()))
#create Sigfox socket
sk1 = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
#make thesocket blocking
sk1.setblocking(False)
#configure as uplink only
sk1.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)
dataList = recv.decode("utf-8")
if(len(dataList) > 10):
print("dataList : %s" %(dataList))
split_val = dataList.split(",")
temp_H = int(split_val[0])
temp_L = int(split_val[1])
x_Val =int(split_val[2])
y_Val =int(split_val[3])
z_Val =int(split_val[4])
moist_Val = int(split_val[5])
print("temp_H : %d temp_L : %d x_Val : %d y_Val : %d z_Val : %d moist_Val : %d" % (temp_H, temp_L,x_Val,y_Val,z_Val,moist_Val))
bData = [temp_H,temp_L,x_Val,y_Val,z_Val,moist_Val]
print(bData)
meas_temp = temp_H + (temp_L*0.01)
print("measure temperature : %.2f" %(meas_temp))
sk1.send(bytes(bData))
uart1.write("OK")
sk1.close()
time.sleep(5)
else:
uart1.write("Error")
except KeyboardInterrupt:
sys.exit()
Set Up Sigfox Backend CallbackSigfox backend is a platform for us to store Sigfox sensor node data and forward the data to external cloud. We learned the configuration methods of Sigfox backend here.
Verification of Callback configuration.
We verified the callback configuration through below Device Messages tab.
After the confirmation of the data transmission from Sigfox, we continue the setting up the Thingspeak IoT Cloud.
Set Up Thingspeak CloudThingSpeak is an IoT analytics platform service that allows us to aggregate, visualize, and analyze live data streams in the cloud.. The instruction on how to use the cloud can be found here.
We have created a channel for storing of sensor data.
We have named all the used variables in the project under the channel.
Cloud Visualization
We have created six data for the sensors nodes: X, Y, Z, temperature and soil moisture value. Five graphs are used for the visualization purpose.
As we send the temperature data in lower & upper byte format due to Sigfox Callback configuration, there is a need to combine the both data to a single temperature value and output to field 6 of data channels. Method used is according to the instruction provided here.
Matlab Analysis Apps Script (Combine Channels Data)
% Script for the temperature data processing
% Channel ID to read data from
readChannelID = 000000; %replace with your Channel ID
% Temperature Field ID
temperatureUpperFieldID = 1;
temperatureLowerFieldID = 2;
% Channel Read API Key
% If your channel is private, then enter the read API
% Key between the '' below:
readAPIKey = 'xxxxxxxxxxxxxx';%replace with your read key
% Read the latest temperature data from the MathWorks Weather Station.
% Learn more about the THINGSPEAKREAD function by going to the Documentation tab on
% the right side pane of this page.
tempUpper = thingSpeakRead(readChannelID,'Fields',temperatureUpperFieldID,'ReadKey',readAPIKey);
tempLower = thingSpeakRead(readChannelID,'Fields',temperatureLowerFieldID,'ReadKey',readAPIKey);
% Convert to Celsius
tempC = tempUpper+tempLower/100.0; %(5/9)*(tempF-32);
display(tempC,'Temperature in Celsius');
fprintf(['Note: To write data to another channel, assign the write channel ID \n',...
'and API Key to ''writeChannelID'' and ''writeAPIKey'' variables. Also \n',...
'uncomment the line of code containing ''thingSpeakWrite'' \n',...
'(remove ''%%'' sign at the beginning of the line.)']);
% To store the temperature in Celsius, write it to a channel other than
% the one used for reading data. To write to a channel, assign the write
% channel ID to the 'writeChannelID' variable, and the write API Key to the
% 'writeAPIKey' variable below. Find the write API Key in the right side pane
% of this page.
% Replace the [] with channel ID to write data to:
writeChannelID = 000000; %replace with your Channel ID
% Enter the Write API Key between the '' below:
writeAPIKey = 'xxxxxxxxxxxxxx';%replace with your write key
temperatureWriteFieldID=7;
% Learn more about the THINGSPEAKWRITE function by going to the Documentation tab on
% the right side pane of this page.
thingSpeakWrite(writeChannelID,'Fields',temperatureWriteFieldID,'Values',tempC ,'WriteKey',writeAPIKey);
To make sure the data is updated during insertion, we need to further configure the apps to react during data insertion.
Final Temperature Display
Final display after the script ran successfully. With the react configuration, the Field 7 : Temperature will be updated automatically during each insertion.
During abnormalities happened, the system will send the signal to the cloud. We have learned also how to use IFFT to send email and twitter to send the twitter social media message to us when the cloud detects abnormalities.
W have created the React to response to the sensor data. Whenever a abnormal situation happened, an email will be sent to technician.
Below is the sample alert email sent by using IFFT.
We learned the configuration of twitter here.
As people are prefer to use social media, we have also activated the twitter alerts. The twitter message is activated with the React plugin and will trigger whenever the alert status is no equal to 0. (sensor abnormality has been detected).
Matlab Analysis Script to Generate Alert SignalFurthermore, we are using another Matlab script to analyse and process the tilt sensor and soil sensor data. An alert channel has been created for the alert purpose.
After analyse the incoming angle data, the final status is sent to Alert Channel Field 2 (Alerts) for user alerts through email, iFTTT app or twitter with the help of Thingspeak REACT plugin. The usage of second channel is due to the limitation of the free user access where the user is not allowed to write to the same channel within 15 seconds.
Final Matlab Script Used For the Alert Status
% Read and generate alerts for Tree Falling Project
% Channel ID to read data from
readChannelID = 000 ;%replace your channel id here
% Temperature Field ID
temperatureUpperFieldID = 1;
temperatureLowerFieldID = 2;
X_FieldID=3;
Y_FieldID=4;
Z_FieldID=5;
Moisture_FieldID=6;
% Channel Read Private API Key
readAPIKey = 'XXX'; %replace your key here
% Read the latest data from channel.
data=thingSpeakRead(readChannelID,'ReadKey',readAPIKey);
tempH = data(1:1);
tempL = data(2:2);
X_Val =data(3:3);
Y_Val =data(4:4);
Z_Val = data(5:5);
moisture_Val = data(6:6);
% Convert to Celsius
tempC = tempH +tempL /100;
% Display Data
display(tempC,'Temperature in Celsius');
display(X_Val,'X Value');
display(Y_Val,'Y Value');
display(Z_Val,'Z Value');
display(moisture_Val,'Moisture');
% Condition Checking. Need to modify according to existing angles.
//Default Optimum value
X_Axis_default = 92 ;%degree
Y_Axis_default = 123;% degree
Z_Axis_default = 90.5; %degree
alertStatus=0;
if X_Val>X_Axis_default+20 || X_Val<X_Axis_default-20
alertStatus=alertStatus + 1;
end
if Y_Val>Y_Axis_default+20 || Y_Val<Y_Axis_default-20
alertStatus=alertStatus + 2;
end
if Z_Val>Z_Axis_default+20 || Z_Val<X_Axis_default-20
alertStatus=alertStatus + 4;
end
if moisture_Val<50
alertStatus=alertStatus + 8;
end
display(alertStatus,'Alert Value');
% Replace the [] with channel ID to write data to:
writeChannelID = 000 ;%replace your channel id here
% Enter the Write API Key between the '' below:
writeAPIKey = 'XXX'; %replace your key here
temperatureWriteFieldID=1;
alertFieldID = 2;
thingSpeakWrite(writeChannelID,'Fields',[1,2],'Values',{tempC,alertStatus} ,'WriteKey',writeAPIKey);
Final HardwareBoth modules are powered by 5V 5000 mAh power bank during the field test. We also tried the power from solar panel that we purchased online. It works well also.
The project has been completed and installed at our school garden for monitoring. All scenarios has been simulated and below is the final result of the installation.
Field Test at School Eco GardenThreshold Setting Through Collected Data
From the graph, it is observed that the current stabilize data value is as below.
//Default Optimum value
Temperature_default = 29;// Celsious
X_Axis_default = 92 ;//degree
Y_Axis_default = 123;// degree
Z_Axis_default = 90.5; // degree
Moisture_default = 72;//0-255
Thus we have used above as the threshold, and to generate the alerts whenever abnormalities happened by using Matlab Analysis Script. The system will generate the email and twitter alerts for below condition.
- Temperature - No alerts.
- X, Y, Z values - When the tree movement is more than 20 degree. Assumption and need further analysis. The 20 degree is set for proof of concept testing purpose.
- Moisture - When the soil moisture is too wet. Less than 50. The threshold is determined after consultation with gardener.
AlertStatus = 0;
if(X_val < X_Axis_default-20 && X_val > X_Axis_default+20)
{
AlertStatus=AlertStatus+1;
}
if(Y_val < Y_Axis_default-20 && Yval > Y_Axis_default+20)
{
AlertStatus=AlertStatus+2;
}
if(Z_val < Z_Axis_default-20 && Z_val > Z_Axis_default+20)
{
AlertStatus=AlertStatus+4;
}
if(moisture < 50)
{
AlertStatus=AlertStatus+8;
}
Field Test Email and Twitter Alerts
We have purposely create the abnormalities by shaking the tree branch. Below is the received data on the tree movement.
Email Alert Generated when abnormalities happened
Twitter Alerts Generated when abnormalities happened
In summary, the first field test has been successfully completed with the functionality been proven.
We are able to
a) Collect the temperature, tree movement in X, Y & Z and soil moisture continuously.
b) Generate alerts whenever abnormalities happened.
Field Test Finding and Learning- It is a feasible, low cost and scalable solution. More moisture or sensor nodes can be fabricated and interconnect with the design.
- A need to use renewable power source.
- Need scaffolding to install the tilts sensors.
- Need more tilt sensors for more tree branches.
- Placement of tilt sensors are important. Suggest to put near center of the branches to minimize the impact of the tree growth on the angle measurement.
- Export the tree tilting angle data through Thingspeak and perform 3D visualisation through the using of 3D Processing as mention in sensor 1 setup.
We have spent totally USD $155 on the project. Complete BOM can be downloaded from attachment tab.
1. To create more tilting sensors with Zigbee RF modules as typical tree have more branches. Need to create more channels and more decision making script for Thingspeak Matlab Analysis. But it is achievable and in progress.
2. To use Raspberry PI as edge processing device and IoT gateway to collect soil moisture and tree tilting sensors, and send the data to Sigfox through Pycom module.
3. To explore the using of more powerful solar panel for actual project deployment. Renewable energy without need for battery replacement.
4. To present the project to school management and seeking contractors help to install the tilt sensor at the tall tree.
5. Currently wind direction and strength is not considered. We are in the process to add in the wind sensor to make the overall analysis more complete. For example varies the angle deviation to larger value when the wind is stronger.
Learning Points from the projectThrough the making of this project, I learnt how Internet of Things can be applied in real life scenarios and how it can solve problems. It is the first time I have learned about Sigfox and its usage in real world. The learning process of the project is tedious. However I am happy that I have learned how to measure the data with sensors, set up Pycom for Sigfox transmission and send data to Thingspeak Cloud through the Sigfox backend. With the guidance of our lecturer, Mr Alex Low, i also learned that we have to plan and think deep into the problem and see if the solution we are able to carry out is feasible and deployable with the usage of waterproof casing and renewable power supply through solar panel.
- Shi Hui, student of Higher Nitec in Electronics Engineering (IoT Specialisation), ITE College Central, Singapore, 2019
Through this project and the guidance of our lecturer: Mr Alex Low, I have learnt how to apply what the IoT project deployment in a real life situation. Additionally, I have learnt to source for cheaper and better alternative sensors for project, and finding useful resources online to help me in the project. After the completion of the project, I am now have a deeper understanding about Sigfox application. This project is a unique, interesting and applicable in real world. It provides me the experience that allows me to learn outside the classroom and make functional Sigfox IoT sensor project.
- Kerine, student of Higher Nitec in Electronics Engineering (IoT Specialisation), ITE College Central, Singapore, 2019
Thanks.
Comments