Search code examples
cavrarduino-uno

How to change endian-ness of data being transmitted serially?


I am trying to send a data serially and since I extract the first digit first i.e. LSB and it is the first char being transmitted, the data becomes totally inverted. Thus first I am inverting the data inside the avr and then transmitting it serially, but when I do that I get whole lot of garbage values. I cannot understand how I can transmit the data in a way that my MSB reaches first and then the LSB. I have written a simpler code for you all guys to look at. Please tell me where I am going wrong.

#include <avr/io.h>
#define F_CPU 16000000UL
volatile int val=0,temp=0,y=0,rev=0,y1;
char c;

void byte_init (int baud)
{
    UBRR0H = (baud>>8);                      // shift the register right by 8 bits
    UBRR0L = baud;                           // set baud rate
    UCSR0B|= (1<<TXEN0)|(1<<RXEN0);                // enable receiver and transmitter
    UCSR0C|= (1<<UCSZ00)|(1<<UCSZ01);   // 8bit data format
}

void byte_transmit (unsigned char data)
{
    while (!( UCSR0A & (1<<UDRE0)));                // wait while register is free
    UDR0 = data;                                   // load data in the register
}

unsigned char byte_receive (void)
{
    while(!(UCSR0A) & (1<<RXC0));                   // wait while data is being received
    return UDR0;                                   // return 8-bit data
}

void setup() {
    // put your setup code here, to run once:
    byte_init(103);
    pinMode(13,OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    digitalWrite(13,HIGH);
    digitalWrite(13,LOW);
    //it can send integer directly
    temp=val;
    while(temp>0)
    {
        y1=temp%10;
        rev=rev*10+val;
        temp=temp/10;
    }
    while(rev>0)
    {
        y=rev%10;
        c=y+'0';
        byte_transmit(c);
        rev=rev/10;
    }
    byte_transmit('A');
    val++;
    delay(1000);
}

Solution

  • To separate the int (16 bits on Arduino) into MSB and LSB, you need something like this:

    int value; // Arduino int is 16 bits
    unsigned char MSB = (value >> 8);  
    unsigned char LSB = (value & 0xFF);
    

    Now that you have two 8-bit values you can send them in the order you need to.