我在做Python和Arduino串口通讯。这是我的代码的一部分。
while True:
data = arduino.readline()
str = data[:-2].decode()
print(str) # to check the str
if str: # if str gets 1 from arduino
some logics here..............
但问题是当python代码运行while子句时,Arduino仍在向Python发送数据。我认为如果它继续发送到python,我不认为代码进展顺利。那么问题是如何在while子句启动时停止发送数据?提前谢谢。
整个代码就在这里!
python代码
import serial
import time
import MySQLdb
from datetime import datetime
import cv2
import boto3
now = datetime.today().strftime("%Y-%m-%d-%H-%M-%S")
station="hansung-"
type=".jpg"
filename=station+now+type
st=filename.split('-')[0]
ye=filename.split('-')[1]
mo=filename.split('-')[2]
da=filename.split('-')[3]
#the picture is just uploaded in to s3 bucket
port ="COM15" #I am testing this on my windows laptop
brate = 9600
arduino =serial.Serial(port, baudrate = brate, timeout=None)
while True:
#keep receive data from arduino
data= arduino.readline()
# delete \n\r from arduino
str = data[:-2].decode()
# if person exists str = 1 or str = 0
print(str)
if str:
#if picture is taken
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
cv2.imwrite(filename, frame)
cap.release()
print('picture is taken')
#upload in to s3
s3 = boto3.resource('s3')
bucketname = 'dongyeon2'
bucket = s3.Bucket(bucketname)
bucket.upload_file(filename, filename, ExtraArgs={'ACL': 'public- read'})
bucketurl = "https://s3-ap-northeast-1.amazonaws.com/dongyeon2/" + filename
db = MySQLdb.connect(host='localhost', user='root',passwd='', db='pythonprogramming')
cur = db.cursor()
#insert into sql
sql = "insert into image(station,year,month,day,img_url) values(%s,%s,%s,%s,%s)"
cur.execute(sql, (st, ye, mo, da, bucketurl))
db.commit()
db.close()
else:
print("no body")
这是Arduino代码
int IR_sensor = A0;
int value;
void setup()
{
Serial.begin(9600);
pinMode(IR_sensor, INPUT);
}
void loop() {
long IR_value = analogRead(IR_sensor);
long IR_range = gp2y0a21yk(IR_value);
if(IR_range < 50)
{
value=1;
Serial.println(value);
}
else {
value=0;
Serial.println(value);
}
delay(1000);
}
long gp2y0a21yk(long IR_value)
{
if (IR_value < 10)
{
IR_value = 10;
}
return ((67870.0 / (IR_value-3.0)) - 40.0)/10;
}
我想要做的是当人通过某个点然后将str改为1然后拍摄该人然后上传到s3并将其保存到sql。如果没有人只打印出没有身体。但是现在我面临的问题是它不起作用,我希望如此。它只出现了 0 没有人 0 没有身体
所以我认为这是因为Arduino保持向python发送数据而python读取str值并在前一个之前转到while子句。先生,你是先生吗?