/* * bh1750fvi.c * * Copyright (C) 2012 Computex Co.,Ltd. * * Sample to test CM-3G main board using CM-3G CHECK BOARD */ #include #include #include #include #include #include #include #define I2C_DEVICE "/dev/i2c-3" #define DEV_ADDRESS 0x23 void usage(char *app_name) { printf("%s - Displays the H-Resolution Mode, H-Resolution Mode2 and L-Resolution mode values for BH1750FVI sensor\n", app_name); printf("Usage: %s -d [device path]\n", app_name); printf("\t\t-d - i2c device path (Default: "I2C_DEVICE")\n"); printf("Eg: %s\n", app_name); exit(0); } /**************************************************************** * Main ****************************************************************/ int main(int argc, char* argv[]) { unsigned char buf[10]; int d; char shortoptions[] = "d:h"; char input_device[16]; float hres, hres2, lres; input_device[0] = 0; for (;;) { d = getopt_long(argc, argv, shortoptions, (void *)NULL, &index); if (-1 == d) { break; } switch (d) { case 'd': strcpy(input_device, optarg); break; default: usage(argv[0]); } } if(input_device[0] == 0) strcpy(input_device, I2C_DEVICE); int file = open(input_device, O_RDWR); if(file < 0) { printf("Error: "I2C_DEVICE " open failed\n"); exit(1); } if(ioctl(file, I2C_SLAVE, DEV_ADDRESS) < 0) { printf("Error: %s setting device address to 0x%xfailed\n", input_device, DEV_ADDRESS); goto out; } /* power on the device */ buf[0] = 0x01; if (write(file, buf,1) != 1) { err_write: printf("Failed to write to i2c bus\n"); goto out; } /* reset the device */ buf[0] = 0x07; if (write(file, buf,1) != 1) { goto err_write; } printf("H-RES H-RES2 L-RES\n"); /* measure one time values */ while(1) { /* power on the device */ buf[0] = 0x01; if (write(file, buf,1) != 1) { goto err_write; } /* H-Resolution Mode */ buf[0] = 0x20; if (write(file, buf,1) != 1) { goto err_write; } usleep(120000); /* 120 ms wait */ buf[0] = 0x0; if (read(file, buf, 2) != 2) { printf("Failed to read from i2c bus\n"); goto out; } hres = ((float)(buf[1] | (buf[0]<<8)))/1.2; /* power on the device */ buf[0] = 0x01; if (write(file, buf,1) != 1) { goto err_write; } /* H-Resolution Mode2 */ buf[0] = 0x21; if (write(file, buf,1) != 1) { goto err_write; } usleep(120000); /* 120 ms wait */ buf[0] = 0x0; if (read(file, buf, 2) != 2) { printf("Failed to read from the i2c bus.\n"); goto out; } hres2 = ((float)(buf[1] | (buf[0]<<8)))/1.2; /* power on the device */ buf[0] = 0x01; if (write(file, buf,1) != 1) { goto err_write; } /* L-Resolution Mode */ buf[0] = 0x23; if (write(file, buf,1) != 1) { goto err_write; } usleep(120000); /* 120 ms wait */ buf[0] = 0x0; if (read(file, buf, 2) != 2) { printf("Failed to read from the i2c bus.\n"); goto out; } lres = ((float)(buf[1] | (buf[0]<<8)))/1.2; printf("%-11.3f %-11.3f %-11.3f\n", hres, hres2, lres); } out: close(file); return 0; }