【问题标题】:Motion detection system运动检测系统
【发布时间】:2021-06-15 07:15:55
【问题描述】:

下面的代码是这样工作的,当红外传感器前面有东西并且按下按钮时,led灯一直亮着,蜂鸣器会一直嗡嗡作响,直到再次按下按钮将其关闭led 和蜂鸣器。

我尝试过的几次尝试是在 state==1 之前放置 ifinfrared_pin.read==0,但该代码使我必须按住按钮,红外传感器感应到某些东西来点亮 LED 并蜂鸣器会发出嗡嗡声。我还尝试使 input_2=infrared_pin.read()==0 并替换infrared_pin_state==True,第2行代码没有infrared_pin_state=False,第5行和第5行,如果infrared_pin.read ()==0 和infrared_pin_state=True。这也使得我需要按住按钮,红外传感器需要感应到某些东西,LED 和蜂鸣器才能亮起并发出嗡嗡声。

所以我希望下面的代码像我按下按钮一样工作,当有红外传感器时,它会打开 LED 和蜂鸣器,直到我再次按下按钮,它会关闭蜂鸣器和 LED。我认为有代码来查看按钮是否被按下,然后前面的红外传感器会点亮 LED。我需要编辑哪一部分才能做到这一点?请帮帮我,我在这方面卡了这么久,没有取得任何进展。

state=0
infrared_pin_state=False

while True:
  input=push_button.read()==1
  if infrared_pin.read()==0:
    infrared_pin_state=True
  if input == False:#have to press button to work
    if state ==1 and infrared_pin_state== True:# this is so the led will start in off
      led_pin.write(1)
      buzz_pin.write(1)
      print("Button pressed")
      state=0
      infrared_pin_state=False
  elif state ==0:
      led_pin.write(0)
      buzz_pin.write(0)
      print("Button depressed")
      state=1
time.sleep(0.5)

【问题讨论】:

  • 试着把你有什么和你想要什么用流程图列出来,看看有什么不同。这不是代码编写或辅导服务。我们可以帮助解决具体的技术问题,而不是对代码或建议的开放式请求。请编辑您的问题以显示您迄今为止尝试过的内容,以及您需要帮助的具体问题。请参阅How To Ask a Good Question 页面,详细了解如何最好地帮助我们。
  • 我编辑了,自己试了下,还是搞不明白,谁能帮帮我,急需。

标签: python-3.x arduino arduino-uno


【解决方案1】:

由于我没有您用于此应用程序的硬件,因此我无法为您提供经过彻底测试的确切代码,因此我将定义一个通用的解决方案并为您提供一个基本的编码框架应该能够跟随:

问题说明 按下按钮后,只要红外线检测到障碍物,LED 就会闪烁并且蜂鸣器会响起。蜂鸣器继续响起,LED 继续闪烁,直到再次按下按钮 &。这可以映射到如下逻辑表:
让:
L = LED & L = 1 表示闪烁
Z = 蜂鸣器 & Z = 1 表示发声
I = 红外线 & I = 1 表示障碍物
B = Button & B = 1 表示按下按钮状态

然后:

B| I| | L| Z|
0| 0| | 0| 0|
0| 1| | 0| 0|
1| 1| | 1| 1|
0| 1| | 0| 0|

上面的逻辑表显示了问题描述中包含的几个问题:

  • 如果障碍物消失但未再次按下按钮,Led 和蜂鸣器会发生什么情况?
  • 如果在检测到障碍物之前按下按钮会发生什么?

出于本设计的目的,做出以下假设:

  • 如果障碍物消失,Led 和蜂鸣器将停止。
  • 如果在检测到障碍物之前按下按钮,蜂鸣器和 LED 会响起。

这是我推荐的代码:

button_state = False  #Assumes Button starts unpressed
obstruction_state = False  #Assumes no Obstruction detected
while True:
    if push_button.read()==1:  #Pressed Button = 1
        button_state = !button_state  # flip the condition of button_state
        print('Button Pressed')
    if infrared_pin.read()==0:  #Obstruction Detected:
        obstruction_state = True
    else:
        obstruction_state = False
    if button_state and obstruction_state:
        led_pin.write(1)
        buzz_pin.write(1)
    else:
        led_pin.write(0)
        buzz_pin.write(0)
    time.sleep(0.5)  

由于我无法使用您的硬件进行测试,您可能需要进行一些调整。希望我的 cmets 能让您根据需要进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多