【问题标题】:How do I get python IDLE/ GUI communicating with mbed board?如何让 python IDLE/GUI 与 mbed 板通信?
【发布时间】:2019-08-12 13:52:25
【问题描述】:

我需要一个 python GUI 与 mbed (LPC1768) 板通信。我可以将字符串从 mbed 板发送到 python 的 IDLE,但是当我尝试将值发送回 mbed 板时,它无法按预期工作。

我编写了一个非常基本的程序,我从 mbed 板上读取了一个字符串并将其打印在 Python 的 IDLE 上。然后程序应要求用户输入一个值,该值应发送到 mbed 板。

此值应设置 LED 闪烁之间的时间。

python 代码

import serial

ser = serial.Serial('COM8', 9600)

try:
    ser.open()
except:
    print("Port already open")

out= ser.readline()                    

#while(1):

print(out)


time=input("Enter a time: " )
print (time)

ser.write(time.encode())


ser.close()

和 mbed c++ 代码

#include "mbed.h"

//DigitalOut myled(LED1);
DigitalOut one(LED1);
DigitalOut two(LED2);
DigitalOut three(LED3);
DigitalOut four(LED4);

Serial pc(USBTX, USBRX);

float c = 0.2;


int main() {
    while(1) {

        pc.printf("Hello World!\n");
        one = 1;
        wait(c);
        two=1;
        one = 0;
        wait(c);
        two=0;
        c = float(pc.getc());
        three=1;
        wait(c);
        three=0;
        four=1;
        wait(c);
        four=0;     
    }
}

程序等待在IDLE中输入值并发送到mbed板并开始使用发送给它的值但突然停止工作,我不知道为什么。

【问题讨论】:

    标签: python c++ mbed


    【解决方案1】:

    你需要走这条线:

    c = float(pc.getc());
    

    跳出你的循环。

    您的程序停止工作的原因是该线路一直在等待您再次发送。如果你只发送一次它会永远等待。

    【讨论】:

    • 如果我想从python代码/IDLE接收数据,请问我需要放什么?
    • 你不应该放任何东西,只需将该行移出循环,就在int main()下方
    【解决方案2】:

    如果您想在程序进入 while 循环后动态设置等待时间,我建议将回调函数附加到串行 RX 中断。

    RawSerial pc(USBTX, USBRX);
    
    void callback() {
        c = float(pc.getc());
    }
    

    Serial 使用互斥体,不能在 mbed OS5 上的 ISR 中使用。请改用RawSerial

    int main() {
    
        pc.attach(&callback, Serial::RxIrq);
    
        while(1) {
            // your code for LED flashing
            // no need to call pc.getc() in here
            one = 1;
            wait(c);
            one = 0;
            wait(c);
        }
    }
    

    这样,LED 会继续闪烁,您可以在 mbed 收到值时更新c

    此外,您似乎正在发送 ASCII 字符。 ASCII 1 是十进制的 49。因此,当您发送 '1' 时,pc.get() 返回 49。我不认为那是你想要的。如果您总是发送一个数字 (1~9),一个简单的解决方法是 pc.getc() - 48。但你最好将string 解析为int 并在python 端进行错误处理。

    【讨论】:

    • 我已经按照您的建议进行了操作,但仍然无法正常工作。该程序似乎没有到达callback 函数
    • 您可能正在发送 ascii 字符。例如,ASCII '1' 是十进制的 49。所以,等待时间是 49 秒。
    • 你是对的,我已经将值“1”发送到微控制器,当它到达时它是值 49。那么我如何发送值 1?我查了一个ASCII表,十进制值1是字符'SOH'。但如果我发送值“SOH”,微控制器只会收到十进制值“H”(即 72)。
    猜你喜欢
    • 1970-01-01
    • 2019-11-26
    • 2018-04-14
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多