Как создать обратный вызов для платы Raspberry Pi Zero GPIO - PullRequest
1 голос
/ 18 апреля 2019

Я пытаюсь прочитать фотодатчик (датчик освещенности), опрашивая его. Тем не менее, хотя я жду 1 миллисекунду, прежде чем опросить его снова. Как мне это исправить?

Я попытался сделать мини-звонок с помощью этого:

def my_callback(channel):
    global sensor_1
    global sensor_2
    global sensor_3
    global pin_L1
    global pin_L2
    global pin_hole
    global prev_sensor_1
    global prev_sensor_2
    global prev_sensor_3
    global t0
    global t1
    global t2
    global t3
    global t4
    print ("Both edges detected on", channel)
    if t3 == 0 and t2 != 0 and t4 == 0:
        print("Condition satisfied.")
        prev_sensor_2 = sensor_2
        sensor_2 = 1
        t3 = int(time.time()*1000)
    else:
        print(t0, t1, t2, t3, t4, sensor_1, sensor_2, sensor_3, prev_sensor_1, prev_sensor_2, prev_sensor_3)

Но это не работает.

from tkinter import *
import time
import RPi.GPIO as GPIO

t0 = 0
t1 = 0
t2 = 0
t3 = 0
t4 = 0

sensor_1 = 0
sensor_2 = 0
sensor_3 = 0

prev_sensor_1 = 0
prev_sensor_2 = 0
prev_sensor_3 = 0

points = 0

window = Tk()

root = Canvas(window, width=750, height=750, bg='limegreen')

pin_L1 = 7
pin_L2 = 11
pin_hole = 16

def my_callback(channel):
    global sensor_1
    global sensor_2
    global sensor_3
    global pin_L1
    global pin_L2
    global pin_hole
    global prev_sensor_1
    global prev_sensor_2
    global prev_sensor_3
    global t0
    global t1
    global t2
    global t3
    global t4
    print ("Both edges detected on", channel)
    if t3 == 0 and t2 != 0 and t4 == 0:
        print("Condition satisfied.")
        prev_sensor_2 = sensor_2
        sensor_2 = 1
        t3 = int(time.time()*1000)
    else:
        print(t0, t1, t2, t3, t4, sensor_1, sensor_2, sensor_3, prev_sensor_1, prev_sensor_2, prev_sensor_3)

def init_sensors():
    print("Initializing sensors...") # Debug
    global sensor_1
    global sensor_2
    global sensor_3
    global pin_L1
    global pin_L2
    global pin_hole
    global prev_sensor_1
    global prev_sensor_2
    global prev_sensor_3
    global t0
    global t1
    global t2
    global t3
    global t4
    sensor_1 = 0
    sensor_2 = 0
    sensor_3 = 0
    prev_sensor_1 = 0
    prev_sensor_2 = 0
    prev_sensor_3 = 0
    t0 = 0
    t1 = 0
    t2 = 0
    t3 = 0
    GPIO.setup(pin_L1, GPIO.OUT)
    GPIO.setup(pin_L2, GPIO.OUT)
    GPIO.setup(pin_hole, GPIO.OUT)
    GPIO.output(pin_L1, GPIO.LOW)
    GPIO.output(pin_L2, GPIO.LOW)
    GPIO.output(pin_hole, GPIO.LOW)
    time.sleep(0.1)
    GPIO.setup(pin_L1, GPIO.IN)
    GPIO.setup(pin_L2, GPIO.IN)

def read_sensors():
    global sensor_1
    global sensor_2
    global sensor_3
    global pin_L1
    global pin_L2
    global pin_hole
    global t0
    global t1
    global t2
    global t3
    global t4
    #print("Reading sensors...") # Debug
    if t0 == 0:
        sensor_1 = GPIO.input(pin_L1)
    elif t1 == 0:
        sensor_1 = GPIO.input(pin_L1)
    elif t2 == 0:
        sensor_1 = GPIO.input(pin_L1)
    #elif t3 == 0:
        #sensor_2 = GPIO.input(pin_L2)
    else:
        sensor_3 = GPIO.input(pin_hole)


def reset_sensors():
    print("Resetting sensors...")
    global sensor_1
    global sensor_2
    global sensor_3
    global prev_sensor_1
    global prev_sensor_2
    global prev_sensor_3
    global t0
    global t1
    global t2
    global t3
    global t4
    sensor_1 = 0
    sensor_2 = 0
    sensor_3 = 0
    prev_sensor_1 = 0
    prev_sensor_2 = 0
    prev_sensor_3 = 0
    t0 = 0
    t1 = 0
    t2 = 0
    t3 = 0
    t4 = 0
    # WIP. Need to find way to read sensors from GPIO Raspberry Pi too

