papous
Posts: 74
Joined: Fri Jan 05, 2018 5:50 am

GPIO to PIGPIO translation

Fri Feb 14, 2020 4:17 pm

Hi everyone
I am trying to use an LDR to measure ambient light using the code below:

Code: Select all

import RPi.GPIO as GPIO
import pigpio
import time
pin_to_circuit = 18
LDR_PIN=18
pi = pigpio.pi()
def rc_time (pin_to_circuit):
    count = 0
  
    #Output on the pin for capacitor
    #GPIO.setup(pin_to_circuit, GPIO.OUT)
    #GPIO.output(pin_to_circuit, GPIO.LOW)
    pi.set_mode(LDR_PIN, pigpio.OUTPUT)
    pi.write(LDR_PIN, pigpio.LOW)

    time.sleep(0.1)

    #Change the pin back to input
    #GPIO.setup(pin_to_circuit, GPIO.IN)
    pi.set_mode(LDR_PIN, pigpio.INPUT)
  
    #Count until the pin goes high
    #while (GPIO.input(pin_to_circuit) == GPIO.LOW):
    while (pi.read(LDR_PIN) == pigpio.LOW): 
        count += 1

    return count
#Catch when script is interrupted, cleanup correctly
try:
    # Main loop
    while True:
        print (rc_time(pin_to_circuit))
except KeyboardInterrupt:
    exit
As you can see I tried translating code that uses the GPIO library to PIGPIO
The GPIO code works fine giving counts between 50 and 100.
The PIGPIO code does not work as it gives counts of 1 or 2

Can anyone suggest why this happens?
By the way joan's pot_cap.py code also works fine

Many thanks for your time

Forris
Raspberry Pi Certified Educator
Raspberry Pi Certified Educator
Posts: 301
Joined: Fri Jan 06, 2012 7:46 pm

Re: GPIO to PIGPIO translation

Mon Feb 17, 2020 4:14 pm

Unless you have a particular reason for using pigpio, have you tried using the gpiozero library?

https://gpiozero.readthedocs.io/en/stab ... ght-sensor

User avatar
joan
Posts: 14654
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: GPIO to PIGPIO translation

Mon Feb 17, 2020 4:24 pm

The loop speed discrepancy is because of the way the pigpio Python module works. It uses the pigpio daemon to provide GPIO services. It talks to the pigpio daemon via a network socket interface. This interface is inherently much slower than directly talking to the hardware. Each read might take half a millisecond with pigpio but only a few microseconds with RPi.GPIO.

Generally this is not a problem and workarounds can always be found with such as scripts when it does cause problems (as is indeed the case with pot_cap.py).

papous
Posts: 74
Joined: Fri Jan 05, 2018 5:50 am

Re: GPIO to PIGPIO translation

Mon Feb 17, 2020 4:51 pm

Thank you both for your replies

Return to “Automation, sensing and robotics”