joan2937 / pigpio

pigpio is a C library for the Raspberry which allows control of the General Purpose Input Outputs (GPIO).
The Unlicense
1.47k stars 410 forks source link

pigpio callback issue with threads #581

Open 316usman opened 1 year ago

316usman commented 1 year ago

I am using the pigpio library to read an encoder and convert its value into degrees. One big issue I face is that to my understanding the pigpio.callback uses its own thread and has its own memory. To start the encoder reading process I use a multiprocessing.Queue to get information about a signal (homing complete) and then I want to start reading the pulses. The trouble is even by using multiprocessing.Queue or even a threading.queue() i cannot get the callback function to read the value from the thread (probably because callbacks run in their own special type of thread.

` class encoder_T(Thread): def init(self, pinNumber1, direction_pin, scale_value, calibration_value, gpio, port_number, homing_queue): super().init() self.gpio = gpio self.pinNumber1 = pinNumber1 self.direction_pin = direction_pin self.calibration_value = calibration_value self.cb1 = self.gpio.callback(self.pinNumber1, pigpio.EITHER_EDGE, self.callback_func) self.cb2 = self.gpio.callback(self.direction_pin, pigpio.EITHER_EDGE, self.callback_func) self.scale_value = scale_value self.position_pulses = 0 self.position_degrees = 0 self.direction = 0 self.homing_queue = homing_queue self.HOMING = False

def callback_func(self, pinNumber, level, tick):

    if pinNumber == self.direction_pin and self.HOMING == True:
        self.direction = level
    elif self.HOMING == True:
        if self.direction:
            self.position_pulses += 1
        else:
            self.position_pulses -= 1
    self.position_degrees = ((self.position_pulses % self.calibration_value + self.calibration_value) % self.calibration_value * self.scale_value) / self.calibration_value
    print (self.position_degrees)

def run(self):
    while True:
        if self.homing_queue.get() == True:
            self.HOMING = True
        elif self.homing_queue.get() == False:
            self.HOMING = False
        time.sleep(0.001)

`

In this code a pass a multiprocessing.Queue() to this thread (because another process was responsible for that signal), and then use the .get() method to get its value and store in a local class variable but the callback function is not able to read that variable. Im just printing to show in reakl scenario it will be sent via udp protocol.

@joan maybe you can clarify, It is also suggested not to read a gpio within the callback in the documentation.

Anyway around for this. Need urgent help

Also posted this on the raspi forums