usbsio_demos/demos/dht_sensor/src/main.c

103 lines
2.4 KiB
C

#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
/* USBSIO header */
#include <lpcusbsio.h>
/* AHT10 */
#include "aht10.h"
static bool s_running = true;
static aht10_ret_t aht_impl_xfer(void *pdev, aht10_xfer_desc_t *xfer);
static aht10_ret_t aht_impl_delay(void *pdev, uint32_t msec);
static void signal_handler(int sig);
int main(int argc, const char *argv[]) {
int ret;
LPC_HANDLE dev_handle;
LPC_HANDLE i2c_handle;
fprintf(stdout, "USBSIO example - AHT10\n");
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
/* Find all SIO devices. */
ret = LPCUSBSIO_GetNumPorts(LPCUSBSIO_VID, MCULINKSIO_PID);
if (ret == 0) {
fprintf(stderr, "No MCU-Link devices found.\n");
return -1;
}
/* Open device */
dev_handle = LPCUSBSIO_Open(0); /* For now, open the first device available. */
if (dev_handle == NULL) {
fprintf(stderr, "Failed to open device #0\n");
return -2;
}
fprintf(stdout, "%s\n", LPCUSBSIO_GetVersion(dev_handle));
I2C_PORTCONFIG_T i2c_cfg = {
.ClockRate = I2C_CLOCK_FAST_MODE,
.Options = 0U,
};
i2c_handle = I2C_Open(dev_handle, &i2c_cfg, 0);
aht10_t aht = {
.user_data = i2c_handle,
.cb =
{
.delay = aht_impl_delay,
.xfer = aht_impl_xfer,
},
};
aht10_init(&aht);
aht10_result_t result;
while (s_running) {
if (aht10_measure(&aht, &result) != AHT10_OK) {
fprintf(stderr, "Sensor communication error.\n");
} else {
fprintf(stdout, "Temperature: %.3fC, humidity: %.3f%%\n", result.temperature, result.humidity);
}
usleep(100 * 1000);
}
}
static aht10_ret_t aht_impl_xfer(void *pdev, aht10_xfer_desc_t *xfer) {
LPC_HANDLE i2c_handle = pdev;
I2C_FAST_XFER_T i2c_xfer = {
.options = 0U,
.slaveAddr = 0x38,
.rxBuff = xfer->rx_data,
.rxSz = xfer->rx_size,
.txBuff = xfer->tx_data,
.txSz = xfer->tx_size,
};
int ret = I2C_FastXfer(i2c_handle, &i2c_xfer);
if (ret < 0) {
return AHT10_FAIL;
}
return AHT10_OK;
}
static aht10_ret_t aht_impl_delay(void *pdev, uint32_t msec) {
usleep(msec * 1000);
return AHT10_OK;
}
static void signal_handler(int sig) {
s_running = false;
}