Python Robotics Projects
上QQ阅读APP看书,第一时间看更新

Making the robot

Now, let's get down to making the robot. Firstly, you need to make the water connection from the tap to the solenoid and from the solenoid to the sprinkler. You also have to make the connection, as follows:

Now let's start programming. We will be interfacing a soil moisture sensor in this robot. The job of this sensor is to determine the amount of water in the soil. By determining this, we can understand if the garden needs water or not. This soil moisture sensor is an analogue sensor, hence we will be using an ADC to convert the analogue reading to Pi-understandable digital values. So let's get going:

import time
import RPi.GPIO as GPIO
import Adafruit_ADS1x15
water_valve_pin = 23
moisture_percentage = 20
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(water_valve_pin, GPIO.OUT)
adc = Adafruit_ADS1x15.ADS1115()
channel = 0
GAIN = 1
while True:
adc.start_adc(channel, gain=GAIN)
moisture_value = adc.get_last_result()
moisture_value= int(moisture_value/327)
print moisture_value
if moisture_value < moisture_percentage:
GPIO.output(water_valve_pin, GPIO.HIGH)
time.sleep(5)
else:
GPIO.output(water_valve_pin, GPIO.LOW)

Before you run this code, let's understand what it is actually doing:

moisture_percentage = 20

moisture_percentage = 20 is the percentage that will act as a threshold; if the moisture level in the soil becomes less than 20% then your garden needs water. It is this condition that your robot will keep looking for; once this condition is met then appropriate action can be taken. This percentage can also be changed to 30, 40, or any other value as per your garden's needs:

moisture_value = int(moisture_value/327)

The ADC is a 16-bit device—there are 16 binary digits that can represent a value. Hence, the value can be between 0 and 215 or, in other words, between 0 and 32768. Now, it is simple math that for every percentage of moisture the ADC will give the following reading: 32768/100, or 327.68. Hence, to find out the percentage of moisture in the soil, we would have to pide the actual value given by the ADC by 327.68.

The rest of the code is fairly simple and, once you go through it, it won't be very hard for you to understand.