I am working on a project that has my computer communicating with an arduino board that reads the sensor output and put it on the serial port only if a "t" was received.the arduino code as shown below is working.
const int inputPin = 0;
void setup(){
Serial.begin(9600);
pinMode(13, OUTPUT);}
void loop(){
if (Serial.available() > 0){
char c=Serial.read();
if(c=='t'){
int value = analogRead(inputPin);
float celsius = (5.0 * value * 100.0)/1024.0;
Serial.println(celsius);
}
}
}
My problem is in the C code when Im trying to read what arduino puts on the serial port. My C code is:
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
int STATE_OK=0;
int STATE_WARNING=1;
int STATE_CRITICAL=2;
char tempbuf[10];
int fd=open("/dev/ttyACM0",O_RDWR | O_NOCTTY | O_NONBLOCK);
if(fd == -1){
printf("Unable to open /dev/ttyACM0
");
return STATE_WARNING;
} else {
fcntl(fd, F_SETFL, FNDELAY);
int w=write(fd, "t", 1);
printf("The number of bytes written to the serial port is %d
",w);
fprintf(stderr, "fd = %d.
", fd);
sleep(10);
int n=read(fd,tempbuf,5);
printf("%d,%s
",n,strerror(errno));
if(n>0){
float temp=atof(tempbuf);
printf("Temperature is: %f Celsius
", temp);
if (temp>27){
return STATE_CRITICAL;
}else{
printf("The temperature is %f Celsius and checked 10 seconds ago
",temp);
return STATE_OK;
}
}
}
close(fd);
return 0;
}
n is always=0 and i can't figure out what is the problem.
Thanks in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…