Điều khiển led và webcam bằng Raspberry Pi 3

Mình có viết 1 đoạn code python dùng 4 công tắc hành trình để điều khiển 4 led và 1 webcam trên Raspberry Pi 3. Mình muốn xuất ảnh từ webcam sau khi công tắc hành trình thứ 2 đóng. Nhưng khi chạy mình thấy ảnh chỉ hiện lên sau khi công tắc thứ 3 đóng và đó là ảnh từ lần trước. Cụ thể là ở vòng lặp thứ 1 trả về 1 khung trắng, vòng lặp thứ 2 trả về ảnh chụp ở vòng lặp thứ 1 và cứ vậy…
Đây là code của mình:

import RPi.GPIO as GPIO
import numpy as np
import cv2
from Tkinter import *
from PIL import Image
from PIL import ImageTk
from Tkinter import Label

#Khai bao chan va GPIO
ButtonPin1 = 11                       
ButtonPin2 = 12
ButtonPin3 = 15
ButtonPin4 = 16
LedPin1 = 21                          
LedPin2 = 22
LedPin3 = 23
LedPin4 = 24
GPIO.setmode(GPIO.BOARD)             
GPIO.setup(LedPin1, GPIO.OUT)         
GPIO.setup(LedPin2, GPIO.OUT)
GPIO.setup(LedPin3, GPIO.OUT)
GPIO.setup(LedPin4, GPIO.OUT)
GPIO.output(LedPin1, GPIO.LOW)
GPIO.output(LedPin2, GPIO.LOW)
GPIO.output(LedPin3, GPIO.LOW)
GPIO.output(LedPin4, GPIO.LOW)
GPIO.setup(ButtonPin1, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) 
GPIO.setup(ButtonPin2, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)        
GPIO.setup(ButtonPin3, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(ButtonPin4, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)

root = Tk()
root.title("Anh")

def start():
    GPIO.output(LedPin1, GPIO.HIGH)
    GPIO.wait_for_edge(ButtonPin1, GPIO.RISING)
    GPIO.output(LedPin1, GPIO.LOW)
    root.after(2000, start1)
def start1():
    GPIO.output(LedPin2, GPIO.HIGH)
    GPIO.wait_for_edge(ButtonPin2, GPIO.RISING)
    root.after(0, start2)
def start2():
    cap = cv2.VideoCapture(0)
    ret, img = cap.read()
    img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret2 , threshold = cv2.threshold(img1,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(img1,contours,0,(0,0,255),3)
    panel = None
    img1 = Image.fromarray(img1)
    img1 = ImageTk.PhotoImage(img1)
    panel = Label(root, image=img1)
    panel.image = img1
    panel.grid(row=0, column=0)
    root.after(0, start3)
def start3():
    GPIO.output(LedPin2, GPIO.LOW)  
    GPIO.output(LedPin3, GPIO.HIGH)
    GPIO.wait_for_edge(ButtonPin3, GPIO.RISING)
    GPIO.output(LedPin3, GPIO.LOW)
    root.after(2000, start4)
def start4():
    GPIO.output(LedPin4, GPIO.HIGH)
    GPIO.wait_for_edge(ButtonPin4, GPIO.RISING)
    GPIO.output(LedPin4, GPIO.LOW)  
    root.after(500, start)
root.after(500, start)
root.mainloop()

Bạn nào biết giúp mình với!

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?