#include "iom48v.h" const unsigned char disp[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xa7,0xa1,0x86,0x8e,0xff,0x7f}; unsigned char ledbuf[]={0xff,0xff,0xff,0xff}; unsigned char k=0; unsigned int x=0; unsigned int v=0; unsigned int i=0; unsigned char a[]={0x0e,0x0d,0x0b,0x07}; void delay(unsigned int x){ while(x--);} void io_init(void){ DDRC=0x0f; PORTC=0x0f; DDRB=0xff; PORTB=0xff; DDRD=0x02;} void t1_init(void){ TCCR1A=0x00; TCCR1B=0x0a; TCNT1=0; OCR1A=625; //ctc模式 ICR1=0xffff;} void uart_init(void){ UCSR0A=0b01000000; //异步,1起始位,八数据位,无校验,一停止 UCSR0B=0b00001000; //发送使能 UCSR0C=0b00000110; UBRR0=12;//baud=4800 } void uart_send(unsigned char d){//数据发送 while(!(UCSR0A&(1<<UDRE0))); //等待数据寄存器为空 UDR0=d; } unsigned char uart_receive(void){//数据接收 while(!(UCSR0A&0x80)); return UDR0;} #pragma interrupt_handler Int_TCCR1A:12 void Int_TCCR1A(void){ k=(k+1)%4; PORTC=0x0f; PORTB=ledbuf[k]; PORTC=a[k];} void decode(unsigned int v){ ledbuf[0]=disp[v/1000];ledbuf[0]&=0x7f; v=v%1000; ledbuf[1]=disp[v/100]; v=v%100; ledbuf[2]=disp[v/10]; ledbuf[3]=disp[v%10];} void main(void){ uart_init(); io_init(); t1_init(); SREG|=0x80; TIMSK1=0x02; while(1){ if((PIND&0x04)==0x04){ uart_send('a');} i=uart_receive(); decode(i); } }为什么这代码无法实现数据发送,接收和数码管显示接受的数据
时间: 2024-03-26 10:34:52 浏览: 95
这段代码中存在多个问题:
1.缺少头文件,例如avr/io.h
2.在main函数中没有开启总中断,需要添加sei()函数
3.在uart_init函数中设置波特率错误,应该设置为UBRR0=25,以获得波特率为19200
4.在uart_receive函数中,应该将UCSR0A的第7位(即RXC0)与0x80进行比较,而不是直接与0x08进行比较
5.在decode函数中,应该将ledbuf[0]的最高位清零,以显示数字"0"
修改后的代码如下:
```
#include <avr/io.h>
const unsigned char disp[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xa7,0xa1,0x86,0x8e,0xff,0x7f};
unsigned char ledbuf[]={0xff,0xff,0xff,0xff};
unsigned char k=0;
unsigned int x=0;
unsigned int v=0;
unsigned int i=0;
unsigned char a[]={0x0e,0x0d,0x0b,0x07};
void delay(unsigned int x){
while(x--);
}
void io_init(void){
DDRC=0x0f;
PORTC=0x0f;
DDRB=0xff;
PORTB=0xff;
DDRD=0x02;
}
void t1_init(void){
TCCR1A=0x00;
TCCR1B=0x0a;
TCNT1=0;
OCR1A=625; //ctc模式
ICR1=0xffff;
}
void uart_init(void){
UCSR0A=0b01000000; //异步,1起始位,八数据位,无校验,一停止
UCSR0B=0b00011000; //发送接收使能
UCSR0C=0b00000110;
UBRR0=25;//baud=19200
}
void uart_send(unsigned char d){//数据发送
while(!(UCSR0A&(1<<UDRE0))); //等待数据寄存器为空
UDR0=d;
}
unsigned char uart_receive(void){//数据接收
while(!(UCSR0A&(1<<RXC0)));
return UDR0;
}
#pragma interrupt_handler Int_TCCR1A:12
void Int_TCCR1A(void){
k=(k+1)%4;
PORTC=0x0f;
PORTB=ledbuf[k];
PORTC=a[k];
}
void decode(unsigned int v){
ledbuf[0]=disp[v/1000];
ledbuf[0]&=0x7f; //最高位清零
v=v%1000;
ledbuf[1]=disp[v/100];
v=v%100;
ledbuf[2]=disp[v/10];
ledbuf[3]=disp[v%10];
}
int main(void){
uart_init();
io_init();
t1_init();
sei(); //开启总中断
TIMSK1=0x02;
while(1){
if((PIND&0x04)==0x04){
uart_send('a');
}
i=uart_receive();
decode(i);
}
}
```
注意:这里只是对代码中存在的问题进行了修改,但并不能保证代码的正确性。在实际应用中,还需要根据具体需求进行修改和优化。
阅读全文