Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <signal.h>
#include <errno.h>
static sig_atomic_t end = 0;
static void sighandler(int signo)
{
end = 1;
}
int main(int argc, char** argv)
{
struct termios tio;
int tty_fd;
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_handler = sighandler;
sigaction(SIGINT, &sa, NULL);
sigaction(SIGQUIT, &sa, NULL);
sigaction(SIGTERM, &sa, NULL);
printf("RS232\n\n");
memset(&tio, 0, sizeof(tio));
tio.c_iflag = 0;
tio.c_oflag = 0;
tio.c_cflag = B9600 | CS8 | PARODD | CREAD | CLOCAL;
tio.c_lflag = 0;
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 5;
printf("Open device\n");
tty_fd = open("/dev/ttyAMA0",O_RDWR | O_NONBLOCK);
if (-1 == tty_fd)
{
printf ("unableto open device, error '%s' (%d)\n",
strerror(errno), errno);
return EXIT_FAILURE;
}
cfsetospeed(&tio, B9600);
cfsetispeed(&tio, B9600);
tcsetattr(tty_fd, TCSANOW, &tio);
//_____________________________________________________________________________________
int choose = 0;
do
{
printf("1. Temperature\n");
printf("2. Humidity\n");
printf("3. CO2\n");
printf("4. Exit\n");
scanf("%d", &choose);
printf("\n");
switch (choose)
{
case 1: // Temperature
{
char command1[] = "T\r\n";
float temp;
char *p1;
unsigned char buftemp[8];
char buftemp2[5];
write(tty_fd, &command1, 5);
while (!(read(tty_fd, &buftemp, 8) && buftemp[0]>0))
{
}
memmove (buftemp2, buftemp + 3, 5);
temp = strtof(buftemp2, &p1);
temp = temp - 1000;
temp = temp / 10;
printf("Temperature: %.2f C\n", temp);
break;
}
case 2: // Humidity
{
char command2[] = "H\r\n";
float humi;
char *p2;
unsigned char bufhumi[8];
char bufhumi2[5];
write(tty_fd, &command2, 5);
while (!(read(tty_fd, &bufhumi, 8) && bufhumi[0]>0))
{
}
memmove (bufhumi2, bufhumi + 3, 5);
humi = strtof(bufhumi2, &p2);
humi = humi / 10;
printf("Humidity: %.2f %\n", humi);
break;
}
case 3: // Carbondioxide
{
char command3[] = "Z\r\n";
float carb;
char *p3;
unsigned char bufcarb[8];
char bufcarb2[5];
write(tty_fd, &command3, 5);
while (!(read(tty_fd, &bufcarb, 8) && bufcarb[0]>0))
{
}
memmove (bufcarb2, bufcarb + 3, 5);
carb = strtof(bufcarb2, &p3);
printf("Carbondioxide: %.2f ppm\n", carb);
carb = carb / 10000;
printf("Carbondioxide: %.2f %\n", carb);
break;
}
}
}
while (choose !=4);
close(tty_fd);
return 0;
}