Skip to content

Instantly share code, notes, and snippets.

@ksasao
Created April 19, 2020 15:33
Show Gist options
  • Select an option

  • Save ksasao/95c603cba021adbcf2b15c228df7a43e to your computer and use it in GitHub Desktop.

Select an option

Save ksasao/95c603cba021adbcf2b15c228df7a43e to your computer and use it in GitHub Desktop.
#include "M5Atom.h"
float temp = 0.0;
float humi = 0.0;
void setup()
{
M5.begin(true, false, true);
delay(50);
M5.dis.drawpix(0, 0xf00000);
// I2C pin setup
// 3V3, G22(GND), G19(SDA), G23(SDL)
pinMode(22,OUTPUT);
digitalWrite(22, LOW);
Wire.begin(19, 23);
}
void loop()
{
if(updateSHTC3()){
Serial.println("Temperature,Humidity");
Serial.print(temp);
Serial.print(",");
Serial.println(humi);
}else{
Serial.print("*");
}
delay(1000);
M5.update();
}
// SHTC3
bool updateSHTC3(){
Wire.beginTransmission(0x70);
if (Wire.write(0x78) != 1) {
return false;
}
if (Wire.write(0x66) != 1) {
return false;
}
if (Wire.endTransmission(true) != 0) {
return false;
}
delay(15);
int dataLength = 6;
uint8_t data[6];
Wire.requestFrom(0x70, dataLength);
// check if the same number of bytes are received that are requested.
if (Wire.available() != dataLength) {
return false;
}
// read temp & humi
for (int i = 0; i < dataLength; ++i) {
data[i] = Wire.read();
}
// crc check
if(crc8(&data[0],2) != data[2] || crc8(&data[3],2) != data[5]){
Serial.println("crc error.");
return false;
}
// convert
int t = data[0] << 8 | data[1];
int h = data[3] << 8 | data[4];
temp = -45.0 + 175.0 * t / 65535.0;
humi = 100.0 * h / 65535.0;
return true;
}
uint8_t crc8(const uint8_t *data, uint8_t len){
// adapted from SHT21 sample code from
// http://www.sensirion.com/en/products/humidity-temperature/download-center/
uint8_t crc = 0xff;
uint8_t byteCtr;
for (byteCtr = 0; byteCtr < len; ++byteCtr) {
crc ^= data[byteCtr];
for (uint8_t bit = 8; bit > 0; --bit) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0x31;
} else {
crc = (crc << 1);
}
}
}
return crc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment