Originally posted by me on May 9, 2017
Again, very simple code to read from a device, and put that read information out to stdout. In this case, reading from a 1-wire DS18B20 sensor. The pin used is unimportant, so long as that pin is configurable as gpio, and is not already in use by another device. 1-wire is one of the simpler sensor types connectable to a beaglebone, and can be plugged directly into one of the two headers on the beaglebone using jumper wires. You need power(3v3), ground, and a gpio pin connected. See the DS18B20 datasheet to determine which pin on the sensor is used for what purpose. As for setup in Linux for this sensor. You can search the web for a guide as to how to do this manually from the cmdline, or you can use a device tree overlay. I used this overlay file as a template, then modified the pin information to reflect the pin I needed to use. https://github.com/beagleboard/bb.org-overlays/blob/master/src/arm/BB-W1-P9.12-00A0.dts
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int read_DS18B20(void)
{
DIR *dir;
struct dirent *dirent;
char dev[16];
char devPath[128];
char buf[80];
char tmpData[6];
char path[] = "/sys/bus/w1/devices";
ssize_t nread;
dir = opendir(path);
if(dir == NULL){
perror("/sys/bus/w1/devices");
exit(errno);
}
while((dirent = readdir(dir))){
if (dirent->d_type == DT_LNK && strstr(dirent->d_name, "28-") != NULL){
strcpy(dev, dirent->d_name);
}
}
(void)closedir(dir);
sprintf(devPath, "%s/%s/w1_slave", path, dev);
int fd = open(devPath, O_RDONLY);
if (fd == -1){
perror ("/sys/bus/w1/devices/28-*/w1_slave");
exit(errno);
}
long tempC = 0;
nread = read(fd, buf, 80);
if(nread > 0){
strncpy(tmpData, strstr(buf, "t=") + 2, 5);
tempC = strtol(tmpData, NULL, 10);
}
close(fd);
return tempC;
}
int main (void)
{
float temp = read_DS18B20() * (1 / 1000.0);
printf("Temp: %.3f C \n", temp);
return 0;
}
Output:
root@wgd:~/# gcc -Wall -o read_ds18b20 read_ds18b20.c
root@wgd:~/# ./read_ds18b20
Temp: 25.312 C