你能创建一个Arduino按钮来让你在python程序中执行某些事情吗?



有没有办法创建一个Arduino按钮,让你在python程序中做某些事情。例如,您能否使其像pygame.K_LEFTpygame中一样工作,但不是在键盘上按下按钮,而是在Arduino上。

这里的问题是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 个字母(字节(的代码。 当它收到它识别的代码时,会执行一些操作,否则将忽略该代码。

你在这里没有详细介绍,但我假设你说的是让你的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键盘固件来查看有关此内容的各种页面。

最新更新