STM32新手~~~
// usart.c
void NVIC_Config(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
/* Enable the USARTx Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void Uart_Init(void)
{
USART_InitTypeDef USART_InitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
uchar temp;
temp++;
// PA9 -- TX PA10 -- RX
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_Init(GPIOA, &GPIO_InitStructure);
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_Cmd(USART1, ENABLE);
//USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
//NVIC_Config();
}
void UART1Write(uchar* data,uint len)
{
u16 i;
for(i=0; i<len; i++)
UART1_SendBuf[i] = data[i];
UART1_SendSum = len;
USART_ITConfig(USART1, USART_IT_TXE, ENABLE);
for (i=0; i<len; i++)
{
USART_SendData(USART1, data[i]);
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
{
;
}
}
}
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
UART1_BUF[UART1_COUNT++] = USART_ReceiveData(USART1); //接收数据
if(UART1_COUNT >= UART1BUF_SIZE_MAX) //超过最大缓存,清零计数
{
UART1_COUNT = 0;
}
}
}
// main.c
uchar array[] = {0xaa, 0xaa, 0xaa, 0xaa, 0xaa};
SystemInit();
while(1)
{
UART1Write(array, 1);
}
//-------------------------程序分割线------------------------------------
以上是usart.c和main.c中的内容 省略了头文件和一些参数的声明
遇到了两个问题:
1.发送的数据错误,不是0xaa,而是别的值。测试过Tx脚的波特率,应该是正确的,不知道是什么原因了,求解。
2.如果//NVIC_Config();去掉注释,则程序会一直死在里面出不来,后面的数据也不会发送。
以上配置都是从其他贴子中复制过来的,不知道错在哪里。
此帖出自
小平头技术问答
为什么这么说?
1.我查看了下数据手册,上面说TXE中断标志位需要通过软件清楚,所以我在发送函数最后加了一句USART1->CR1 &= 0xff7f;可是结果还是死在循环中。
2.为何在数据手册中说RXNE中断也需要通过软件清楚标志位,可是正常使用的时候开启RXNE中断,每次只需要读取其中接收到的数据,程序就不会死在循环中?
This bit is set by hardware when the content of the RDR shift register has been transferred
to the USART_DR register. An interrupt is generated if RXNEIE=1 in the USART_CR1
register. It is cleared by a read to the USART_DR register. The RXNE flag can also be
cleared by writing a zero to it. This clearing sequence is recommended only for multibuffer
communication.
0: Data is not received
1: Received data is ready to be read.
一周热门 更多>