Wednesday, May 21, 2008

Read Temperature Measurement by serial port

The program given at the end of this web page can be used to read the temperature data from the serial port connected to the 512 Point Temperature Measurement System developed by Prof. Peter H. Anderson and his students. It has been tested on a SUN LX running Solaris 7, but it should work on other Unix implementations as well. The program will make a measurement every 900 seconds assuming that one temperature sensor is connected to take measurements. The data is then written to a file in the following format:

Run  count  temperature    serial number
1 00 12.09 106F383B 0000007A Sun Dec 10 23:48:04 2000
1 00 12.02 106F383B 0000007A Mon Dec 11 00:03:04 2000
1 00 11.96 106F383B 0000007A Mon Dec 11 00:18:04 2000

*/
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "termios.h"
#include "stdio.h"
#include "time.h"

main()
{
time_t t;
struct tm *tt;
/* FILE to log the temperature */
FILE *logfile;
int fd,res,counter;
struct termios newtio;
char buf[255];

/* Open the serial port ttya.
O_NDELAY: Don't wait for DCD signal line when opening the port.
O_RDWR: Open for read and write */
fd = open("/dev/ttya", O_RDWR | O_NDELAY);

if (fd <>

bzero(&newtio, sizeof(newtio));

/* port settings: 9600, 8bit
CREAD enables port to read data
CLOCAL prevents that we become the owner of the port and react to
control characters and are subject to hang up signals etc. */
newtio.c_cflag = B9600 | CS8 | CREAD | CLOCAL;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;

/* Set line options */
newtio.c_lflag = 0;

newtio.c_cc[VTIME] = 0; /* ignore timer */
newtio.c_cc[VMIN] = 0; /* no blocking read */

tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);

counter = 0;
/* infinite loop to measure the temperature */
while (1==1)
{
int i;
char *buf2;
logfile = fopen("temp.log","a");

/* Send a character. This will initiate the temperature reading */
i = write(fd,"a",1);
if (i == -1)
{
printf("unable to write\n");
printf("exit ...\n");
exit(-1);
}

/* Wait a short time so the PIC can finish a reading */
sleep(2);

/* Read the data sent by the PIC */
res = read(fd,buf,255);

/* Print a header every 50 output lines */
if (counter % 50 == 0)
fprintf(logfile,"Run count temperature serial number\n");

/* Print the 'run' on which this reading was performed */
fprintf(logfile," %c ",buf[0]);

/* Hexadecimal number counting the readings */
fprintf(logfile," %c%c ",buf[1],buf[2]);

/* Now print the temperature */
/* Temperature starts at position 4 and ends with space character */
i = 4;
while (buf[i] != 32)
fprintf(logfile,"%c",buf[i++]);

/* Print rest of reading, which is the serial number */
fprintf(logfile," ");
for (;i

if (res!=0)
{
/* Get the current time */
t = time(NULL);
buf2 = ctime(&t);
fprintf(logfile," %s",buf2);
}
++counter;
fclose(logfile);
sleep(898);
}
}

0 comments: