Perfecting motion

Were you able to find any flaws in the previous code? They are not hard to find; the code works brilliantly when it's only a single person in the room. If this is installed somewhere where multiple people are coming and going, then it might be challenging. This is because whenever a person moves outside, the light will be turned off.

So now that the problem is evident, it's time to make the code even more better. To do this, the hardware will remain exactly the same; we simply need to make the code smarter. Let's see how we can do that:

import GPIO library
import RPi.GPIO as GPIO
import time
import time
import Adafruit_ADS1x15
adc0 = Adafruit_ADS1x15.ADS1115()
GAIN = 1
adc0.start_adc(0, gain=GAIN)
adc1.start_adc(1, gain=GAIN)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
PCount = 0
while True:
F_value = adc0.get_last_result()
F1 = (1.0 / (F_value / 13.15)) - 0.35
time.sleep(0.1)
F_value = adc0.get_last_result()
F2 = (1.0 / (F_value / 13.15)) - 0.35
F0_final = F1-F2
if F0 > 10 :
Time0 = time.time()
F_value = adc1.get_last_result()
F1 = (1.0 / (F_value / 13.15)) - 0.35
time.sleep(0.1)
F_value = adc1.get_last_result()
F2 = (1.0 / (F_value / 13.15)) - 0.35
F1_final = F1-F2
if F1 > 10:
Time1 = time.time()
if Time1 > Time0:
PCount = PCount + 1
if Time1 < Time0:
PCount = PCount - 1

if PCount > 0:

GPIO.output(LIGHT, GPIO.HIGH)
else if PCount = 0:
GPIO.output(LIGHT, GPIO.LOW)

What we have done is something really basic. We have declared a variable called PCount. This variable is declared to count the number of people who are there inside a room or a home. As you can see in the first few lines of the code, we have declared the value of PCount as 0. We are assuming that once we start this, the number of people inside would be 0

    if Time1 > Time0:

PCount = PCount + 1

Whenever the condition if Time1 > Time0: is satisfied, the PCount value is incremented by 1. As we all know, the condition will only be true when a person is walking inside the home.

    if Time1 < Time0:

PCount = PCount - 1

Similarly, when a person is walking outside, the condition if Time1 < Time0: is true; whenever that happens, the value of PCount is decremented by 1

    if PCount > 0:

GPIO.output(LIGHT, GPIO.HIGH)

Now that we have started counting the number of people in the room, we are now applying the condition, which will turn on if the number of PCount is more than 0. Hence, the light will be on for the time when the number of people inside the home is more than 0

    else if PCount = 0:

GPIO.output(LIGHT, GPIO.LOW)

In a very similar fashion, the lights will be turned off if the value of PCount or the number of people inside the home gets to 0

Hence, nailed! 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.130.24