Search code examples
c#avr-gcc

AVR char and C# byte differ


I wrote a tiny C# application that writes bytes to a COM port:

SerialPort serialPort = new SerialPort
{
    PortName = "COM6",
    BaudRate = 57600,
    DataBits = 8,
    Parity = Parity.None,
    StopBits = StopBits.One,
    Handshake = Handshake.None
};

serialPort.DataReceived += delegate
{
    var read = serialPort.ReadByte();
    Console.WriteLine("Recv: {0}", read);
    Trace.WriteLine(read);
};

serialPort.Open();

for (Byte i = 0; i < 250; i++)
{
    Console.WriteLine("Send: {0}", i);
    serialPort.Write(new[] {i}, 0, 1);
    Thread.Sleep(250);
}

Now I receive these signals with my ATMega328P and send back what I received:

void InitUart()
{
    // Enable receiver and transmitter
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);

    // Set baud rate
    UBRR0H = (UART_BAUD_PRESCALE  >> 8);
    UBRR0L = UART_BAUD_PRESCALE;

    // Set frame: 8data, 1 stop bit
    UCSR0C |= (1 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01);

    // Enable all interrupts
    sei();
}

void UART_Send(char b)
{
    UDR0 = b;
    while ((UCSR0A & (1 << TXC0)) == 0) {};
}

ISR(USART_RX_vect)
{
    char b = UDR0;
    _delay_ms(125);
    UART_Send(b);
} 

But what happens is this:

Send: 0
Recv: 128
Send: 1
Recv: 129
Send: 2
Recv: 130
Send: 3
Recv: 131
Send: 4
Recv: 132
Send: 5
Recv: 133
Send: 6
Recv: 134
Send: 7
Recv: 135
Send: 8
Recv: 136
Send: 9
Recv: 137
Send: 10
Recv: 138
Send: 11
Recv: 139
Send: 12
Recv: 140
Send: 13
Recv: 141
Send: 14
...
Recv: 250
Send: 123
Recv: 251
Send: 124
Recv: 252
Send: 125
Recv: 253
Send: 126
Send: 127
Send: 128
Recv: 128
Send: 129
Recv: 129
Send: 130
Recv: 130
Send: 131
Recv: 131
Send: 132
Recv: 132
Send: 133
Recv: 133
Send: 134
Recv: 134
Send: 135
Recv: 135
Send: 136
Recv: 136
Send: 137
Recv: 137
Send: 138
Recv: 138
Send: 139
Recv: 139
Send: 140
Recv: 140

So it goes up to 127 then it is suddenly correct.

Somehow there is a 128 difference in the byte values, but I cannot get my hand on it.

Edit: after some more testing I noticed this:

Send: 0 (0)
Recv: 128 (10000000)
Send: 1 (1)
Recv: 129 (10000001)
Send: 2 (10)
Recv: 130 (10000010)
Send: 3 (11)
Recv: 131 (10000011)
Send: 4 (100)
Recv: 132 (10000100)
Send: 5 (101)
Recv: 133 (10000101)

I appears that the complements are different from C# and AVR C.


Solution

  • The solution was that I was using the wrong speed for the serial port thus the packets would not arrive properly.