• Control blink of LED


  •  
    from gpiozero import LED
    led = LED(4)
    led.blink(on_time = 0.3, off_time = 0.3)
    
    
  • Control blink and fading of LED


  •  
    from gpiozero import LED
    led = LED(4)
    led.blink(on_time = 0.3, off_time = 0.3, fade_in_time = 1.0, fade_out_time = 1.0)
    
    
  • Blinking speed controlled by a push button can be written like this


  •  
    from time import sleep
    from signal import pause
    from gpiozero import LED,Button
    
    led = LED(4) # make pin 4 into an output
    push =  Button(24) # make pin 24 into an input
    print("LED blinker switch using gpiozero - By Mike Cook")
    
    while True:
        led.on()
        if push.is_pressed:
            sleep(0.30)
        else :
            sleep(1.00)
        led.off()
    
    pause()
    
    
  • when_pressed and when_released cause a function to run when the button is pressed or released rather than return any information about the input


  •  
    from gpiozero import LED, Button
    from signal import pause
    led = LED(4) # make pin 4 into an output
    push = Button(24) # make pin 24 into an input
    
    def blinkFast():
        led.blink(on_time = 0.3, off_time = 0.3)
    
    def blinkSlow():
        led.blink(on_time = 1.0, off_time = 1.0)
    
    push.when_pressed = blinkFast
    push.when_released = blinkSlow
    
    pause()
    
    
  • Display pin number of button


  •  
    from gpiozero import Button
    from signal import pause
    
    def say_hello(button):
        print(button.pin)
    
    def say_goodbye():
        print("Goodbye!")
    
    button1 = Button(20)
    button2 = Button(21)
    
    button1.when_pressed = say_hello
    button1.when_released = say_goodbye
    button2.when_pressed = say_hello
    button2.when_released = say_goodbye
    
    pause()
    
    
  • If a switch is pressed multiple times by mistake, then an event may be accidentally called twice. This can be avoided using debouncing.


  •  
    from gpiozero import Button
    from signal import pause
    
    def toggle_led():
        led.toggle()
    
    led = LED(21)
    button = Button(18, bounce_time=0.1)
    
    button1.when_pressed = toggle_led
    
    pause()
    
    
  • Line sensor and its working.


  •  
    from gpiozero import LineSensor
    from signal import pause
    
    def line_event():
        print('Line detected')
    def no_line_event():
        print('No line detected')
        
    sensor = LineSensor(4)
    sensor.when_line = line_event
    sensor.when_no_line = no_line_event
    pause()
    
    
  • Line sensor should run functions if line event is detected for a certain threshold in seconds.


  •  
    from gpiozero import LineSensor
    from signal import pause
    
    def line_event():
        print('Line detected')
    def no_line_event():
        print('No line detected')
        
    sensor = LineSensor(4)
    sensor.wait_for_line(2) = line_event
    sensor.wait_for_no_line(2) = no_line_event
    pause()
    
    
  • Represents a passive infra-red (PIR) motion sensor.


  • A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.


  • The following code will print a line of text when motion is detected:


  •  
    from gpiozero import MotionSensor
    
    pir = MotionSensor(4)
    pir.wait_for_motion()
    print("Motion detected!")
    
    
  • Represents a passive infra-red (PIR) motion sensor.


  • A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.


  • wait_for_motion(timeout=None) wait_for_no_motion(timeout=None)


  • Pause the script until the device is activated, or the timeout is reached.


  • Parameters: timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.


  •  
    from gpiozero import MotionSensor
    
    pir = MotionSensor(4)
    pir.wait_for_motion(10)
    print("Motion detected!")
    pir.wait_for_motion()
    print("Motion not detected even after 10 seconds!")
    
    
  • Represents a passive infra-red (PIR) motion sensor.


  • A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.


  • MotionSensor(pin, *, queue_len=1, sample_rate=10, threshold=0.5, partial=False, pin_factory=None)


  • queue_len (int) – The length of the queue used to store values read from the sensor. This defaults to 1 which effectively disables the queue. If your motion sensor is particularly “twitchy” you may wish to increase this value.


  • sample_rate (float) – The number of values to read from the device (and append to the internal queue) per second. Defaults to 100.


  • threshold (float) – Defaults to 0.5. When the average of all values in the internal queue rises above this value, the sensor will be considered “active” by the is_active property, and all appropriate events will be fired.


  • In one second the motion sensor, samples 10 observations and stores in the internal queue. Then after after one second is over , the average of observations is taken and if that is above a threshold the motion is detected.


  •  
    from gpiozero import MotionSensor
    
    pir = MotionSensor(4, queue_len=10, sample_rate=10, threshold=0.5)
    pir.wait_for_motion(1)
    print("Motion detected as threshold crossed within one second!")
    pir.wait_for_motion()
    print("Motion not detected even after 1 second!")
    
    
  • Represents a passive infra-red (PIR) motion sensor.


  • A typical PIR device has a small circuit board with three pins: VCC, OUT, and GND. VCC should be connected to a 5V pin, GND to one of the ground pins, and finally OUT to the GPIO specified as the value of the pin parameter in the constructor.


  • MotionSensor(pin, *, queue_len=1, sample_rate=10, threshold=0.5, partial=False, pin_factory=None)


  • when_motion - The function to run when the device changes state from inactive to active.


  • when_no_motion - The function to run when the device changes state from active to inactive.


  •  
    from gpiozero import MotionSensor
    
    def motion_event():
        print('Motion detected')
    def no_motion_event():
        print('No motion detected')
    
    pir = MotionSensor(4)
    
    pir.when_motion = motion_event
    pir.when_no_motion = no_motion_event
    pause()
    
    
    
    
  • Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).


  • LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)


  •  
    from gpiozero import LightSensor
    
    ldr = LightSensor(18)
    ldr.wait_for_light()
    print("Light detected!")
    
    
  • Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).


  • LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)


  • queue_len (int) – The length of the queue used to store values read from the circuit. This defaults to 5.


  • charge_time_limit (float) – If the capacitor in the circuit takes longer than this length of time to charge, it is assumed to be dark. The default (0.01 seconds) is appropriate for a 1µF capacitor coupled with the LDR. You may need to adjust this value for different valued capacitors or LDRs.


  • threshold (float) – Defaults to 0.1. When the average of all values in the internal queue rises above this value, the area will be considered “light”, and all appropriate events will be fired.


  • We create a queue of length 5, and if average of the entire queue is above threshold then we can print light detected.


  •  
    from gpiozero import LightSensor
    
    ldr = LightSensor(18, queue_len=5, charge_time_limit=0.01, threshold=0.5)
    ldr.wait_for_light()
    print("Light detected!")
    
    
  • Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).


  • LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)


  • queue_len (int) – The length of the queue used to store values read from the circuit. This defaults to 5.


  • charge_time_limit (float) – If the capacitor in the circuit takes longer than this length of time to charge, it is assumed to be dark. The default (0.01 seconds) is appropriate for a 1µF capacitor coupled with the LDR. You may need to adjust this value for different valued capacitors or LDRs.


  • threshold (float) – Defaults to 0.1. When the average of all values in the internal queue rises above this value, the area will be considered “light”, and all appropriate events will be fired.


  • when_dark - The function to run when the device changes state from active to inactive.


  • when_light - The function to run when the device changes state from inactive to active.


  •  
    from gpiozero import LightSensor
    
    def light_event():
        print('Light detected')
    def no_light_event():
        print('No light detected')
    
    ldr = LightSensor(4)
    
    ldr.when_light = light_event
    ldr.when_dark = no_light_event
    pause()
    
    
  • Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).


  • LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)


  • queue_len (int) – The length of the queue used to store values read from the circuit. This defaults to 5.


  • charge_time_limit (float) – If the capacitor in the circuit takes longer than this length of time to charge, it is assumed to be dark. The default (0.01 seconds) is appropriate for a 1µF capacitor coupled with the LDR. You may need to adjust this value for different valued capacitors or LDRs.


  • threshold (float) – Defaults to 0.1. When the average of all values in the internal queue rises above this value, the area will be considered “light”, and all appropriate events will be fired.


  • wait_for_dark(timeout=None) Pause the script until the device is deactivated, or the timeout is reached.


  • wait_for_light(timeout=None) Pause the script until the device is activated, or the timeout is reached.


  •  
    from gpiozero import LightSensor
    
    ldr = LightSensor(4)
    
    ldr.wait_for_light() 
     print('Light detected')
    ldr.wait_for_dark() 
     print('No light detected')
     
    pause()
    
    
     
    from gpiozero import LightSensor
    
    ldr = LightSensor(4)
    
    ldr.wait_for_light(10) 
     print('Light detected within 10 seconds')
    ldr.wait_for_dark(10) 
     print('No light detected even after 10 seconds')
     
    pause()
    
    
  • Connect one leg of the LDR to the 3V3 pin; connect one leg of a 1µF capacitor to a ground pin; connect the other leg of the LDR and the other leg of the capacitor to the same GPIO pin. This class repeatedly discharges the capacitor, then times the duration it takes to charge (which will vary according to the light falling on the LDR).


  • LightSensor(pin, *, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None)


  • light_detected - Returns True if the value currently exceeds threshold and False otherwise.


  • pin - The Pin that the device is connected to. This will be None if the device has been closed (see the close() method). When dealing with GPIO pins, query pin.number to discover the GPIO pin (in BCM numbering) that the device is connected to.


  • value - Returns a value between 0 (dark) and 1 (light).


  •  
    from gpiozero import LightSensor
    
    ldr = LightSensor(4)
    print("light detected",ldr.light_detected)
    print("LDR connected at",ldr.pin)
    print("Is it dark",ldr.value)
    pause()
    
    
  • HC-SR04 ultrasonic distance sensor


  • The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:


  • Connect the GND pin of the sensor to a ground pin on the Pi.


  • Connect the TRIG pin of the sensor a GPIO pin.


  • Connect one end of a 330Ω resistor to the ECHO pin of the sensor.


  • Connect one end of a 470Ω resistor to the GND pin of the sensor.


  • Connect the free ends of both resistors to another GPIO pin. This forms the required voltage divider.


  • Finally, connect the VCC pin of the sensor to a 5V pin on the Pi.


  • Alternatively, the 3V3 tolerant HC-SR04P sensor (which does not require a voltage divider) will work with this class.


  • The following code will periodically report the distance measured by the sensor in cm assuming the TRIG pin is connected to GPIO17, and the ECHO pin to GPIO18:


  •  
    
    from gpiozero import DistanceSensor
    from time import sleep
    
    sensor = DistanceSensor(echo=18, trigger=17)
    while True:
        print('Distance: ', sensor.distance * 100)
        sleep(1)
    
    
    
    
  • HC-SR04 ultrasonic distance sensor


  • The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:


  • Connect the GND pin of the sensor to a ground pin on the Pi.


  • Connect the TRIG pin of the sensor a GPIO pin.


  • Connect one end of a 330Ω resistor to the ECHO pin of the sensor.


  • Connect one end of a 470Ω resistor to the GND pin of the sensor.


  • Connect the free ends of both resistors to another GPIO pin. This forms the required voltage divider.


  • Finally, connect the VCC pin of the sensor to a 5V pin on the Pi.


  • Alternatively, the 3V3 tolerant HC-SR04P sensor (which does not require a voltage divider) will work with this class.


  • The following code will periodically report the distance measured by the sensor in cm assuming the TRIG pin is connected to GPIO17, and the ECHO pin to GPIO18:


  • queue_len (int) – The length of the queue used to store values read from the sensor. This defaults to 30.


  • max_distance (float) – The value attribute reports a normalized value between 0 (too close to measure) and 1 (maximum distance). This parameter specifies the maximum distance expected in meters. This defaults to 1.


  • threshold_distance (float) – Defaults to 0.3. This is the distance (in meters) that will trigger the in_range and out_of_range events when crossed.


  • wait_for_in_range(timeout=None) - Pause the script until the device is deactivated, or the timeout is reached. Parameters: timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is inactive.


  • wait_for_out_of_range(timeout=None) - Pause the script until the device is activated, or the timeout is reached. Parameters: timeout (float or None) – Number of seconds to wait before proceeding. If this is None (the default), then wait indefinitely until the device is active.


  •  
    
    from gpiozero import DistanceSensor
    from time import sleep
    
    sensor = DistanceSensor(echo=18, trigger=17)
    
    
    sensor.wait_for_in_range() 
     print('Within range')
     
    sensor.wait_for_out_of_range(10) 
     print('Outside range')
    
    
    
  • HC-SR04 ultrasonic distance sensor


  • The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:


  • Connect the GND pin of the sensor to a ground pin on the Pi.


  • Connect the TRIG pin of the sensor a GPIO pin.


  • Connect one end of a 330Ω resistor to the ECHO pin of the sensor.


  • Connect one end of a 470Ω resistor to the GND pin of the sensor.


  • Connect the free ends of both resistors to another GPIO pin. This forms the required voltage divider.


  • Finally, connect the VCC pin of the sensor to a 5V pin on the Pi.


  • Alternatively, the 3V3 tolerant HC-SR04P sensor (which does not require a voltage divider) will work with this class.


  • The following code will periodically report the distance measured by the sensor in cm assuming the TRIG pin is connected to GPIO17, and the ECHO pin to GPIO18:


  • queue_len (int) – The length of the queue used to store values read from the sensor. This defaults to 30.


  • max_distance (float) – The value attribute reports a normalized value between 0 (too close to measure) and 1 (maximum distance). This parameter specifies the maximum distance expected in meters. This defaults to 1.


  • threshold_distance (float) – Defaults to 0.3. This is the distance (in meters) that will trigger the in_range and out_of_range events when crossed.


  • when_in_range - The function to run when the device changes state from active to inactive.


  • when_out_of_range - The function to run when the device changes state from inactive to active.


  •  
    
    from gpiozero import DistanceSensor
    from time import sleep
    
    sensor = DistanceSensor(echo=18, trigger=17)
    
    def distance_event():
        print('Distance detected')
    def no_distance_event():
        print('No Distance detected')
    
    
    
    sensor.when_in_range = distance_event
    sensor.when_out_of_range = no_distance_event
    
    
    
  • HC-SR04 ultrasonic distance sensor


  • The distance sensor requires two GPIO pins: one for the trigger (marked TRIG on the sensor) and another for the echo (marked ECHO on the sensor). However, a voltage divider is required to ensure the 5V from the ECHO pin doesn’t damage the Pi. Wire your sensor according to the following instructions:


  • distance - Returns the current distance measured by the sensor in meters.


  • echo - Returns the Pin that the sensor’s echo is connected to.


  • trigger - Returns the Pin that the sensor’s trigger is connected to.


  • value - Returns a value between 0, indicating the reflector is either touching the sensor or is sufficiently near that the sensor can’t tell the difference, and 1, indicating the reflector is at or beyond the specified max_distance.


  •  
    
    from gpiozero import DistanceSensor
    from time import sleep
    
    sensor = DistanceSensor(echo=18, trigger=17,max_distance=5)
    print("how far is object in meters",sensor.distance)
    print("echo pin",sensor.echo)
    print("trigger pin",sensor.trigger)
    print("how far is the object relative to maximum distance",sensor.value)