Skip to main content
 首页 » 编程设计

python之Li-Fi通信中的编码/解码问题

2025年02月15日7qq78292959

我正在做一个关于 LIFI 的项目,我们想通过 USB 端口(windows 操作系统)发送文本消息到灯闪烁(0s n 1s)n 接收器将其反馈到 PC USB 端口(linux 操作系统)来测试通信.编码是用 python3 语言完成的,它适用于单字符字母表和多字符数字,但我收到的某些字符没有收到相同的数字或字母表。它可能与编码 n 解码有关。

传输

import serial 
ser=serial.Serial() 
ser.port="/dev/ttyUSB0" 
ser.baudrate=9600 
ser.open() 
while 1: 
    print("what to send--") 
    ab=input() 
    if ser.isOpen(): 
        a=ser.write(ab.encode())   #Can also use (b'str')- converts to bytes 
        print("Sent") 
        print(a) 
    else: 
        print("Couldnt Open")     
 
ser.close()  

接收者

import serial 
ser=serial.Serial("/dev/ttyUSB2", 9600) 
if ser.isOpen(): 
     print(ser.name + " is open  \n Receiving= ") 
     while True: 
          out= ser.read() 
          print(out.decode()) 
else: 
    print("Couldnt open") 
 
ser.close() 

我在无限循环中逐字阅读。我正确地收到了一些字符,例如 x、z、o.p,但是对于“b”,我得到了“s”,对于“c”,我得到了“r”。对于数字 2、3、6、7 是正确的,但 1、、4、5、8、9、0 是 !、6、7、>、!、>。 对于一行字母,我得到 UnicodeDecodeError: 'utf8' codec can't decode byte 0x9c.

请您参考如下方法:

我在更改为手册中给出的 Baudrate=38400 后开始工作,但理论上它应该适用于所有波特率。