Elmin Delibašić
Published © GPL3+

SORACOM: Smart Agriculture

Smart agriculture is very topical these days, so I will give you a conceptual solution for Smart Agriculture with SORACOM and devices.
  • Difficulty: Advanced
  • Type: tutorial
  • Duration: 50 hours
  • Views: 3828
SORACOM: Smart Agriculture

Things used in this project

Hardware components

Relay Module (Generic) × 1
Water Valve × 1
Ceramic Capacitive Rain Sensor Ceramic Capacitive Rain Sensor × 1
Grove - Barometer Sensor (BMP280) Grove - Barometer Sensor (BMP280) × 1
DHT11 Temperature & Humidity Sensor (3 pins) DHT11 Temperature & Humidity Sensor (3 pins) × 1
SORACOM Air Global IoT SIM SORACOM Air Global IoT SIM × 1
Raspberry Pi Zero Wireless Raspberry Pi Zero Wireless × 1
SparkFun Soil Moisture Sensor (with Screw Terminals) SparkFun Soil Moisture Sensor (with Screw Terminals) × 1
Battery Holder, 18650 x 1 Battery Holder, 18650 x 1 × 1
TP4056 × 1
Solar Panel 6V × 1
Diode 1n4148 × 1
Huawei E303 Huawei E303 × 1

Software apps and online services

Raspbian Raspbian × 1
SORACOM Harvest SORACOM Harvest × 1
SORACOM Lagoon SORACOM Lagoon × 1
SORACOM Air IoT Connectivity Platform SORACOM Air IoT Connectivity Platform × 1


SORACOM Complete Starter Kit has arrived.Thanks for the product and quick delivery. Package photos are below.SORACOM IoT Starter KitSoracom IoT Starter Kit

- In this project I made a system of monitoring and management of agriculture. I connected some of the sensors to Raspberry Pi. I sent data with Soracom SIM Card to Soracom services.

Stage of the project:Step 1 - 3 (Installing the system on raspberry pi and explaining how to create, launch, and retrieve python scripts necessary to start the project.)Step 4 - 7 (Configuring 3G USB Modem and connecting with SORACOM Services needed for this project.)Step 8 - 12 (Idea, schema, hardwer, pyhton code needed to create a project.)

- Let's start with the basic things that are necessary for the design of the project.

