#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#define I2C_PORT i2c0
#define AHT10_ADDR 0x38
#define SDA_PIN 4
#define SCL_PIN 5
void aht10_init() {
uint8_t cmd[] = {0xBE, 0x08, 0x00};
i2c_write_blocking(I2C_PORT, AHT10_ADDR, cmd, 3, false);
sleep_ms(20);
}
void aht10_trigger_measurement() {
uint8_t cmd[] = {0xAC, 0x33, 0x00};
i2c_write_blocking(I2C_PORT, AHT10_ADDR, cmd, 3, false);
sleep_ms(80); // tempo de espera da medição
}
bool aht10_read(float *temperature, float *humidity) {
uint8_t data[6];
int res = i2c_read_blocking(I2C_PORT, AHT10_ADDR, data, 6, false);
if (res != 6) return false;
uint32_t hum_raw = ((uint32_t)data[1] << 12) | ((uint32_t)data[2] << 4) | ((data[3] >> 4) & 0x0F);
uint32_t temp_raw = (((uint32_t)data[3] & 0x0F) << 16) | ((uint32_t)data[4] << 8) | data[5];
*humidity = ((float)hum_raw / 1048576) * 100.0;
*temperature = ((float)temp_raw / 1048576) * 125.0 - 40.0;
return true;
}
int main() {
stdio_init_all();
i2c_init(I2C_PORT, 100 * 1000);
gpio_set_function(SDA_PIN, GPIO_FUNC_I2C);
gpio_set_function(SCL_PIN, GPIO_FUNC_I2C);
gpio_pull_up(SDA_PIN);
gpio_pull_up(SCL_PIN);
aht10_init();
sleep_ms(100);
while (true) {
aht10_trigger_measurement();
float temp, hum;
if (aht10_read(&temp, &hum)) {
printf("Temperature: %.2f °C, Humidity: %.2f %%\n", temp, hum);
} else {
printf("Failed to read AHT10\n");
}
sleep_ms(2000);
}
}