добавил ещё несколько примеров для I2C

This commit is contained in:
Ogneyar committed 2024-08-21 15:49:49 +03:00
1 parent 996e316403
commit 045e4c6c78
5 files changed
+157 -3

No files matched your search

@@ -0,0 +1,59 @@
#include <Arduino.h>
#include <Wire.h>
#include "AHT10.h"
static const uint8_t AHT10_ADDR = 0x38;
bool AHT10::begin() {
Wire.beginTransmission(AHT10_ADDR);
Wire.write(0xE1);
Wire.write(0x08);
Wire.write(0x00);
return Wire.endTransmission() == 0;
}
bool AHT10::reset() {
Wire.beginTransmission(AHT10_ADDR);
Wire.write(0xBA);
return Wire.endTransmission() == 0;
}
bool AHT10::measure(float *temp, float *hum) {
uint8_t data[6];
uint32_t d;
Wire.beginTransmission(AHT10_ADDR);
Wire.write(0xAC);
Wire.write(0x33);
Wire.write(0x00);
if (Wire.endTransmission())
return false;
delay(75);
if ((Wire.requestFrom(AHT10_ADDR, (uint8_t)6) != 6) || (Wire.readBytes(data, 6) != 6))
return false;
if (temp) {
d = ((uint32_t)(data[3] & 0x0F) << 16) | ((uint32_t)data[4] << 8) | data[5];
*temp = (float)d * 200 / 1048576 - 50;
}
if (hum) {
d = ((uint32_t)data[1] << 12) | ((uint32_t)data[2] << 4) | (data[3] >> 4);
*hum = (float)d * 100 / 1048576;
}
return true;
}
float AHT10::getTemperature() {
float result;
if (! measure(&result, NULL))
result = NAN;
return result;
}
float AHT10::getHumidity() {
float result;
if (! measure(NULL, &result))
result = NAN;
return result;
}
@@ -0,0 +1,15 @@
#ifndef __AHT10_H
#define __AHT10_H
#include <Wire.h>
class AHT10 {
public:
static bool begin();
static bool reset();
static bool measure(float *temp, float *hum);
static float getTemperature();
static float getHumidity();
};
#endif
@@ -0,0 +1,32 @@
/*
The AHT10 temperature and humidity sensor connected to I2C is used for this test.
*/
#include "AHT10.h"
void setup() {
Serial.begin(115200);
Serial.println();
Wire.begin();
if (! AHT10::begin()) {
Serial.println(F("AHT10 not detected!"));
Serial.flush();
}
}
void loop() {
float temp, hum;
delay(2000);
if (AHT10::measure(&temp, &hum)) {
Serial.print(F("Temperature is "));
Serial.print(temp);
Serial.print(F(" C, humidity is "));
Serial.print(hum);
Serial.println('%');
} else {
Serial.println(F("AHT10 read error!"));
}
}