avr与python串行通信时的奇怪b'\x'数据

2024-09-25 04:28:34 发布

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

我正在尝试在python和atmega128 avr c脚本之间发送和接收数据。我得到了奇怪的字节类型我不明白。你知道吗

我尝试用python代码读取数据,但结果看起来有点像b'\x00'b'\x06'b'\x9e'b'f'b'\x06'。我的代码有什么问题?你知道吗

这是我的atmega主线

unsigned char Message[]="Initialization Complete!"; 
unsigned char buff = 0;

MCU_init(); 
UART_init_with_INT();

uart_send_string(Message,25);
uart_send_byte('\n');
uart_send_byte('\r');

return 0;

这是我的python脚本读取数据

import serial

ser = serial.Serial('COM4', 115200)

while(True):
    print(ser.read())

#ser.write(b'hello test')
ser.close()

这是我真正奇怪的结果

b'\x86'
b'\x98'
b'\xf8'
b'\x9e'
b'\x86'
b'\x9e'
b'`'
b'f'
b'\x9e'
b'\x06'
b'\x06'
b'\x9e'
b'\x86'
b'\x9e'
b'\x98'
b'f'
b'\x06'
b'~'
b'\x86'
b'\x9e'
b'\xfe'
b'\x9e'
b'\xf8'
b'\x9e'
b'\x00'
b'\x98'
b'\x80'
b'\xe6'
b'\x9e'
b'\xe6'
b'\x9e'
b'\x00'
b'\x06'
b'\x9e'
b'f'
b'\x06'
b'~'
b'f'
b'f'
b'\x18'
b'\x06'
b'\xe6'
b'\x80'

然而,我期望的结果是 "Initialization Complete!"

另外,这是UART实现

void uart_send_byte(unsigned char byte)
{
        while(!(UCSR1A&(1<<UDRE1)));
        UDR1 = byte;
}

void uart_send_string(unsigned char *str, unsigned char len)
{
        int i;
        for(i=0;i<len;i++) {
                if(!(*(str+i)))
                        break;
                uart_send_byte(*(str+i));
        }
}

Tags: 代码脚本sendbytex86serx00uart
2条回答

python读取的是字节:https://docs.python.org/3/library/stdtypes.html

如果要将字节转换为ascii,可以使用以下函数:

ser.read().decode("ascii")

根据编码,参数可能会改变(例如,可能是utf-8)

谢谢大家,我解决了。你知道吗

我修改了python代码,如下所示!我必须设置端口。你知道吗

import serial

ser = serial.Serial(
    port='/COM4',
    baudrate=57600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

while(True):
    print(ser.readline())

ser.close()

相关问题 更多 >