<div dir="ltr"><div><div><div>I'm not sure if the exercise is to learn C or to read the device.<br><br></div>If it is simply to read the device,<br><br></div>tail -f <device> should work fine.<br><br></div>Bill<br>
<br></div><div class="gmail_extra"><br><br><div class="gmail_quote">On Thu, Jan 16, 2014 at 7:55 PM, Jamon Camisso <span dir="ltr"><<a href="mailto:jamon.camisso-H217xnMUJC0sA/PxXw9srA@public.gmane.org" target="_blank">jamon.camisso@utoronto.ca</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">So I've managed to get a temperature sensor wired up and outputting data<br>
from my Raspberry Pi. I can poll the /sys/bus/w1/devices file for the<br>
sensor and see output like the following:<br>
<br>
1a 01 4b 46 7f ff 06 10 ea : crc=ea YES<br>
1a 01 4b 46 7f ff 06 10 ea t=17625<br>
<br>
I've given myself the exercise of learning some C and so far I've done a<br>
reasonable job with a C function to read it and get the t=17625 value as<br>
a temperature, the function's output: temp is : 17.7C<br>
<br>
const char file[] = "/sys/bus/w1/devices/device-id-here/w1_slave";<br>
float get_temp() {<br>
  FILE *fp;<br>
  char line[40], temp_raw[5];<br>
  fp = fopen(file, "r");<br>
  if (fp == NULL) {<br>
    fprintf(stderr, "File %s not found\n", file);<br>
    exit(1);<br>
  }<br>
  else {<br>
    while (fgets(line, 40, fp) != NULL) {<br>
      // pass, just want the last line of the file<br>
    }<br>
    fclose(fp);<br>
  }<br>
  int len = strlen(line);<br>
  strncpy(temp_raw, line+len-6, 6);<br>
  float temp_f = floorf((atof(temp_raw)/1000 + 0.05)*100)/100;<br>
  printf("temp is : %.1f\n", temp_f );<br>
  return temp_f;<br>
}<br>
<br>
So ok, great, job done right? Well I don't think so. I think I'm going<br>
about this in a very non-reusable manner. I can't tell if the device is<br>
returning lines one at a time to stdout first of all, hence the while loop.<br>
<br>
Question 1) Would fread( )or fscanf() be better here? Can I skip the<br>
while loop? What if this was 500,000 lines long? Any better way? I was<br>
thinking of looking at how head and tail in coreutils handle this but<br>
figured to ask here first.<br>
<br>
Second, I'm not sure how to extract the t=17625 value - it is always at<br>
position len-6 (\0 line termination needs to be accounted for). It is<br>
always the same length which is great. But:<br>
<br>
Question 2) Is there a better way than strncpy?<br>
<br>
Thanks for any tips,<br>
<br>
Jamon<br>
--<br>
The Toronto Linux Users Group.      Meetings: <a href="http://gtalug.org/" target="_blank">http://gtalug.org/</a><br>
TLUG requests: Linux topics, No HTML, wrap text below 80 columns<br>
How to UNSUBSCRIBE: <a href="http://gtalug.org/wiki/Mailing_lists" target="_blank">http://gtalug.org/wiki/Mailing_lists</a><br>
</blockquote></div><br></div>