Step 1: How to install Raspbian on Raspberry Pi?Get started, download the .img file on the Raspbian system. Download it from this link.After you download the system image, now you need to boot your , i.e. to mount the image you downloaded to an SD card. Etcher is a graphical SD card writing tool recommended by Raspberry pi community. Download Etcher and install it.
  • Connect an SD card reader with the SD card inside.
  • Open Etcher and select from your hard drive the Raspberry Pi .img file you wish to write to the SD card.
  • Select the SD card you wish to write your image to.
  • Review your selections and click 'Flash!' to begin writing data to the SD card.
  • Executing the previous steps on your SD card is set by the Raspbian system. Let's move on.Raspberry Pi Zero W, MicroSD Card and micro USB 2.0Raspberry Pi Zero W- Now connect the display (HDMI), mouse and keyboard (USB) to Raspberry Pi Zero W. Connect power and you can start working. (username: pi and password: raspberry)(If you have one, do not take the following steps)- If you don't have a monitor, keyboard, and mouse, then use the linux terminal on your computer. After mounting an image, make two text files on your MicroSD card.With the name "ssh" empty and without extension.Under the name "wpa_supplicant.conf" and enter this code in file:ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev update_config=1 country=US network={ ssid="YOURSSID" psk="YOURPASSWORD" scan_ssid=1 } Replace YOURSSID and YOURPASSWORD with whatever is used for your network setup. - Now after you insert the card into Raspberry Pi and connect it to power, it will connect to the network.

    - In the terminal of your computer, run this command:

    ssh pi@<IP> (username: pi and password: raspberry)<IP> is IP address of your Raspberry Pi. (You can find the IP addresses by scanning ip addresses on your network). Raspberry Pi ssh access via Linux OSRaspbian desktop on Raspberry Pi Zero W (with monitor, mouse and keyboard)When you receive one of two images from above, this means that we made the installation and configuration of system on Raspberry Pi Zero W.One form of protection is to change the access code for your Raspberry Pi Zero W, which will be offered immediately on the start screen after launch. Step 2: How to create and run Python script?- After the previous step, we can now access the terminal at Raspberry. The next command in the terminal is positioned you on Desktop:cd Desktop - Now we can create a new python script using next command:touch script_name.py - Now the script with the name script_name.py is created. You need a text editor to edit this file. The text editor "nano" is installed with next command:sudo apt-get install nano

    - After we installed the nano, we can now edit the created script. To access script editing, you need to run command:

    sudo nano script_name.py

    - To save the edited file, use the following keys on the keyboard:

    Ctrl + X - to exit and save,Y - after Ctrl + X approve save and confirm file name.

    - To start Python script, use this command:

    sudo python3 script_name.py Command: cd DesktopCommand for create Python scriptNano text editor and simple scriptRun Python scriptStep 3: How to run Python script with startup Raspberry Pi?This is necessary because each time when connecting Raspberry Pi to the power supply, the . It's simpler because we will not have to run the script again in the terminal every time.
  • This resolved the user's frustration, user won't have to run script every time when the power supply falls. Now, user must only provide new power, everything else will happens in the background.
  • Let's start with the setting. Run next command in terminal on Raspberry Pi:
  • sudo crontab -e

    Choose editor and enter the next line of code at the end of document:

    @reboot python3 /home/pi/Desktop/script_name.py /home/pi/Desktop/script_name.py is path to the script you want to run.
  • Reboot Raspberry Pi.
  • Now, when you start the Raspberry Pi, the script you selected will automatically launch.Step 4: Installing Python libraries

    Libraries are needed to read data from the BMP280 and DHT11 sensors. This sensors are included in project, therefore libraries need to be installed.

    The installation of the BMP280 library is performed by running next commands in terminal:sudo pip3 install adafruit-circuitpython-bmp280 - After completion, the library is installed for Python version 3. Similarly, libraries for DHT sensors are installed. Let's start bellow commands:git clone https://github.com/adafruit/Adafruit_Python_DHT.git cd Adafruit_Python_DHT sudo python3 setup.py install

    - Now, all libraries for project are installed.

    Step 5: Install and Configure the 3G USB ModemHUAWEI MS2131 USB Stick (Modem)HUAWEI USB ModemSORACOM SIM Card and HUAWEI USB Modem- Now let's look at how to configure Raspberry Pi to communicate over 3G modem and SORACOM Global SIM:Download and install the Soracom Starter Kit modem setup script with this terminal command (on Raspberry Pi):sudo curl -O https://soracom-files.s3.amazonaws.com/starterkit/setup.sh
  • Next, modify the file properties so we can run it:
  • sudo chmod +x setup.sh
  • Then all we have to do is run it, and the script will take care of everything else:
  • sudo ./setup.sh The setup.sh script will first install some required packages and get our Raspberry Pi prepared. Once it’s ready, it will ask us to plug in our modem. After plugging in modem, you will see "Setup complete!"HUAWEI 3G USB Modem and Raspberry Pi Zero W- If the connection is confirmed, we can now use the modem on Raspberry, and with it SORACOM SIM Card, which is in the modem. This step is also explained on IoT Starter Kit.Step 6: Configure SORACOM Harvest- Using SORACOM Harvest service we can collect and visualize data sent from RPi (Raspberry Pi) via SORACOM SIM Card. Let's start with setting up SORACOM Harvest.Let's log in to Soracom User Console. (If you have not set Soracom SIM card on the page, you can do this by following instructions on this page)After signing up on the page, click on the Menu in the upper left corner and select Groups. Click on button +Add and insert optional name.Click Create and find SORACOM Harvest drop-down menu. Click the switch in the SORACOM Harvest drop-down menu, change it to ON, and click the Save button.Click on Menu in upper left corner and select SIM Managment.Check box left of your SIM card and select Actions drop-down menu.Select Change Group, select your group.Click on Update blue button.- Now, when we set the harvest, let's try to send data with RPi to SORACOM Harvest via HTTP protocol (You need to have a connected 3G Modem (SORACOM Global SIM) with Raspberry Pi). In terminal run this commands:curl -v -X POST \ -H 'content-type:application/json' \ -d '{"temperature":20}' \ http://harvest.soracom.io Go to SIM Managment > Select Your SIM > Actions > Harvest data.
  • If everything is done correctly, we can see the message we sent at the bottom and on the diagram.
  • Sending data from terminalHarvest data viewerStep 7: Configure SORACOM LagoonSORACOM Lagoon is dashboard for create graphs, tables, maps and more with just a few clicks. The data collected in SORACOM Harvest service are used to create graphs, tables, etc.

    Let's start making SORACOM Lagoon dashboard:

    Open the Soracom User Console page.Click on Menu and select SORACOM Lagoon.Create SORACOM Lagoon and open it by clicking on SORACOM Lagoon Console.SORACOM LAGOON ConsoleCreate new dashboard (Click + on left menu and click Dashboard).Now select a Graph.New dashboardGraph editorNow it opens the graph editor for adjusting how you want your graph to look like. Choose what you want to be shown on graph, choose the look of the line and shadows on graph as well as the name of graph. (The data menu you can view is all the information you received in SORACOM Harvest. Don't forget to save dashboard (button in the right upper corner or CTRL+S).Step 8: Scheme and details of project!

    - Now let's say something more about the project I'm creating. This project will serve for easier control of agriculture. For the purpose of this project, I used various sensors. Sensors:

    DHT11 (temperature and humidity) sensor,BMP280 (temperature, pressure and altitude) sensor,Soil Moisture sensor,Rain sensor.Graph of communication between servicesRaspberry Pi Zero WHUAWEI 3G USB MODEMSORACOM SIM CardDHT11 sensorBMP280 sensorSoil Moisture sensorRain ModuleRelay moduleWater valveScheme for connecting Raspberry Pi Zero W and sensorsTestingTestingRPi Zero W and HUAWEI 3G USB Modem

    - Now the hardwer is fully connected, we can access the code writing.

    Step 9: Solar power system (Additionally)
  • If you like, you can include an independent power supply for Raspberry Pi and sensors used in the project.
  • Below you can see an example of how to connect the Solar Panel through which the battery will be charged and powered by Raspberry Pi.Solar Power System- The solar panel used in this case is 6V (1W). The diode is used to lower the voltage to a value of 5V as much as the power supply for Raspberry Pi. Module TP 4056 is used to rationally charge and discharge the battery as well as the RPi power supply.Step 10: Python code for project!

    The code for this project is written in Python 3_ programming language and run on Raspberry Pi Zero W as explained at the beginning (Step 2-3). The python script for this project is soracom_smart_agriculture.py (Code section). Let's look at what the individual parts of the code are.

  • At the beginning, the libraries required for the project are included, this is achieved by the following code:
  • import RPi.GPIO as GPIO import time import json import sys, requests import board import busio import digitalio import adafruit_bmp280 import Adafruit_DHT
  • Now it is necessary to define the GPIO pins to which the corresponding sensors and relays will be connected:
  • pin_dht = 14 pin_soil = 15 pin_rain = 18 pin_pump = 21 The following lines invoke commands and determine the pins from which data from the BMP280 sensor will be read: spi = busio.SPI(board.SCK, board.MOSI, board.MISO) bmp_cs = digitalio.DigitalInOut(board.D5) bmp280 = adafruit_bmp280.Adafruit_BMP280_SPI(spi, bmp_cs) bmp280.sea_level_pressure = 1013.25
  • After that, it is necessary to define whether certain pins will be input or output. If we read the data from the sensors, then these are the input pins, and if we control the ignition and extinguishing of the valve, then this is the output pin.
  • GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(pin_dht, GPIO.IN) GPIO.setup(pin_soil, GPIO.IN) GPIO.setup(pin_rain, GPIO.IN) GPIO.setup(pin_pump, GPIO.OUT) The code below uses "while 1:" which means that the code will be infinitely long. Inside while there are calls to read data from the sensor. h, t = Adafruit_DHT.read_retry(11, pin_dht) soil_data = GPIO.input(pin_soil) rain_data = GPIO.input(pin_rain) t_bmp = round(bmp280.temperature, 2) p = round(bmp280.pressure, 2) a = round(bmp280.altitude, 2) The round is used to filter to two decimal places (for example, 12.22)
  • The following lines of code are used to check whether watering is required or not. If necessary, the water valve will start. If rain falls and the water is flooded, the valve will not be triggered because the rain will soak the soil. And if no watering is required, the valve will not turn on.
  • if (soil_data == 0): GPIO.output(pin_pump, GPIO.HIGH) pump_data = 0 else: if (rain_data == 1): GPIO.output(pin_pump, GPIO.LOW) pump_data = 1 else: GPIO.output(pin_pump, GPIO.HIGH) pump_data = 0 Below is a description of how to communicate with the HUAWEI 3G modem and send the data to SORACOM User Console. headers = {'Content-Type': 'application/json'} payload = {'temperature': t_bmp, 'humidity': h, 'soil_moisture': soil_data, 'rain_data': rain, 'pressure': p, 'altitude': a, 'pump_on_off': pump_data } try: r = requests.post('http://harvest.soracom.io', data=json.dumps(payload), headers=headers, timeout=5) except requests.exceptions.ConnectTimeout: print ("ERROR: connection timeout. Is 3G connection online?") sys.exit(1) if r.status_code == 400: print ("ERROR: failed to submit data. Did you enable Harvest for your SIM?") sys.exit(1) print payload is the json file that is sent to SORACOM User Console. It contains all the values ​​read from the sensor as well as the condition of the valve (whether it works or does not work)
  • Last but not the least, it is necessary to set the time that will be between reading:
  • time.sleep(2) 2 in this code is 2 seconds of waiting until re-read.- In the code I attached, I have added a print part to the terminal every time Raspberry Pi read and send the data.Step 11: Finishing project!SORACOM User ConsoleRun python codeTerminal command and printError with 3G connection- In the second picture, we saw an error that occurred due to the transmission of data via the 3G modem. This is an error that will occur if there is a problem connecting to the 3G network or the device (3G Modem) is disconnected.SORACOM HarvestHarvest data application/jsonHarvest data visualizeHarvest data visualizeHarvest data visualize- In Step 6, it is shown how to set up SORACOM Harvest and how to view data, this overview is shown on photos above.SORACOM LagoonSORACOM Lagoon dashboardSORACOM Lagoon dashboardSORACOM Lagoon dashboardStep 12: Testing!Finally, we conclude that we can solve the problem of surveillance of agriculture using SORACOMGlobal SIM card, SORACOMServices and using the hardwarecomponents. If we take advantage of step3 and step9 we can come up with a project that will be able to function independently without the help of people. Namely, SolarPanel will perform charging the battery, thus providing the power for RaspberryPi. If it comes to restarting Raspberry Pi, In step 3 will ensure that the Python script will automatically start, meaning that we will not have to go the plantation (strawberry,raspberry and other) for starting python script and system.Using the sensors and relay we will read and send this data to SORACOM services:
  • Temperature,
  • Pressure,
  • Humidity in air,
  • Humidity in soil,
  • Raining / not raining and
  • Water pump ON/OFF.
  • Soracom Harvest, Soracom Lagoon Dashboard and Terminal printBox with project electronicsSolar Panel and Rain sensor- Green LED diode which You saw in video and on photos is replacement for water valve which we don't have for this project. If green led diode are turned ON, water valve is opened else if green led diode are turned OFF, water valve is closed. Conclusion

    - If we look at the model that was created by this project for the needs of serial production (more devices), it's advantages are:

    Low price (The price of the sensors and elements used in the project is very low (without HUAWEI 3G modem) around 20-30 $),Low price for SORACOM services on a monthly basis (AWS is not involved in the project because I have been aiming to create a project with a low monthly consumption),If a power failure occurs, with a re-power supply, the whole system will automatically start,One of the security is password on Raspberry Pi for accessing the device,It's also possible to add SORACOM Endorse for device authentication.- The video shows a prototype with many visible connections and physically uninsulated devices. If this device is produced by a larger number it is possible to make it PCB design to which the hardware components would be placed and placed in a waterproof box that could protect the electronics from the rain.