发帖原因:自己遇到了,串口通信乱码的问题
解决方法:设置芯片PLL
过程:程序不是自己所写,波特率原先被调置为38400,用示波器观测波形,发现脉宽非计算所需值,查找资料
参考:http://blog.sina.com.cn/s/blog_6035432c0100tyg1.html
开发环境:MDK4.22
硬件:LPC2132, J-LINK
程序代码:
/*******************************************************************************
*File: main.C
*功能: 串口发送数据
*说明: 使用外部晶振,不使用PLL,Fpclk=Fcclk/4
*******************************************************************************/
#include "config.h"
#define LEDS8 0xFF << 16 // P1[25:18]控制LED8~LED1
/*******************************************************************************
*名称: DelayNS()
*功能: 长软件延时
*******************************************************************************/
void DelayNS(uint32 dly)
{ uint32 i;
for(;dly>0;dly--)
for(i=0;i<50000;i++);
}
/*******************************************************************************
*名称: UART0_Ini()
*功能: 初始化串口0.设置为8位数据位,1位停止位,无奇偶校验,波特率为9600
*******************************************************************************/
void UART0_Ini(void)
{
/*
* BIT symbol value descrption reset value
* 1:0 word length 00 5 bit character 0
* select 01 6 bit character
* 10 7 bit character
* 11 8 bit character
* 2 stop bit 0 1 stop bit 0
* select 1 2 stop bit
* 3 parity enable 0 disable parity generation and check 0
* 1 enable parity generation and checking
* 5:4 parity select 00 odd parity 0
* 01 even parity
* 10 forced "1" stick parity
* 11 forced "0" stick parity
*/
U0LCR=0x83; //DLAB=1,可设置波特率
U0DLL=0x48; // baudrate = Fpclk/(16*(16*U0DLM + U0DLL))
U0DLM=0x00;
U0LCR=0x03;
}
/*******************************************************************************
*名称: UART0_SendByte()
*功能: 向串口发送字节数据,并等待发送完毕
*******************************************************************************/
void UART0_SendByte(uint8 data)
{ U0THR=data; //发送数据
while((U0LSR&0x40)==0) ; //等待数据发送完毕
{
uint32 i;
for(i=0; i<5; i++);
}
}
/*******************************************************************************
*名称:UART0_SendStr()
*功能:向串口发送一字符串
*******************************************************************************/
void UART0_SendStr(uint8 const *str)
{ while(1)
{ if(*str=='\0')
{UART0_SendByte('\r');
UART0_SendByte('\n');
break;
}
UART0_SendByte(*str++); //发送数据
}
}
char UART0_RecvByte(void)
{ while(!(U0LSR&0x01));
return U0RBR;
}
/*******************************************************************************
*名称: main()
*功能: 向串口UART0发送字符串"Hello World!"
*******************************************************************************/
int main(void)
{
uint8 const SEND_STRING[]="HELLO WORLD!\n";
uint8 const SEND_STR[]="the leds will display last character ASCII code\n";
unsigned char temp;
PINSEL0=0x00000005; //设置I/O连接到UART0
PINSEL1=0x00000000;
PINSEL2 = PINSEL2 & (~0x08); // P1[25:16]连接GPIO
IO1DIR = LEDS8; // LED灯控制口输出
UART0_Ini();
UART0_SendStr(SEND_STRING);
UART0_SendStr(SEND_STR);
DelayNS(10);
while(1)
{
temp = UART0_RecvByte();
UART0_SendByte(temp);
IO1CLR = LEDS8 & (0Xff << 16);
IO1SET = LEDS8 & (temp << 16);
}
}
KEIL中设置为:
设置MSEL = PSEL = 4
上述代码可以正常使用。