打印
[AVR单片机]

串口错码怎么解决?高手来看下。

[复制链接]
1704|8
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
ll_211314|  楼主 | 2009-11-26 14:13 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
用串口调试软件发数据给单片机,单片机再把收到的数据发出去,用串口调试软件查看单片机发送的数据.

结果发现串口调试软件接收到的数据很多和发出去的不一样,搞不清楚是怎么回事了,懂的人指导一下。

波特率1200,无校验,数据位8,停止位1 。


// Target : M16
// Crystal: 8.0000Mhz
//AVR单片机atmega16串口中断接收和发送程序。接收到字符后再发送出去
#include <iom16v.h>
#include <macros.h>
unsigned char com_in_buf[1];
void port_init(void)
{
PORTA = 0x00;
DDRA  = 0x00;
PORTB = 0x00;
DDRB  = 0xFF;
PORTC = 0x00; //m103 output only
DDRC  = 0x00;
PORTD = 0xFF;
DDRD  = 0xFF;
}

//UART0 initialize  
// desired baud rate: 1200  
// actual: baud rate:1200 (0%)  
// char size: 8 bit  
// parity: Disabled  
void uart0_init(void)
{
UCSRB = 0x00; //disable while setting baud rate
UCSRA = 0x00;
UCSRC = BIT(URSEL) | 0x06;
UBRRL = 0xF9; //set baud rate lo
UBRRH = 0x00; //set baud rate hi
UCSRB = 0x98;
}

void send_data(unsigned char back)
{
  while( !( UCSRA & (1<<UDRE)) ) ;
  UDR=back;
}

#pragma interrupt_handler uart0_rx_isr:12
void uart0_rx_isr(void)
{
//uart has received a character in UDR
com_in_buf[0]=UDR;
send_data(com_in_buf[0]);
}

//call this routine to initialize all peripherals
void init_devices(void)
{
//stop errant interrupts until set up
CLI(); //disable all interrupts
port_init();
uart0_init();

MCUCR = 0x00;
GICR  = 0x00;
TIMSK = 0x00; //timer interrupt sources
SEI(); //re-enable interrupts
//all peripherals are now initialized
}

void main(void)
{
  char j;
  init_devices();
  while(1)
  {
    for(j=1;j<100;j++)
  ;
  }
}

相关帖子

沙发
宇容创行| | 2009-11-26 14:21 | 只看该作者
不用在中断里发数据
收发最好都用中断

icc的代码,直接看安装目录下的uartintr.c

学习规范的做法

使用特权

评论回复
板凳
donkey89| | 2009-11-26 21:28 | 只看该作者
你试试直接发,不用中断.

使用特权

评论回复
地板
NE5532| | 2009-11-27 21:53 | 只看该作者
串口一般很少出错,查波特率。

使用特权

评论回复
5
wangwo| | 2009-11-27 22:43 | 只看该作者
过来学习

使用特权

评论回复
6
ll_211314|  楼主 | 2009-12-3 09:07 | 只看该作者
问题已解决,是usb转串口不行,换了个pci扩展出来的串口就好了。

使用特权

评论回复
7
wangwo| | 2009-12-3 22:20 | 只看该作者
解决了就好

使用特权

评论回复
8
suoma| | 2009-12-4 21:26 | 只看该作者
也就是说程序没问题?

使用特权

评论回复
9
love_life| | 2009-12-5 00:42 | 只看该作者
usb转串口非常不好用,老容易出错了

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

10

主题

38

帖子

0

粉丝