c - 写入后从串行端口读取

标签 c serial-port arduino

我正在开发一个项目,该项目让我的计算机与 arduino 板通信,该板读取传感器输出并仅在收到“t”时将其放在串行端口上。如下所示的 arduino 代码正在运行。

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);
    }
  }
}

当我试图读取 arduino 放在串行端口上的内容时,我的问题出在 C 代码中。我的 C 代码是:
#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\n");
            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 \n",w);
        fprintf(stderr, "fd = %d.\n", fd);
        sleep(10);
        int n=read(fd,tempbuf,5);
        printf("%d,%s \n",n,strerror(errno));
        if(n>0){
            float temp=atof(tempbuf);
            printf("Temperature is: %f Celsius\n", temp);
            if (temp>27){
                return STATE_CRITICAL;
            }else{
                printf("The temperature is %f Celsius and checked 10 seconds ago\n",temp);
                return STATE_OK;
            }
        }
    }
    close(fd);
    return 0;
}

n 总是 = 0,我不知道是什么问题。
提前致谢。

最佳答案

i can't figure out what is the problem



一个大问题是“计算机”上运行的C程序不完整。

Arduino 的程序执行至少波特率的串行端口设置(以及默认情况下可能执行的任何其他操作)。
但是“计算机的”C 程序从不正确配置串口 .串行端口将使用之前配置的任何属性(波特率、数据长度、奇偶校验设置、规范与原始模式),这将导致不可预测的读取和写入。 (环回测试可能会产生假阳性结果。)

使用 POSIX Serial Port guidethis answer对于示例代码。

对于规范模式,您可能需要添加如下代码(假设为 8N1):
    rc = tcgetattr(fd, &tty);
    if (rc < 0) {
        /* handle error */
    }
    savetty = tty;    /* preserve original settings for restoration */

    spd = B9600;
    cfsetospeed(&tty, (speed_t)spd);
    cfsetispeed(&tty, (speed_t)spd);

    tty.c_cflag &= ~PARENB
    tty.c_cflag &= ~CSTOPB
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;

    tty.c_cflag &= ~CRTSCTS;    /* no HW flow control? */
    tty.c_cflag |= CLOCAL | CREAD;

    tty.c_iflag |= IGNPAR | IGNCR;
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    tty.c_lflag |= ICANON;
    tty.c_oflag &= ~OPOST;

    rc = tcsetattr(fd, TCSANOW, &tty);
    if (rc < 0) {
        /* handle error */
    }

您可能应该删除该行
fcntl(fd, F_SETFL, FNDELAY);  

以及 O_NONBLOCK open() 中的选项打电话。

关于c - 写入后从串行端口读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675127/

相关文章:

c - 为什么我总是收到无效的反馈?

C、无法通过取消引用检索变量值,未知段错误

c - 如何从非文本文件中读取、修改结构?

c - vxworks设置串口波特率失败

c++ - 使用 C++ 模板作为返回类型/变量名

c - 轻松访问多个结构数组

c - 为什么 free 函数在我的代码中不起作用?

serial-port - 无法通过 AT 命令获取 IMSI 和 IMEI

air - 让我的串行端口与我的 Adob​​e Air 应用程序通信

c# - asp C# 如何在同一个程序中通过串口读取和发送数据