def task():
    global sensor_1
    global sensor_2
    global sensor_3
    global prev_sensor_1
    global prev_sensor_2
    global prev_sensor_3
    global t0
    global t1
    global t2
    global t3
    global t4
    global points
    read_sensors()
    if t0 == 0: # ball not placed
        # show_message('Place the golf ball so it blocks sensor 1.')
        if prev_sensor_1 != sensor_1:
            prev_sensor_1 = sensor_1
            if sensor_1 == 1:
                t0 = int(time.time()*1000)
                show_message('Ball detected. Please wait 3 seconds.')
    elif t1 == 0: # L1 and prev L1 not 1 for 3 secs
        current_time = int(time.time()*1000)
        time_dif = current_time - t0
        if time_dif >= 3000 and sensor_1 == 1 and prev_sensor_1 == 1: # Check if player meant to do so, not on accident
            #show_message('Ball detected.\nYou have 10 seconds to putt!')
            t1 = int(time.time()*1000)
        elif sensor_1 != 1:
            reset_sensors()
            show_message('System error. Place the ball at the start.')
    elif t2 == 0: # ball not hit
        print("t2 is 0")
        if prev_sensor_1 != sensor_1:
            prev_sensor_1 = sensor_1
            if sensor_1 == 0:
                t2 = int(time.time()*1000)
                show_message('Ball hit!')
        else:
            print("t2 is 0, show msg")
            current_time = int(time.time()*1000)
            secs_left = "Ball detected. You have " + str(int(((t1+10000) - current_time)/1000)) + " seconds left"
            show_message(secs_left)
            time_dif = current_time - t1
            if time_dif > 10000:
                show_message('Time Expired. Place the ball at the start.')
                t1 = 0
                reset_sensors()
    else:
        if t3 == 0: # L2 not detected ball
            if prev_sensor_2 != sensor_2:
                    prev_sensor_2 = sensor_2
                    if sensor_2 == 1:
                        t3 = int(time.time()*1000)
                        show_message('Sensor 2 has detected ball.')
                        speed = 12000 / (t3 - t2)
                        show_speed(round(speed, 2))
        else:
            #current_time = int(time.time()*1000)
            #time_dif = current_time - t2
            time_dif = t3 - t2
            if time_dif > 3000:
                show_message('Sensor 2 failed to detect ball. Try again.\nPlace the ball at the start.')
                reset_sensors()
            else:
                show_message('Sensor 2 has detected ball.')
        if t4 == 0:
            if prev_sensor_3 != sensor_3:
                prev_sensor_3 = sensor_3
                if sensor_3 == 1:
                    t4 = int(time.time()*1000)
                    show_message('Congratulations! You have won\n1000 points! Place the ball at the start.')
                    points += 1000
                    show_points(points)
                    reset_sensors()
        else:
            current_time = int(time.time()*1000)
            time_dif = current_time - t3
            if time_dif > 5000:
                show_message('Miss. Try again.')
                reset_sensors()


    root.after(10, task)

def reset_sim():
    global points
    points = 0

def show_message(label):
    global message
    message['text'] = label

def show_speed(label):
    global speed_message
    speed_message['text'] = label

def show_points(label):
    global pts
    pts['text'] = label

# Main Code

init_sensors()
reset_sensors()
reset_sim()

intro = root.create_text(375, 250, anchor=CENTER, font=('Calibri', 48), text='  Welcome to the \n     Putt Tracker', fill='black')

#window.after(10, bob) Uncomment for moving title

message = Label(root, anchor=CENTER, font=('Calibri', 20), bg='limegreen', fg='black')
message.place(x=50, y=400)

speed_message = Label(root, anchor=CENTER, font=('Calibri', 24), text='N/A', bg='limegreen', fg='black')
speed_message.place(x=430, y=50)

unit_start = Label(root, anchor=CENTER, font=('Calibri', 24), text='Your ball speed was', bg='limegreen', fg='black')
unit_start.place(x=100, y=50)

unit = Label(root, anchor=CENTER, font=('Calibri', 24), text='in/s', bg='limegreen', fg='black')
unit.place(x=550, y=50)

pts = Label(root, anchor=CENTER, font=('Calibri', 24), text='0', bg='limegreen', fg='black')
pts.place(x=200, y=550)

#window.after(100, rainbow_pts) Uncomment for colored points

show_message('Place the golf ball so it blocks sensor 1.')

pts_value_end = Label(root, anchor=CENTER, font=('Calibri', 24), text='points', bg='limegreen', fg='black')
pts_value_end.place(x=350, y=550)

exploit = root.create_text(700, 675, anchor=S, font=('Calibri', 4), text='Press \'a\' for bonus points.', fill='black')

root.after(1, task)

try:
#   GPIO.add_event_detect(pin_L2, GPIO.BOTH, callback=my_callback)
    GPIO.add_event_detect(pin_L2, GPIO.RISING, callback=my_callback)
    root.pack()
    root.mainloop()
except KeyboardInterrupt:
    pass
finally:
    GPIO.cleanup()

Извините за длинный код. Я надеялся, что датчик обнаружит мяч, но это не произошло, что привело к ошибке обнаружения. Как мне это исправить?

...