点灯
#include "stm32f10x.h"
#include <math.h>
#include <stdio.h>
#include "delay.h"
#define PI_F 3.14159265f
void led_init(){
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
IO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET);
}
int main(void)
{
while (1)
{
if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == Bit_RESET)
{
GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_SET);
}
else
{
GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET);
}
}
}
重写fputc(),串口打印字符串
int fputc(int ch, FILE *f)
{
USART1_SendByte((uint8_t)ch);
return ch;
}
串口发送数据
void usart_send_string(void)
{
const char *str = "Hello, USART!\r\n";
USART1_SendBuffer((const uint8_t *)str, (uint16_t)strlen(str));
}
串口接收数据
void usart_receive_string(void)
{
static uint8_t buffer[128];
static uint16_t len = 0;
static uint32_t last_tick = 0;
const uint32_t rx_timeout_ms = 200; // 超时(毫秒),无新字节则认为接收完成
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET)
{
// 读取所有可用字节以防止在高波特率下漏掉数据
while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) != RESET)
{
uint8_t ch = (uint8_t)USART_ReceiveData(USART1);
if (len < sizeof(buffer) - 1)
{
buffer[len++] = ch;
}
last_tick = GetTick();
if (ch == '\r' || ch == '\n')
{
// 去除结尾的 CR/LF 后打印
while (len > 0 && (buffer[len-1] == '\r' || buffer[len-1] == '\n')) len--;
if (len > 0)
{
buffer[len] = '\0';
printf("RECV: %s\r\n", buffer);
}
len = 0;
}
}
}
// 若缓冲非空且超时,则认为接收完成,打印并清缓冲
if (len > 0 && (GetTick() - last_tick) >= rx_timeout_ms)
{
buffer[len] = '\0';
printf("RECV: %s\r\n", buffer);
len = 0;
}
}