2

I'm trying to send and receive data between python and atmega128 avr c script. I am getting weird type of byte I don't understand.

I've tried to read data in python code but the results look kind of like b'\x00' b'\x06' b'\x9e' b'f' b'\x06'. What is wrong in my code?

Here is my main thread of 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;

This is my python script reading data

import serial

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

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

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

This is my actual weird result

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'

However what I expect the output to be is "Initialization Complete!"

P.S. This is UART implementation

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));
        }
}
FLYnn
  • 117
  • 9

2 Answers2

0

What python is reading are bytes: https://docs.python.org/3/library/stdtypes.html

If you want to convert bytes to ascii you can do it with the following function:

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

Depending on the encoding, the argument might change (e.g. could be utf-8)

Felipe Sulser
  • 1,185
  • 8
  • 19
  • This gives me error UnicodeDecodeError: 'ascii' codec can't decode byte 0x86 in position 0: ordinal not in range(128) – FLYnn Jun 21 '19 at 14:04
  • @MadPhysicist: In Python 3.x if you attempt to `print()` a `bytes` object, you'll get its `repr` instead, which will be a `b`-prefixed bytestring literal (using `\x` escapes). That looks like exactly what the OP is getting. – Daniel Pryden Jun 21 '19 at 14:34
  • 1
    @Daniel. That is not quite true. Every character that is ASCII printable will be displayed as a character rather than a hex code. You can see this with `\``, `f`, and `~` in the original output. The fact that the bytes aren't being printed as characters pretty much means they aren't ASCII – Mad Physicist Jun 21 '19 at 14:59
0

Thanks everyone, I solved.

I changed my python code as below and done! I had to setup port.

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()
FLYnn
  • 117
  • 9