本帖最后由 云帆沧海 于 2012-7-19 10:36 编辑
首先说明函数功能:
通过中断实现串口通信,首先由PC向stm32发送数据,然后再将收到的数据由stm32传回PC机,通过下面函数为什么不能实现?望指点
主函数:
#include "stm32f10x_lib.h"
#include "platform_config.h"
void RCC_Configuration(void); //时钟使能
void GPIO_Configuration(void); //GPIO使能
void NVIC_Configuration(void); //中断使能
USART_InitTypeDef USART_InitStructure;
int main(void)
{
RCC_Configuration();
NVIC_Configuration();
GPIO_Configuration();
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_Init(USART1, &USART_InitStructure);
USART_ITConfig(USART1, USART_IT_TXE|USART_IT_RXNE, ENABLE);
USART_Cmd(USART1, ENABLE);
while (1)
{
}
}
void RCC_Configuration(void)
{
/*使能串口1使用的GPIO时钟*/
RCC_APB2PeriphClockCmd(USART1_GPIO_CLK, ENABLE);
/*使能串口1时钟*/
RCC_APB2PeriphClockCmd(USART1_CLK, ENABLE);
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/*串口1 TX管脚配置*/
GPIO_InitStructure.GPIO_Pin = USART1_TxPin;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(USART1_GPIO, &GPIO_InitStructure);
/*串口1 RX管脚配置*/
GPIO_InitStructure.GPIO_Pin = USART1_RxPin;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(USART1_GPIO, &GPIO_InitStructure);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占式中断优先级设置为0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //响应式中断优先级设置为0
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
中断函数:
#include "stm32f10x_it.h"
#define RxBufferSize 0xfe
u8 RxBuffer[RxBufferSize];
u16 RxCounter = 0;
int i=0;
void receive_data(void) ; //声明接收发送函数
void send_data(void) ;
void USART1_IRQHandler(void) //中断主函数
{
while(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //检查串口1的接收中断
{
receive_data();
}
while(USART_GetITStatus(USART1, USART_IT_TXE) != RESET)
{
send_data() ;
}
USART_ITConfig(USART1, USART_IT_TXE|USART_IT_RXNE, ENABLE); //使能中断
}
void receive_data(void) //接收函数
{
RxBuffer[RxCounter++] = USART_ReceiveData(USART1); //接收数据
if(RxCounter<0xfe||'\n'==RxBuffer[RxCounter])
{
USART_ITConfig(USART1, USART_IT_RXNE, DISABLE); //失能接收中断
}
}
void send_data(void) //发送函数
{
if(i<RxCounter)
USART_SendData(USART1, RxBuffer[i++]);
// USART_ITConfig(USART1, USART_IT_TXE, DISABLE);
USART_ClearITPendingBit(USART1, USART_IT_TXE);
}
PS:本人使用的开发板为神舟三号,芯片类型STM32F103ZE |