2018年2月9日,昨天学习内容如下:
巩固前面学的知识,通过一个题目——通过串口中断功能来控制LED灯亮灭。完整代码见下面
部分代码参考的烈火狂龙大哥的课本
#include<stm32f10x.h>
#define LEDON GPIOC->BSRR = GPIO_Pin_13
#define LEDOFF GPIOC->BRR = GPIO_Pin_13
unsigned char temp=' ';
void delay(uint16_t n)
{
uint16_t i,j;
for(i=0; i<n;i++)
for(j=0;j<8500;j++);
}
int main(void)
{
void led_init();
void uart1_init(uint32_t baud);
void Nvic_Init(void);
//led init
led_init();
uart1_init(115200);
Nvic_Init();
LEDON;
while(1){
delay(2000);
if(temp)
USART_ITConfig(USART1,USART_IT_TXE,ENABLE);
}
}
void led_init()
{
GPIO_InitTypeDef GPIO_Structure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_Disable,ENABLE);
GPIO_PinRemapConfig(GPIO_Remap_SWJ_JTAGDisable,ENABLE);
GPIO_Structure.GPIO_Pin= GPIO_Pin_13;
GPIO_Structure.GPIO_Speed= GPIO_Speed_50MHz;
GPIO_Structure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC,&GPIO_Structure);
}
void uart1_init(uint32_t baud)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
GPIO_InitStructure.GPIO_Pin= GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = baud;
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_RXNE,ENABLE);///////
////
USART_Cmd(USART1,ENABLE);
USART_ClearFlag(USART1,USART_FLAG_TC);
}
void Nvic_Init(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
//NVIC_PriorityGroup
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority= 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void USART1_IRQHandler(void)
{
//if(USART_GetFlagStatus(USART1,USART_FLAG_ORE)!= RESET){USART_ReceiveData(USART1);}
if(USART1->SR & USART_SR_TC)
{
USART1->DR = temp;
temp=0;
USART1->CR1 &= ~USART_CR1_TXEIE;
}
if(USART1-> SR & USART_SR_RXNE)
{
temp = (unsigned char)USART1->DR;
if(temp == 'k')
LEDON;
if(temp == 'g')
LEDOFF;
}
}
|