【问题标题】:Can you create a Arduino button that lets you executing certain things in your python program?你能创建一个 Arduino 按钮,让你在 python 程序中执行某些操作吗?
【发布时间】:2019-09-08 18:27:19
【问题描述】:

有没有一种方法可以创建一个 Arduino 按钮,让您在 Python 程序中执行某些操作。例如,你能不能让它像 pygame.K_LEFT 在 pygame 中一样工作,但不是在键盘上按下按钮,而是在 Arduino 上。

【问题讨论】:

    标签: python button input arduino pygame


    【解决方案1】:

    您在这里没有详细介绍,但我假设您正在谈论让您的 Python 程序在本地计算机上运行,​​Arduino 及其按钮通过以下方式连接到计算机USB。对于许多 Arduino 模型(根据https://www.arduino.cc/reference/en/language/functions/usb/keyboard/Leonardo、Esplora、Zero、Due 和 MKR 系列),您可以使用 Arduino 键盘库通过 USB 端口将击键发送到您的计算机,但我也使用 Arduino Uno 进行了此操作几年前通过上传不同的固件进行的一次安装——如果您有一个 Arduino Uno(或者可能是上面未提及的其他型号之一),您可以通过搜索 Arduino Uno USB 键盘固件来查看有关此的各种页面。

    【讨论】:

      【解决方案2】:

      这里的问题是 Arduino 和执行 Python 的 PC/RPi(我假设)之间的通信。

      两个系统之间需要有一些接口。实现这一点的一种简单方法是使用串行连接,但您也可以使用网络连接。

      所以为了保持代码简单,我将展示一个使用 Arduino 串行的示例。

      Arduino C-ish 代码:

      #define BUTTON1_PIN 5
      #define BUTTON2_PIN 6
      
      void setup() 
      {
          pinMode( BUTTON1_PIN, INPUT ); 
          pinMode( BUTTON2_PIN, INPUT ); 
      
          Serial.begin( 115200 );  // fast
          Serial.write( "RS" );    // restart!
      }
      
      void loop() 
      {
          // TODO: Handle de-douncing (or do it in hardware)
      
          if ( digitalRead( BUTTON1_PIN ) == HIGH )
          {
              Serial.write( "B1" );   // Send a button code out the serial
          }
          if ( digitalRead( BUTTON2_PIN ) == HIGH )
          {
              Serial.write( "B2" );  
          }
      
          // etc... for more buttons, whatever
      }
      

      在 PC/RPi 端,在串口上监听来自 Arduino 的指令:

      import serial
      
      # Change for your com port, e.g.: "COM8:", "/dev/ttyUSB0", etc.
      serial_port = serial.Serial( port='/dev/ttyUSB1', baudrate=115200 )  # defaults to N81
      
      while ( True ):
          command = serial_port.read( 2 )  # read 2 bytes from the Arduino
          if ( len( command ) == 2 ):
              if ( command == b'RS' ):
                  print( "Arduino was Reset" )
              elif ( command == b'B1' ):
                  print( 'received button 01' )
              elif ( command == b'B2' ):
                  print( 'received button 02' )
              elif ( command == b'qq' ):
                  # Arduino says to quit
                  print( 'received QUIT' )
                  break
      
      serial_port.close()
      

      这一切都很简单。每当在 Arduino 上按下一个按钮时,就会在串行线上写下一个代码。 Python 程序侦听串行线路,读取 2 个字母(字节)代码。当它接收到它识别的代码时,就完成了一些事情,否则代码将被忽略。

      【讨论】:

        猜你喜欢
        • 2023-03-08
        • 2015-09-29
        • 2019-09-08
        • 1970-01-01
        • 1970-01-01
        • 2023-03-24
        • 2015-11-28
        • 1970-01-01
        • 2020-01-11
        相关资源
        最近更新 更多