Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save radostin-stefanov/dc9224349fdf4623507ee5dcfcb661d3 to your computer and use it in GitHub Desktop.
Save radostin-stefanov/dc9224349fdf4623507ee5dcfcb661d3 to your computer and use it in GitHub Desktop.
Mongoose IoT HTU21D without i2c_stop
#include "HTU21D.h"
#include <stdio.h>
#include <stdbool.h>
#include "fw/src/sj_i2c.h"
#include "fw/src/sj_mongoose.h"
#define HTU21DF_I2CADDR 0x40
#define HTU21DF_READTEMP 0xE3
#define HTU21DF_READHUM 0xE5
#define HTU21DF_WRITEREG 0xE6
#define HTU21DF_READREG 0xE7
#define HTU21DF_RESET 0xFE
i2c_connection conn;
bool htu21d_init(i2c_connection c,uint8_t *stat){
conn = c;
unsigned char aucDataBuf = {0};
enum i2c_ack_type res;
aucDataBuf = HTU21DF_READREG;
res = i2c_start(conn, HTU21DF_I2CADDR, I2C_WRITE);
if (res != I2C_ACK) {
LOG(LL_INFO, ("i2c_start failed: %d", res));
i2c_stop(conn);
return false;
}
res = i2c_send_bytes(conn, &aucDataBuf, 1);
if (res != I2C_ACK) {
LOG(LL_INFO, ("i2c_send_bytes failed: %d", res));
i2c_stop(conn);
return false;
}
// i2c_stop(conn);
res = i2c_start(conn, HTU21DF_I2CADDR, I2C_READ);
if (res != I2C_ACK) {
LOG(LL_INFO, ("i2c_start 2 failed: %d", res));
i2c_stop(conn);
return false;
}
*stat = i2c_read_byte(conn, I2C_ACK);
// if (res != I2C_ACK) {
// LOG(LL_INFO, ("init status: %hhd", *stat));
// return false;
// }
i2c_stop(conn);
return (*stat == 2) ? true : false;
}
static int read_bytes(i2c_connection conn, uint8_t addr,
uint8_t reg, uint8_t *data, size_t data_len) {
enum i2c_ack_type res;
res = i2c_start(conn, addr, I2C_WRITE);
if (res != I2C_ACK) {
LOG(LL_INFO, ("error: %d", res));
return -1;
}
res = i2c_send_byte(conn, reg);
if (res != I2C_ACK) {
LOG(LL_INFO, ("error: %d", res));
return -2;
}
osi_Sleep(50);
res = i2c_start(conn, addr, I2C_READ);
if (res != I2C_ACK) {
LOG(LL_INFO, ("error reg: %d", reg));
return -3;
}
LOG(LL_INFO, ("error i2c_read_bytes"));
i2c_read_bytes(conn, data_len, data, I2C_ACK);
LOG(LL_INFO, ("i2c_read_bytes"));
return 0;
}
double htu21d_readTemperature(uint8_t addr) {
unsigned char reg = HTU21DF_READTEMP;
unsigned char val[3] = {0, 0, 0};
int status = read_bytes(conn, addr, reg, val, 3);
i2c_stop(conn);
LOG(LL_INFO, ("bytes from sensor: %02x %02x %02x", val[0], val[1], val[2]))
if (status < 0) return -1000;
uint16_t t = val[1];
t |= (val[0] << 8);
double temp = t;
temp *= 175.72;
temp /= 65536;
temp -= 46.85;
return temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment