1、接收
默认串口的数据格式为 一位起始位+8位数据位+停止位,由于起始位为低电平,停止位为高电平。因此,RX线要使能外部中断,中断方式为下降沿中断。只需要在中断程序中使能定时器,并且要在main函数之前对定时器进行初始化,设置定时器的预装值,这里设置的预装值就是设置串口的波特率,另外还要使能定时器的更新中断,在定时器的中断处理程序中,按位接收串口发送过来的数据。当接收到停止位时,失能定时器,然后对定时器进行清零处理
下面是外部中断处理函数:
INTERRUPT_HANDLER(EXTI_PORTA_IRQHandler, 3)
{
if(EXTI_GetExtIntSensitivity(EXTI_PORT_GPIOA)==EXTI_SENSITIVITY_FALL_LOW
&& emuart_struct.statu==EMUART_WAIT)
{
GPIO_Init(GPIOA, GPIO_PIN_3, GPIO_MODE_IN_FL_NO_IT); //关闭PA.3中断
emuart_struct.statu=EMUART_RECV;
TIM2_Cmd(ENABLE); //Delay(0X1FF); //启动定时器
}
}
2、发送
原理同接收一样,在发送函数中使能定时器,并且将RX口线拉低。在定时器更新中断处理函数中按位发送数据,当数据发送完毕后将RX线拉高,并且失能定时器,然后对定时器进行清零处理。
下面是定时器中断处理函数:
INTERRUPT_HANDLER(TIM2_UPD_OVF_BRK_IRQHandler, 13)
{
static unsigned char recvdata=0;
unsigned char bitemp=0;
unsigned char readbit;
if(TIM2_GetITStatus(TIM2_IT_UPDATE)==SET)
{
TIM2_ClearITPendingBit(TIM2_IT_UPDATE);
if(emuart_struct.statu==EMUART_RECV) //读取数据
{
emuart_struct.bitRecved++;
if(emuart_struct.bitRecved>=1 && emuart_struct.bitRecved<=8)
{
if(GPIO_ReadInputPin(GPIOA, GPIO_PIN_3) == 0X08)
{
readbit=(unsigned char)(1<
}
else
{
readbit=(unsigned char)(0<
}
recvdata|=readbit;
}
else if(emuart_struct.bitRecved==9)
{
emuart_struct.bitRecved=0;
emuart_struct.recvData=recvdata;
emuart_struct.isRead=ISNOTREAD;
emuart_struct.statu=EMUART_WAIT;
recvdata=0;
TIM2_Cmd(DISABLE); //关闭定时器
TIM2->CNTRH=0;//TIM2->ARRH; //定时器清零
TIM2->CNTRL=0;//TIM2->ARRL;
GPIO_Init(GPIOA, GPIO_PIN_3, GPIO_MODE_IN_FL_IT); //打开外部中断
}
}
else if(emuart_struct.statu==EMUART_SEND) //发送数据
{
emuart_struct.bitSended++;
if(emuart_struct.bitSended>=1 && emuart_struct.bitSended<=8)
{
bitemp=(emuart_struct.sendData>>(emuart_struct.bitSended-1))&0x01;
if(bitemp==1)
{
GPIO_WriteHigh(GPIOB, GPIO_PIN_4);
}
else if(bitemp==0)
{
GPIO_WriteLow(GPIOB, GPIO_PIN_4);
}
}
else if(emuart_struct.bitSended==9) //发送或接收数据完毕
{
emuart_struct.bitSended=0;
GPIO_WriteHigh(GPIOB,GPIO_PIN_4);
emuart_struct.statu=EMUART_WAIT;
emuart_struct.isSend=ISEND;
TIM2_Cmd(DISABLE); //关闭定时器
TIM2->CNTRH=0; //定时器清零
TIM2->CNTRL=0;
}
}
}
}
『本文转载自网络,版权归原作者所有,如有侵权请联系删除』