在python中释放按钮时,输出发生了变化

2024-04-19 12:04:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个算法,信号将通过python发送到Firebase。流量是当我按下按钮时,它会被检测到,并在释放时计数为1次。你知道吗

我尝试的python代码是这样的

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)

我尝试的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);
  }
}

我也在连接python和arduino。arduino一直在向python发送信号0。当按下按钮1或按钮2时,它将发送1或2。你知道吗

所以,我正在尝试的代码是用户按下按钮1或按钮2给出的输出是1,结果将在用户立即释放按钮后发送。你知道吗

但现在我的代码只能在按下按钮1或按钮2时接收信号。当我一直按这个按钮时,它会一直发出信号,但我不想。我怎样才能写出一次松开按钮后发出的信号?你知道吗


Tags: 代码fbif信号asserialmsgresult