CubeMX配置
- 开一个串口
- 开一个输入引脚,配置成下拉模式
硬件连接
VCC —— 5.5V
Sign —— PB5
GND —— GND
代码
hc_sr505.c
#include "hc_sr505.h"
#include "GPIO.h"
#define HC_SR505_Port GPIOB
#define HC_SR505_PIN GPIO_PIN_5
uint8_t hs_sr505_Judge(void)
{
if((HC_SR505_Port->IDR & HC_SR505_PIN) == HC_SR505_PIN)
{
return manned;
}
else
{
return unmanned;
}
}
hc_sr505.h
#ifndef __HC_SR505_H_
#define __HC_SR505_H_
#include "stdint.h"
typedef enum
{
manned = 0,
unmanned
}IsThereAnyone;
//判断有没有人
uint8_t hs_sr505_Judge(void);
/* //使用方法
if(hs_sr505_Judge() == manned)
PrintfDebug("有人\r\n");
else
PrintfDebug("没人\r\n");
*/
#endif /*__HC_SR505_H_*/
main.c
头文件
#include "hc_sr505.h"
#include "stdio.h"
#include "stdarg.h"
主文件外部函数
#define DEBUG_HUART huart1
/* 手写printf,避免使用微库造成不必要的错误 */
#define CONSOLEBUF_SIZE 512
void PrintfDebug(const char *fmt, ...)
{
char Uart_buf[CONSOLEBUF_SIZE];
va_list args;
va_start(args, fmt);
int length = vsnprintf(Uart_buf, sizeof(Uart_buf) - 1, fmt, args);
va_end(args);
HAL_UART_Transmit(&DEBUG_HUART, (uint8_t *)Uart_buf, length, 0xff);
}
初始化
无
主循环
if(hs_sr505_Judge() == manned)
PrintfDebug("有人\r\n");
else
PrintfDebug("没人\r\n");
HAL_Delay(200);