本人使用的是正点原子购买的开发板——精英版STM32F103ZET6
这款开发板的其中一个LED引脚PB5,看下图

#代码直接放在main.c中编译,加入所需库函数
#include <stm32f10x.h>
#include <stm32f10x_usart.h>
#include <stm32f10x_gpio.h>
#include <stm32f10x_rcc.h>
#include <misc.h>
#include <string.h>
#include <stdio.h>
#define LED_ON GPIO_ResetBits(GPIOB,GPIO_Pin_5);
#define LED_OFF GPIO_SetBits(GPIOB,GPIO_Pin_5);
#define MAX 100
u8 RxBuffer[MAX];
u8 TxBuffer[MAX];
int RxCount=0;
int TxCount=0;
void GPIO_LED_init()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_5;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_SetBits(GPIOB,GPIO_Pin_5);
}
void GPIO_USART_int()
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
void USART_init()
{
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
USART_InitStructure.USART_BaudRate=115200;
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
USART_InitStructure.USART_Parity=USART_Parity_No;
USART_InitStructure.USART_StopBits=USART_StopBits_1;
USART_InitStructure.USART_WordLength=USART_WordLength_8b;
USART_Cmd(USART1,ENABLE);
USART_Init(USART1,&USART_InitStructure);
}
char USART1_SendByte(u8 data)
{
int cnt = 0;
USART_SendData(USART1,data);
while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET)
{
cnt++;
if(cnt>12000)
return 0;
}
return 1;
}
u8 USART1_GetByte()
{
while(USART_GetFlagStatus(USART1,USART_FLAG_RXNE)==RESET){}
return (USART_ReceiveData(USART1));
}
u8 ReceiveData()
{
vu32 cnt=0;
while(1)
{
RxBuffer[RxCount++]=USART1_GetByte();
if(strstr((char *)RxBuffer,"ON")!=NULL)
{
RxCount=0;
return 1;
}
else
if(strstr((char *)RxBuffer,"OFF")!=NULL)
{
RxCount=0;
return 2;
}
else
if(RxCount>3)
{
RxCount=0;
return 0;
}
}
}
void SendString(u8 *state)
{
while(*state!='\0')
USART1_SendByte(*state++);
}
void EmptyRxBuffer(u8 len)
{
u8 i;
for(i=0;i<len;i++)
RxBuffer[i]=0;
}
int main(void)
{
GPIO_LED_init();
GPIO_USART_int();
USART_init();
while(1)
{
switch(ReceiveData())
{
case 1:
if((GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5))==RESET)
SendString((u8 *)("the LED has been ON\n"));
else
{
LED_ON;
SendString((u8 *)("the LED is ON now\n"));
}
break;
case 2:
if((GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_5))!=RESET)
SendString((u8 *)("the LED has been OFF\n"));
else
{
LED_OFF;
SendString((u8 *)("the LED is OFF now\n"));
}
break;
case 0:
SendString((u8 *)("Command erro!\n"));
break;
}
EmptyRxBuffer(MAX);
}
}