Skip to content

Instantly share code, notes, and snippets.

@MattBlack85
Created March 13, 2017 12:42
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 MattBlack85/2a30239904deeb6c7273090b89285e12 to your computer and use it in GitHub Desktop.
Save MattBlack85/2a30239904deeb6c7273090b89285e12 to your computer and use it in GitHub Desktop.
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
int main(void) {
DIR *main_dir;
FILE *temp_file;
struct dirent *read_dir;
char devices_folder[20] = "/sys/bus/w1/devices";
char dev_folder[16];
char full_path[128];
char buf[256];
size_t nread;
char tmpData[6];
main_dir = opendir(devices_folder);
if (main_dir == NULL) {
printf("Folder %s not found\n", devices_folder);
return 1;
}
while ((read_dir = readdir(main_dir))) {
// Look for device folders, start with 28-
if (strstr(read_dir->d_name, "28-")) {
strcpy(dev_folder, read_dir->d_name);
}
}
closedir(main_dir);
// Build the full path to the file where the read will be written
sprintf(full_path, "%s/%s/w1_slave", devices_folder, dev_folder);
while(1) {
sleep(1);
temp_file = fopen(full_path, "r");
if(temp_file == NULL) {
printf("Couldn't open the w1 device.\n");
return 1;
}
while((nread = fread(buf, 1, 256, temp_file))) {
strncpy(tmpData, strstr(buf, "t=") + 2, 5);
printf("T: %s", tmpData);
float tempC = strtof(tmpData, NULL);
printf("Temp: %.3f C ", tempC / 1000);
printf("%.3f F\n\n", (tempC / 1000) * 9 / 5 + 32);
}
close(temp_file);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment