#include <stdio.h> #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "driver/gpio.h" #define GW_GRAY_SERIAL_CLK 22 #define GW_GRAY_SERIAL_DAT 21 /** * @brief 读8次数据,每次输出一次时钟(上升沿+下降沿),然后读一次DAT IO数据 */ static esp_err_t gw_gray_serial_read(uint8_t *byte_read) { esp_err_t err; /* 姑且记录一下ESP-IDF的错误提示 */ uint8_t ret = 0; /* 把8个bit塞进这个变量里 */ /* 循环八次 */ for (int i = 0; i < 8; ++i) { err = gpio_set_level(GW_GRAY_SERIAL_CLK, 0); if (err) return err; ret <<= 1; /* 右移一位给数字数据腾位置 */ ret |= gpio_get_level(GW_GRAY_SERIAL_DAT); /* 把数字数据写入第一位bit */ err = gpio_set_level(GW_GRAY_SERIAL_CLK, 1); if (err) return err; esp_rom_delay_us(5); } *byte_read = ret; return err; } void app_main(void) { uint8_t sensor_data = 0; ESP_ERROR_CHECK(gpio_set_direction(GW_GRAY_SERIAL_CLK, GPIO_MODE_OUTPUT)); ESP_ERROR_CHECK(gpio_set_pull_mode(GW_GRAY_SERIAL_CLK, GPIO_PULLUP_ONLY)); ESP_ERROR_CHECK(gpio_set_direction(GW_GRAY_SERIAL_DAT, GPIO_MODE_INPUT)); ESP_ERROR_CHECK(gpio_set_pull_mode(GW_GRAY_SERIAL_DAT, GPIO_PULLUP_ONLY)); ESP_ERROR_CHECK(gpio_set_level(GW_GRAY_SERIAL_CLK, 0)); while(1) { ESP_ERROR_CHECK(gw_gray_serial_read(&sensor_data)); for (int i = 0; i < 8; ++i) { printf("%d ", (sensor_data >> i) & 0x1); } printf("\n"); vTaskDelay(pdMS_TO_TICKS(200)); } }