这个例子是基于HiSpark Wi-Fi IoT套件Hi3861板子人体红外感应设备和光敏电阻实例,从本例程中,在HarmonyOS中Hi3861 如何控制操作外设设备
1. 如何操作IO口,来控制三色LED输出,读取人体感应
2. 通过ADC光敏电阻数值
3. I2C控制OLED 显示输出的结果。
============================================================
1. 代码如下:
/* 读取人体红外感应
* HiSpark_WiFi_IoT_DCL板
* GPIO_09 ADC3光敏电阻
* GPIO_10 RED 灯
* GPIO_11 GREEN 灯
* GPIO_12 BLUE 灯
* GPIO_07 人体红外
*/
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_watchdog.h"
#include "wifiiot_pwm.h"
#include "wifiiot_adc.h"
#include "oled_ssd1306.h"
#define ANALOG_CHAN_NAME WIFI_IOT_ADC_CHANNEL_4
#define R_LED WIFI_IOT_GPIO_IDX_10
#define B_LED WIFI_IOT_GPIO_IDX_12
#define G_LED WIFI_IOT_GPIO_IDX_11
static void *SensorTask(const char *arg)
{
int status = 0;
(void)arg;
printf("SensorTask start!rn");
while (1)
{
static char text[128] = {0};
unsigned short data = 0;
AdcRead(ANALOG_CHAN_NAME, &data, WIFI_IOT_ADC_EQU_MODEL_4, WIFI_IOT_ADC_CUR_BAIS_DEFAULT, 0);
snprintf(text, sizeof(text), "%d ", data);
OledShowString(0, 2, text, 1);
if(data>1500){
if(status==0){
OledShowString(0, 4, "PH0_RES!!!", 1);
}
status=1;
}else{
if(status==1){
OledShowString(0, 4, " ", 1);
}
status=0;
}
WifiIotGpioValue rel=0;
if(GpioGetInputVal(WIFI_IOT_IO_NAME_GPIO_7, &rel) == 0){//当有感应到有人体在运动时,三色LED会同时点亮
snprintf(text, sizeof(text), "GPIO_7=%d", (int)rel);
OledShowString(0, 5, text, 1);
GpioSetOutputVal(R_LED, (int)rel);
GpioSetOutputVal(B_LED, (int)rel);
GpioSetOutputVal(G_LED, (int)rel);
}
usleep(20 * 1000);
}
return NULL;
}
static void StartSensorTask(void)
{
osThreadAttr_t attr;
GpioInit();
//设置红色,蓝 色,绿色 LED IO为输出状态
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_10, WIFI_IOT_IO_FUNC_GPIO_10_GPIO);
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_10, WIFI_IOT_GPIO_DIR_OUT);
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_IO_FUNC_GPIO_11_GPIO);
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_11, WIFI_IOT_GPIO_DIR_OUT);
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_IO_FUNC_GPIO_12_GPIO);
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_12, WIFI_IOT_GPIO_DIR_OUT);
//设置IO为输入状态,并许能中断
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_IO_FUNC_GPIO_9_GPIO);
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_9, WIFI_IOT_GPIO_DIR_IN);
IoSetFunc(WIFI_IOT_IO_NAME_GPIO_7, WIFI_IOT_IO_FUNC_GPIO_7_GPIO);
GpioSetDir(WIFI_IOT_IO_NAME_GPIO_7, WIFI_IOT_GPIO_DIR_IN);
IoSetPull(WIFI_IOT_IO_NAME_GPIO_7, WIFI_IOT_IO_PULL_UP);
OledInit();
OledFillScreen(0x00);
OledShowString(0, 0, "Hello Test", 1);
WatchDogDisable();
//设置任务参数,并Start一个SensorTask任务线程
attr.name = "SensorTask";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 2048;
attr.priority = osPriorityNormal;
if (osThreadNew((osThreadFunc_t)SensorTask, NULL, &attr) == NULL)
{
printf("[Demo] Falied to create SensorTask!n");
}
}
APP_FEATURE_INIT(StartSensorTask); //在APP中初始化中回调StartSensorTask(void)
=========================================================
2. 附上代码:
=========================================================
3. 编译视频