您可以创建一个Arduino按钮,让您在python程序中执行某些操作吗?

时间:2019-09-08 18:27:19

标签: python button input arduino pygame

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

2 个答案:

答案 0 :(得分: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键盘来查看与此相关的各个页面固件。

答案 1 :(得分:2)

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

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

为使代码简单,我将使用Arduino串行示例。

Arduino C语言代码:

conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute('create table results (result text, student_id int, lesson_id text, lesson_title text)')

with open(JSON_FILE) as f:
    for line in f:

        traffic=json.loads(line)

        a = traffic["result"]
        b = traffic["student_id"]
        lesson_id = traffic["lesson_id"]  # don't rename cursor variable 
        d = traffic["lesson_title"]

        c.execute('insert into results values (?,?,?,?)', data)

conn.commit()
c.close()

在PC / RPi端,在串行端口上侦听Arduino的指令:

#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
}

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