让ChatGPT编写嵌入式应用,三分钟完成传感器接入!

ChatGPT 生成的代码
```c
#include <zephyr.h>
#include <device.h>
#include <drivers/i2c.h>
#include <stdio.h>
#define SHT30_I2C_ADDR 0x44 // SHT30 的 I2C 地址
#define SHT30_CMD_MEASURE_HIGHREP 0x2C06 // SHT30 进行高精度测量的命令
void main(void) {
int err;
struct device *i2c_dev;
i2c_dev = device_get_binding("I2C_0"); // 获取 I2C 设备句柄
if (i2c_dev == NULL) {
printf("Failed to get I2C device handle\n");
return;
}
uint8_t cmd[2] = {SHT30_CMD_MEASURE_HIGHREP >> 8, SHT30_CMD_MEASURE_HIGHREP & 0xFF};
err = i2c_write(i2c_dev, cmd, sizeof(cmd), SHT30_I2C_ADDR); // 发送测量命令
if (err < 0) {
printf("Failed to send measurement command, error code: %d\n", err);
return;
}
k_sleep(K_MSEC(20)); // 等待测量完成
uint8_t data[6];
err = i2c_read(i2c_dev, data, sizeof(data), SHT30_I2C_ADDR); // 读取传感器数据
if (err < 0) {
printf("Failed to read data, error code: %d\n", err);
return;
}
// 解析数据并打印
uint16_t temp_raw = (data[0] << 8) | data[1];
uint16_t humidity_raw = (data[3] << 8) | data[4];
float temp = -45 + 175 * (float)temp_raw / 65535;
float humidity = 100 * (float)humidity_raw / 65535;
printf("Temperature: %.2f C\nHumidity: %.2f %%RH\n", temp, humidity);
}
```