使用arduino进行ASCII读取

时间:2013-05-05 21:03:03

标签: serial-port arduino ascii

这是我的第一篇文章,我知道这个主题可能非常简单或明显,但我无法弄清楚如何解决它。

我有一个来自jyetech wiuch的电容表声称有一个8-N-1串行输出,这里是link to the manual。我只想用我的Arduino Uno阅读输出,有人可以帮助我吗?这是我所做的代码,我得到了一些真实数据,但也有一些奇怪的字符。

#include <stdio.h>

void setup() {
Serial.begin(38400);

Serial.println("OK");
}

char command[1024];
char commandBuffer[128];
int commandBufferSize = 0;

void readCommandBuffer(int bytesToRead) {
int i = 0;
char c = 0;
while (i < 128 && (i < bytesToRead || bytesToRead <= 0)) {
    while (!Serial.available())
        ;
    c = Serial.read();
    if (c == '\r' || c == '\n') {
        break;
    }
    commandBuffer[i] = c;
    i++;
}
commandBufferSize = i;
}

void readCommand() {
command[0] = '\0';
readCommandBuffer(0);
if (strncmp(commandBuffer, "RCV", 3) == 0) {
    commandBuffer[commandBufferSize] = '\0';
    int expectedSize = atoi(commandBuffer + 4);
    if (expectedSize <= 0 || expectedSize > 1024) {
        return;
    }
    Serial.println("RDY");
    int bytesRead = 0;
    while (bytesRead < expectedSize) {
        readCommandBuffer(expectedSize - bytesRead);
        memcpy(command + bytesRead, commandBuffer, commandBufferSize);
        bytesRead += commandBufferSize;
        Serial.print("ACK ");
        Serial.println(commandBufferSize);
    }
    command[bytesRead] = '\0';
} else {
    memcpy(command, commandBuffer, commandBufferSize);
    command[commandBufferSize] = '\0';
}
}

void loop() {
if (Serial.available()) {
    readCommand();
    // "command" now contains the full command
    Serial.println(command);
}}

1 个答案:

答案 0 :(得分:0)

您必须使用两个串行端口,一个用于与PC通信(通常的串行对象),另一个用于与仪器通信。 如果你有一个只有一个硬件串口的Arduino UNO,你必须使用软件串口库。超级主板有4个硬件串口,可通过内置对象Serial1,Serial2等获得。

顺便说一句,刚才注意到一个非常类似的问题:#/ p>

Serial Data communication Arduino