Skip to content

Instantly share code, notes, and snippets.

@tsyd
Created July 26, 2017 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsyd/f48e933a21fb40b9f9eea28118f54e01 to your computer and use it in GitHub Desktop.
Save tsyd/f48e933a21fb40b9f9eea28118f54e01 to your computer and use it in GitHub Desktop.
Simple C program to read HIH8120 series humidity and temperature sensors over I2C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <math.h>
int main()
{
int file;
char *filename = "/dev/i2c-1";
if ((file = open(filename, O_RDWR)) < 0) {
printf("Failed to open the i2c bus\n");
exit(1);
}
uint8_t addr = 0b00100111;
if (ioctl(file, I2C_SLAVE, addr) < 0) {
printf("Failed to acquire bus access to slave\n");
exit(1);
}
uint8_t out[1] = { 0b00000000 };
if (write(file, out, 1) != 1) {
printf("Failed to write: %u\n", errno);
exit(1);
}
sleep(1);
uint8_t in[4] = { 0 };
if (read(file, in, 4) != 4) {
printf("Failed to read: %u\n", errno);
exit(1);
}
uint32_t status = in[0] & 0b11000000 >> 6;
uint32_t humidity = ((in[0] & 0b00111111) << 8) | in[1];
uint32_t temperature = (in[2] << 6) | (in[3] & 0b11111100);
printf("%.1f,", roundf((humidity / (float) 16382 * 100) * 2.0f) / 2.0f);
printf("%.1f\n", roundf(((temperature / (float) 16382) * 165 - 40) * 2.0f) / 2.0f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment