将两个程序组合成一个while循环



所以我尝试将这两个单独的程序结合起来。一个用于测量温度,另一个用于扫描二维码。当我尝试这个脚本时,只有第一个程序正在执行。你能帮我找到我缺少的东西或我放置的任何错误的缩进或代码吗?这两个程序分开后运行得很好。注意:在分隔的脚本中有一个"while True:";在第二程序中的if传感器==0之前

import board
import busio as io
import adafruit_mlx90614
import RPi.GPIO as GPIO
from time import sleep
import cv2
import re
import csv
from datetime import date
from datetime import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(15, GPIO.IN)
while True:
sensor = GPIO.input(15)
if sensor == 1:
print("Scanning...")
sleep(0.1)
elif sensor == 0:
print("User Detected")
i2c = io.I2C(board.SCL, board.SDA, frequency=100000)
mlx = adafruit_mlx90614.MLX90614(i2c)
temp = "{:.2f}".format(mlx.object_temperature)
sleep(0.1)
print("Temperature:", str(temp) + "°C")

if temp >= str(37.5):
print("High Temperature")
else:
print("Normal Temperature")
break

cap = cv2.VideoCapture(0) # for second program
detector = cv2.QRCodeDetector() # scanning QR code
print("Reading QR code using Raspberry Pi camera")
print("Please place QR code.")
print()
if sensor == 0: # second program starts here                  
_, img = cap.read()
data, bbox, _ = detector.detectAndDecode(img)

if bbox is not None:
for i in range(len(bbox)):
cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,
0, 0), thickness=2)

cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 255, 0), 2)
if data:
sw1Press = False

data = data.split(",")
today = date.today()
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Name: " + data[0])
print("Age: " + data[1])
print("Address: " + data[2])
print("ContactNo: " + data[3])
print("Date: " + str(today))          
print("Time: " + current_time)
print()

userScanned = False
if userScanned == False:
with open('List2.csv', 'a') as csvfile:
fieldNames = ['Name', 'Temp', 'Age', 'Address', 'ContactNo', 'Date', 'Time']
writer = csv.DictWriter(csvfile, fieldnames=fieldNames)
writer.writerow({'Name': data[0], 'Temp': temp, 'Age': data[1], 'Address': data[2],
'ContactNo': data[3], 'Date': date, 'Time': current_time})
print("Done")

else:
cap.read()
cv2.destroyAllWindows()
led.off()
cap.release()
cv2.destroyAllWindows()

您的问题是由代码中的break语句引起的。如果sensor==0为true,则包含此break语句的块将运行,该块中的break将始终被命中,此时while True:循环将退出,并且break以下的任何代码将永远不会运行。第二个程序的代码在break下面。因此,当sensor==0为true时,它不会运行。但根据保护它的if语句,它只有在sensor == 0为true时才会运行。所以第二个程序永远不会运行。

不仅第二个程序的代码永远不会运行,而且第一个程序中break以下的代码也永远不会运行。你可能是说CCD_ 12语句缩进,所以它只在";"常温";案例由于这两个程序似乎是独立的,我猜您根本不想要break语句。

解决这个问题最明显的方法是删除中断,并可能使第一个程序中剩余代码的执行取决于某些条件。我认为这个条件是必要的,因为我能看到的将break放在首位的唯一原因是跳过这个代码的执行。这样的东西:

if sensor == 0:
print("User Detected")
...
if temp >= str(37.5):
print("High Temperature")
else:
print("Normal Temperature")
# break               <- @@@ break statement removed @@@
if (????):  #         <- @@@ if remainder of this code should not always be run, conditionally run it or not.
cap = cv2.VideoCapture(0)  # for second program
detector = cv2.QRCodeDetector()  # scanning QR code

print("Reading QR code using Raspberry Pi camera")
print("Please place QR code.")
print()

cap = cv2.VideoCapture(0)  # for second program
detector = cv2.QRCodeDetector()  # scanning QR code

print("Reading QR code using Raspberry Pi camera")
print("Please place QR code.")
print()
if sensor == 0:  # second program starts here
_, img = cap.read()
data, bbox, _ = detector.detectAndDecode(img)

在这个版本的代码中,每次都会通过主循环到达第二个程序的开始。

一个更好的计划是将这两个程序中的每一个的代码放在自己的函数中,然后在外部逻辑中调用这两个函数。如果这样做,可以使用return而不是break来跳过第一个程序中的所有剩余代码。如果运行第二个函数/程序,这将不会产生任何影响。

假设两个程序都独立运行,请尝试此

import board
import busio as io
import adafruit_mlx90614
import RPi.GPIO as GPIO
from time import sleep
import cv2
import re
import csv
from datetime import date
from datetime import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setup(15, GPIO.IN)
def get_temperature():
print("User Detected")
i2c = io.I2C(board.SCL, board.SDA, frequency=100000)
mlx = adafruit_mlx90614.MLX90614(i2c)
temp = "{:.2f}".format(mlx.object_temperature)
sleep(0.1)
print("Temperature:", str(temp) + "°C")
if temp >= str(37.5):
print("High Temperature")
break
else:
print("Normal Temperature")
break
def scan_qr():
cap = cv2.VideoCapture(0) # for second program
detector = cv2.QRCodeDetector() # scanning QR code
print("Reading QR code using Raspberry Pi camera")
print("Please place QR code.n")
_, img = cap.read()
data, bbox, _ = detector.detectAndDecode(img)
if bbox is not None:
for i in range(len(bbox)):
cv2.line(img, tuple(bbox[i][0]), tuple(bbox[(i+1) % len(bbox)][0]), color=(255,0, 0), thickness=2)
cv2.putText(img, data, (int(bbox[0][0][0]), int(bbox[0][0][1]) - 10), cv2.FONT_HERSHEY_SIMPLEX,0.5, (0, 255, 0), 2)
if data:
sw1Press = False
data = data.split(",")
today = date.today()
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Name: " + data[0])
print("Age: " + data[1])
print("Address: " + data[2])
print("ContactNo: " + data[3])
print("Date: " + str(today))
print("Time: " + current_time + "n")
userScanned = False
if userScanned == False:
with open('List2.csv', 'a') as csvfile:
fieldNames = ['Name', 'Temp', 'Age', 'Address', 'ContactNo', 'Date', 'Time']
writer = csv.DictWriter(csvfile, fieldnames=fieldNames)
writer.writerow({'Name': data[0], 'Temp': temp, 'Age': data[1], 'Address': data[2],'ContactNo': data[3], 'Date':date, 'Time': current_time})
print("Done")
else:
cap.read()
cv2.destroyAllWindows()
while True:
sensor = GPIO.input(15)
if sensor == 1:
print("Scanning...")
sleep(0.1)
elif sensor == 0:
if (# condition that indicates we want temperature
):
get_temperature()
elif(# condition that indicates we want to scan a qr code
):
scan_qr()
break
led.off()
cap.release()
cv2.destroyAllWindows()

触发执行哪个功能的条件最有可能是硬件特定/依赖

最新更新