123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- /* include ---------------------------------------------------------*/
- #include "main.h"
- /* private define -------------------------------------------------*/
- // ECHO
- #define ECHO_GPIO_PORT GPIOA /* GPIO端口 */
- #define ECHO_GPIO_CLK RCC_APB2Periph_GPIOA /* GPIO端口时钟 */
- #define ECHO_GPIO_PIN GPIO_Pin_8 /* 连接到SCL时钟线的GPIO */
- #define ECHO_GPIO_TOGGLE ECHO_GPIO_PORT->BSRR = ((ECHO_GPIO_PORT->ODR & ECHO_GPIO_PIN) << 16) | (~ECHO_GPIO_PORT->ODR & ECHO_GPIO_PIN)
- #define ECHO_GPIO_SET ECHO_GPIO_PORT->BSRR = (uint32_t)ECHO_GPIO_PIN // 置1
- #define ECHO_GPIO_RESET ECHO_GPIO_PORT->BSRR = (uint32_t)ECHO_GPIO_PIN<<16 // 置0
- #define ECHO_GPIO_READ ((ECHO_GPIO_PORT->IDR & ECHO_GPIO_PIN) != 0)
- // TRIG
- #define TRIG_GPIO_PORT GPIOB /* GPIO端口 */
- #define TRIG_GPIO_CLK RCC_APB2Periph_GPIOB /* GPIO端口时钟 */
- #define TRIG_GPIO_PIN GPIO_Pin_15 /* 连接到SCL时钟线的GPIO */
- #define TRIG_GPIO_TOGGLE TRIG_GPIO_PORT->BSRR = ((TRIG_GPIO_PORT->ODR & TRIG_GPIO_PIN) << 16) | (~TRIG_GPIO_PORT->ODR & TRIG_GPIO_PIN)
- #define TRIG_GPIO_SET TRIG_GPIO_PORT->BSRR = (uint32_t)TRIG_GPIO_PIN // 置1
- #define TRIG_GPIO_RESET TRIG_GPIO_PORT->BSRR = (uint32_t)TRIG_GPIO_PIN<<16 // 置0
- #define TRIG_GPIO_READ ((TRIG_GPIO_PORT->IDR & TRIG_GPIO_PIN) != 0)
- /* private variables ----------------------------------------------*/
- /* private function prototypes ------------------------------------*/
- static void Init(void);
- static uint16_t Read(void);
- /* public variables -----------------------------------------------*/
- SR04_t SR04 =
- {
- Init,
- Read
- };
- /**
- * @brief SR04 Init
- * @param None
- * @retval None
- * @note None
- */
- static void Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStructer;
- RCC_APB2PeriphClockCmd(TRIG_GPIO_CLK, ENABLE);
- /*TRIG触发信号*/
- GPIO_InitStructer.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_InitStructer.GPIO_Mode=GPIO_Mode_Out_PP;
- GPIO_InitStructer.GPIO_Pin=TRIG_GPIO_PIN;
- GPIO_Init(TRIG_GPIO_PORT, &GPIO_InitStructer);
- GPIO_ResetBits(TRIG_GPIO_PORT,TRIG_GPIO_PIN);
- RCC_APB2PeriphClockCmd(ECHO_GPIO_CLK, ENABLE);
- /*ECOH回响信号*/
- GPIO_InitStructer.GPIO_Mode=GPIO_Mode_IN_FLOATING;
- GPIO_InitStructer.GPIO_Pin=ECHO_GPIO_PIN;
- GPIO_Init(ECHO_GPIO_PORT, &GPIO_InitStructer);
- }
- /**
- * @brief Read IO口控制
- * @param None
- * @retval cm
- * @note None
- */
- static uint16_t Read(void)
- {
- uint32_t tim_time = 0;
- uint16_t length = 0;
- TRIG_GPIO_SET;
- DELAYClass.DelayUs(20);
- TRIG_GPIO_RESET;
- //等待返回信号
- while(ECHO_GPIO_READ == RESET)
- {
- tim_time++;
- DELAYClass.DelayUs(1);
- if(tim_time >= 10000)
- {
- return 10000;
- }
- }
- tim_time = 0;
- //等待返回信号
- while(ECHO_GPIO_READ)
- {
- tim_time++;
- DELAYClass.DelayUs(1);
- if(tim_time >= 10000)
- {
- return 10000;
- }
- }
- //关闭定时器
- length = (tim_time * 0.12)/2;
- return length;
-
- }
|