樹莓派讀取ds18吧0溫度感測器資料備份
阿新 • • 發佈:2018-12-10
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <stdlib.h> int ds18b20_get_temperature(float *temp) { int fd=-1; char buf[128]; //建立一個buf DIR* dir; //用opendir開啟資料夾,返回一個指標 struct dirent *ptr; //定義一個指向資料夾資訊結構體的指標fp, char* l ="28-"; char* m ="t="; char* q; char strtemp[20]; int found; //是否找到裝置ds18b20,找到found=1,沒找到found=0 char path[128]="/sys/bus/w1/devices/";//用來存放目錄路徑 char* point; dir =opendir(path); //開啟裝置所在路徑資料夾 /*判斷傳進來的地址是否存在,不存在返回-1*/ if(temp==NULL) { return -1; } /*判斷裝置所在路徑是否合法,合法則列印路徑,不合法則呼叫系統出錯,並返回-2 */ if (dir==NULL) { perror("oepn devicedir failure"); return -2; } else printf("\nopen succful!\n") ; /*讀取產品序列號,即:讀取28-後的字串*/ ptr=readdir(dir); if((ptr=readdir(dir)) == NULL) { perror("ptr=readdir(dir)"); return -1; } while((ptr=readdir(dir)) !=NULL) { //printf("d_name : %s\n",strstr(ptr->d_name,l)); q=strstr(ptr->d_name,l); //q的值為感測裝置檔案全名:28-041731f7c0ff if(q!=0) //如果q串不為0 { strcpy(strtemp,ptr->d_name); //把裝置名拷貝到陣列strtemp中去 printf("DEVICE:%s\n",strtemp); printf("DS18b20 SN=%s\n",q+strlen(l)); //列印去頭(28-)產品序列號 printf("path=%s\n",path); strncat(path,strtemp,sizeof(strtemp)); strncat(path,"/w1_slave",sizeof("/w1_slave")); printf("ALL_path:%s\n",path); fd=open(path,O_RDONLY); if(fd=open(path,O_RDONLY)<0) { perror("read error:"); } } } closedir(dir); //關閉該資料夾 /* if (found!=1) //如果沒在該資料夾中找到ds18b20取樣,列印錯誤資訊 { printf("not found DS18B20 in %s\n",path); return -3; } */ */ fd=open(path,O_RDONLY); if(fd=open(path,O_RDONLY)<0) { perror("open2 error:"); } else { printf("fd=%d\n",fd); } /* if read(fd,buf,sizeof(buf)); { perror("read error:"); } point=strstr(buf,"t=")+2; *temp=atof(point)/1000; return 0; }