简体   繁体   English

如何在树莓派中处理串行读取值

[英]How to process a serial read value in Raspberry pi

I have been trying to have some serial communication between raspberry and my STM32 board (I use MBEDOS for the firmware).我一直在尝试在树莓派和我的 STM32 板之间进行一些串行通信(我使用 MBEDOS 作为固件)。

Right now, I am able to do serial writing from my raspberry to the microcontroller, and succeed.现在,我能够从我的树莓派到微控制器进行串行写入,并且成功了。

However, I wanted to try to write something from the microcontroller to the raspberry, and the raspberry should process it.但是,我想尝试从微控制器向树莓派写一些东西,树莓派应该处理它。 But, it seems that it fails to do so.但是,它似乎没有这样做。

The code of the raspberry is quite simple:树莓派的代码很简单:

import time
import serial
ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate = 9600,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=1
    )
while 1:
     x=ser.readline()
     if x[2] == "e":
         break         
     print x
print("stop")

A little explanation to my code, what I wanted to do is when my microcontroller send an "e", it should break from the loop.对我的代码做一点解释,我想做的是当我的微控制器发送一个“e”时,它应该从循环中中断。 I used x[2] because I noticed when we print the serial data, it will print:我使用 x[2] 因为我注意到当我们打印串行数据时,它会打印:

b'eeeeeee\n'

hence,I decided to use x[2].因此,我决定使用 x[2]。

In the microcontroller part, I used:在微控制器部分,我使用了:

if(butn == 1) {
        // raspi.putc('e');
        raspi.printf("eeeeeee");
        swo.printf("e is printed");
    }

where butn is the user button.其中 butn 是用户按钮。 I already tried using.putc('e') but it is the same as well.我已经尝试过 using.putc('e') 但它也是一样的。

How can I deal with this problem?我该如何处理这个问题?

Thank you!!谢谢!!

The problem in your code is that Serial.readline() return a bytes object, not a string. 您的代码中的问题是Serial.readline()返回的是bytes对象,而不是字符串。 That's why you see the b when it gets printed. 这就是为什么在打印b时看到b的原因。

Now, indexing with bytes objects doesn't count the b and the ' that appear in its string representation; 现在,使用字节对象建立索引不会计算其字符串表示形式中出现的b和'; so if you want the first character, you should use x[0] . 因此,如果要使用第一个字符,则应使用x[0] However, when you use indexing in the bytes object you won't get a character, you will get the number representation of the particular byte you requested. 但是,当在bytes对象中使用索引时,您将不会获得字符,但将获得所请求的特定字节的数字表示形式。

x = b'eeeee'
print x[0]

>>> 101

Unsurpisingly, 101 is the ascii for 'e'. 毫不奇怪,101是'e'的ascii。

You need to cast x[0] to a character. 您需要将x [0]强制转换为字符。 The result would be: 结果将是:

while 1:
     x=ser.readline()
     if chr(x[0]) == "e":
         break         
     print x

Another option is to write the following:另一种选择是编写以下内容:

x = hex(int.from_bytes((ser.readline()), 'big'))
if x[2] == 'e':
    break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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