我正在尝试连续发送数据,因为我首先提取第一个数字,即LSB,并且它是第一个被传输的字符,所以数据完全反转。因此,首先我将avr中的数据反转,然后串行传输,但是当我这样做时,我得到了大量的垃圾值。我无法理解如何以我的MSB首先到达LSB的方式传输数据。我为你们所有人编写了一个更简单的代码。请告诉我哪里出错了。
#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);
}
答案 0 :(得分:1)
要将int(Arduino上的16位)分成MSB和LSB,你需要这样的东西:
int value; // Arduino int is 16 bits
unsigned char MSB = (value >> 8);
unsigned char LSB = (value & 0xFF);
现在你有两个8位值,你可以按照你需要的顺序发送它们。