0

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);
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Saad Anwar
  • 41
  • 7
  • Are you saying your bits on individual bytes need to be reversed? Like `0b00110001` becoming `0b10001100`? Or are you saying you want the two bytes of an integer (16-bits on Arduino) to be transmitted most-significant byte first? – TomServo Jun 21 '17 at 20:59
  • @JLH the MSB byte to be transmitted first. – Saad Anwar Jun 22 '17 at 02:33
  • Understood. My answer allows you to separate the bytes of an int (16-bit on Arduino) and send them in the order you prefer. – TomServo Jun 23 '17 at 16:08

1 Answers1

1

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.

TomServo
  • 7,248
  • 5
  • 30
  • 47
  • Note that according to the C Standard, if `value` is negative, `value >> 8` has undefined behavior. You can work around this problem with `unsigned char MSB = ((unsigned)value >> 8);` – chqrlie Jun 25 '17 at 10:57