简体   繁体   中英

How do I get python IDLE/ GUI communicating with mbed board?

I need to have a python GUI communicating with an mbed (LPC1768) board. I am able to send a string from the mbed board to python's IDLE but when I try to send a value back to the mbed board, it does not work as expected.

I have written a very basic program where I read a string from the mbed board and print it on Python's IDLE. The program should then ask for the user's to type a value which should be sent to the mbed board.

This value should set the time between LED's flashing.

The python code

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()

and the mbed c++ code

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

The program waits for the value to be entered in IDLE and sent to the mbed board and begins to use the value sent to it but suddenly stops working and I cannot figure out why.

You need to take this line:

c = float(pc.getc());

out of your loop.

The reason your program stops working is that line is holding until you send something again. If you only send once it waits forever.

If you want to dynamically set wait time after the program enters the while loop, I would suggest attaching a callback function to a serial RX interrupt.

RawSerial pc(USBTX, USBRX);

void callback() {
    c = float(pc.getc());
}

Serial uses mutex and cannot be used in ISR on mbed OS5. Use RawSerial instead.

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);
    }
}

This way, the LED continues to blink and you can update c whenever the mbed receives a value.

Also, it looks like you are sending ASCII characters. ASCII 1 is 49 in decimal. So, pc.get() returns 49 when you send '1' . I don't think that is what you want. If you are always sending a single digit (1~9), an easy fix is pc.getc() - 48 . But you better parse string to int and do error handling on python side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM