/*  Copied from     24 May 2017
http://raspberrypihobbyist.blogspot.com/2015/02/using-am2315-temperaturehumidity-sensor.html

example code to test am2315 (temp/humid sensor) on i2c bus
 ted.b.hale@gmail.com

*/
 
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <wiringPi.h>
#include <wiringPiI2C.h>
 
int main(int argc, char *argv[])
{
 int n, fd;
  
// read request - 3 is the read register command
// 0 is the address to start at
// 4 is the number of bytes to read
 unsigned char read_request[3] = {3, 0, 4};
  
// buffer for the response: command byte, length byte, 4 bytes data, 2 bytes of checksum
 unsigned char response[8];
  
// dummy data sent to wake up device
 unsigned char dummy[1] = {0};
  
// the final results
 float humidity, celsius;

// open the am2315 device using WiringPi
// 0x5C is bus address of am2315
// fd is the "file descriptor" used in later read and writes
 fd = wiringPiI2CSetup(0x5c); 
 if (fd==-1)
 {
  printf("wiringPiI2CSetup failed\n");
  return 0;
 }
  
// run until killed with Ctrl-C
 while (1)
 {
  // send some data to wake it up
  n = write(fd, dummy, 1);
  n = write(fd, dummy, 1);
   
  // send the read request
  n = write(fd, read_request, 3);
  printf("write returned %d bytes\n",n);
   
  // very short delay to allow device to do data conversion
  delay(2);
   
  // read the reaponse
  n = read(fd, response, 8);
  printf("read returned %d bytes\n",n);

  // sanity check on data returned
  // first byte should echo the read requst byte (3)
  // second byte should indicate 4 bytes of data returned
  // I don't bother verifying the checksum
  if ((response[0]!=3) || (response[1]!=4))
  {
   printf("i2c response invalid\n");
   for (n=0; n<8; n++)
    printf("%02x ",response[n]);
  }
  else
  {
   // (high byte * 256) + low byte
   // divide by 10
   humidity = (256*response[2] + response[3])/10.0;
 
   // same as above but mask out the sign bit on the high byte
   celsius = (256 * (response[4] & 0x7F) + response[5]) / 10.0;
   // make result negative if the sign bit is set
   if ((response[4]&0x80)!=0)
    celsius *= -1.0;
 
   printf("   humidity = %5.1f%%\n",humidity);
   printf("temperature = %5.1f\n",celsius);
  }
  printf("\n\n\n");
 
  // wait two second and loop again
  delay(2000);
 }
   
 return 0;
}
