要求亮度低于某个阈值时开启电动机和紫外灯,高于这个阈值时关闭电动机和紫外灯。首先阅读B5样例,理解后编写代码如下:
#include <stdio.h>
#include <unistd.h>
#include "cmsis_os2.h"
#include "iot_errno.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_i2c.h"
#include "ohos_init.h"
#define I2C_TASK_STACK_SIZE (1024 * 8)
#define I2C_TASK_PRIO 25
#define WIFI_IOT_IO_FUNC_GPIO_0_I2C1_SDA 6
#define WIFI_IOT_IO_FUNC_GPIO_1_I2C1_SCL 6
#define WIFI_IOT_I2C_IDX 1
#define WIFI_IOT_I2C_BAUDRATE 400000
#define TASK_DELAY_1S 1000000
#define BH_1750_ADDR 0x23
#define BH_1750_STARTUP '\x10'
#define BH_1750_WR_ADDR ((BH_1750_ADDR << 1) | 0x0)
#define BH_1750_RD_ADDR ((BH_1750_ADDR << 1) | 0x1)
#define LUX_THRSHD 1000
static char g_data[2];
/**
* @brief i2c task writes data to NFC tag
*
*/
static void I2cTask(void)
{
// GPIO_0 multiplexed to I2C1_SDA
IoTGpioInit(0);
IoTGpioSetFunc(0, WIFI_IOT_IO_FUNC_GPIO_0_I2C1_SDA);
// GPIO_1 multiplexed to I2C1_SCL
IoTGpioInit(1);
IoTGpioSetFunc(1, WIFI_IOT_IO_FUNC_GPIO_1_I2C1_SCL);
// baudrate: 400kbps
IoTI2cInit(WIFI_IOT_I2C_IDX, WIFI_IOT_I2C_BAUDRATE);
// 初始化紫外灯 14
IoTGpioInit(14);
IoTGpioSetFunc(14, IOT_GPIO_FUNC_GPIO_14_GPIO);
IoTGpioSetDir(14, IOT_GPIO_DIR_OUT);
// 初始化电动机 8
IoTGpioInit(8);
IoTGpioSetFunc(8, IOT_GPIO_FUNC_GPIO_8_GPIO);
IoTGpioSetDir(8, IOT_GPIO_DIR_OUT);
// 初始化光敏电阻
g_data[0] = BH_1750_STARTUP;
IoTI2cWrite(WIFI_IOT_I2C_IDX, BH_1750_WR_ADDR, g_data, 1);
while (1) {
IoTI2cRead(WIFI_IOT_I2C_IDX, BH_1750_RD_ADDR, g_data, 2);
unsigned short lux = *(unsigned short*)g_data;
printf("lux = %hd\n", lux);
if (lux < LUX_THRSHD) {
IoTGpioSetOutputVal(14, 1);
IoTGpioSetOutputVal(8, 1);
} else {
IoTGpioSetOutputVal(14, 0);
IoTGpioSetOutputVal(8, 0);
}
usleep(TASK_DELAY_1S);
}
}
/**
* @brief Main Entry of the I2c Example
*
*/
static void I2cExampleEntry(void)
{
osThreadAttr_t attr;
attr.name = "I2cTask";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = I2C_TASK_STACK_SIZE;
attr.priority = I2C_TASK_PRIO;
if (osThreadNew((osThreadFunc_t)I2cTask, NULL, &attr) == NULL) {
printf("Falied to create I2cTask!\n");
}
}
APP_FEATURE_INIT(I2cExampleEntry);