如何让python空闲/GUI与mbed板通信?

2024-10-03 02:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个pythongui与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板,然后开始使用发送给它的值,但突然停止工作,我不知道为什么。你知道吗


Tags: 字符串代码程序timeoneserthreefour
2条回答

你需要走这条线:

c = float(pc.getc());

从你的圈子里出来。你知道吗

您的程序停止工作的原因是,在您再次发送某些内容之前,该行一直保持。如果你只发送一次,它将永远等待。你知道吗

如果要在程序进入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字符。ASCII1是十进制的49。因此,pc.get()在发送'1'时返回49。我不认为那是你想要的。如果您总是发送一个数字(1~9),一个简单的解决方法是pc.getc() - 48。但您最好将string解析为int,并在python端进行错误处理。你知道吗

相关问题 更多 >