控制/MCU
因为芯片串口不够用,只好用IO口模拟串口,在网上下载了个模拟串口的程序,可运行,但发现串口输出隔几个字符就会出现乱码,主要部分代码如下:
[cpp] view plain copy#define OI_TXD PAout(12)
#define OI_RXD PAin(11)
#define BuadRate_9600 100
u8 len = 0; //接收计数
u8 USART_buf[11]; //接收缓冲区
u8 recvStat = COM_STOP_BIT;
u8 recvData = 0;
void IO_TXD(u8 Data)
{
u8 i = 0;
OI_TXD = 0;
delay_us(BuadRate_9600);
for(i = 0; i 《 8; i++)
{
if(Data&0x01)
OI_TXD = 1;
else
OI_TXD = 0;
delay_us(BuadRate_9600);
Data = Data》》1;
}
OI_TXD = 1;
delay_us(BuadRate_9600);
}
void USART_Send(u8 *buf, u8 len)
{
u8 t;
for(t = 0; t 《 len; t++)
{
IO_TXD(buf[t]);
}
}
void IOConfig(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
EXTI_InitTypeDef EXTI_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOA, ENABLE); //使能PB,PC端口时钟
//SoftWare Serial TXD
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO口速度为50MHz
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA,GPIO_Pin_12);
//SoftWare Serial RXD
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource11);
EXTI_InitStruct.EXTI_Line = EXTI_Line11;
EXTI_InitStruct.EXTI_Mode=EXTI_Mode_Interrupt;
EXTI_InitStruct.EXTI_Trigger=EXTI_Trigger_Falling; //下降沿触发中断
EXTI_InitStruct.EXTI_LineCmd=ENABLE;
EXTI_Init(&EXTI_InitStruct);
NVIC_InitStructure.NVIC_IRQChannel= EXTI15_10_IRQn ;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2;
NVIC_InitStructure.NVIC_IRQChannelSubPriority =2;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
[cpp] view plain copyint main(void)
{
delay_init();
IOConfig();
while(1)
{
USART_Send(“100”,3);
delay_ms(100);
}
一般出现输出乱码,可能是输出部分延时不够造成的,于是检查输出部分使用延时的情况,发现USART_Send中没有用到延时,所在在USART_Send中加入一个1ms的延时,错误解除,改过的代码如下:
[cpp] view plain copyvoid USART_Send(u8 *buf, u8 len)
{
u8 t;
for(t = 0; t 《 len; t++)
{
IO_TXD(buf[t]);
delay_ms(1);
}
}
延时虽然简单,但有时真的会发挥很大的作用。
全部0条评论
快来发表一下你的评论吧 !