最近,我正在尝试编写一个代码,它的流程是在输出“ 1”立即变为“ 0”时将发送信号。
此外,此代码连接到一个简单的按钮开关,因此当我按下按钮时,整个功能将发送“ 1”。幸运的是,我成功了!
AS = serial.Serial('COM8',9600)
url = 'https://xxx.firebaseio.com/'
AoS = 40
FB = firebase.FirebaseApplication(url, None)
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
while (1==1):
if(AS.inWaiting()>0):
msg = AS.readline().strip().decode()
if (msg == '1') and (AoS>0):
AoS-=1
print ("The Signal now is " + str(AoS))
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
if (msg == '2') and (AoS<40):
AoS+=1
print ("The Signal now is " + str(AoS))
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
print(msg)
我要修改的是下一个流程。我正在努力使流程变得完美。正如我所想象的那样,如果用户持续按下按钮,则信号将继续发送,“座位数量”将持续减少或增加。
因此,我发现的解决方案是在用户或我释放按钮后将发送信号。甚至用户或我不小心按下按钮的时间过长,并且在发送一个信号以上时,也仅算作一次!
AS = serial.Serial('COM8',9600)
url = 'https://xxx.firebaseio.com/'
AoS = 40
FB = firebase.FirebaseApplication(url, None)
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
while (1==1):
if(AS.inWaiting()>0):
msg = AS.readline().strip().decode()
if (msg == '1'):
print ("Waiting for release")
print (msg)
if (AoS>0) and (msg == '0'):
AoS-=1
print ("The Signal now is " + str(AoS))
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
if (msg == '2'):
print ("Waiting for release")
print (msg)
if (AoS<40) and (msg == '0'):
AoS+=1
print ("The Signal now is " + str(AoS))
result = FB.patch('/ParkingSeat/',{'Amount of the seats': str(AoS) + '/40'})
print(msg)
但是,我想不出更好的算法来解决这个问题。该算法始终停留在“等待发布”部分。
这是我修改之前的流程
0 0 0 0 0 1 1 1 0 0 0
所以信号会发送3次
但是我想要的流程
0 0 0 0 0 1 1 1 0 0 0
然后,当检测到1之后为0时,信号将仅发送1次。
下面的代码是Arduino的代码。它可能不会影响输出,但是我认为这会使您更容易理解。
const int BUTTON1 = 6;
const int BUTTON2 = 7;
String i, j, x;
int ButtonState = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(BUTTON1, INPUT_PULLUP);
pinMode(BUTTON2, INPUT_PULLUP);
}
void loop() {
if (digitalRead(BUTTON1) == LOW) {
delay(500);
i = "1";
Serial.println(i);
}
else if (digitalRead(BUTTON2) == LOW) {
delay(500);
j = "2";
Serial.println(j);
}
else {
delay(500);
x = "0";
Serial.println(x);
}
}
我想做的所有事情都是针对在线停车系统。 Arduino板接收消息并将消息发送给python。 Python接收到消息并对其进行检测以将其发送到Firebase实时数据库。
最后,谢谢您的帮助!