使用arduino读取ASCII码
这是我的第一篇文章,我知道这个主题可能非常简单或明显,但我无法弄清楚如何解决它。使用arduino读取ASCII码
我有一个来自jyetech的电容表,有一个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);
}}
您必须使用两个串行端口,一个用于与PC(通常的串行对象)对话,另一个用于与仪器对话。 如果您有一个只有一个硬件串行端口的Arduino UNO,则必须使用软件串行库。兆丰板有4而不是硬件串行端口,都可以通过储存卡,在接口Serial1对象,Serial2等
顺便说一句,只是注意到了一个非常类似的问题被问前一段时间:
所以我需要用软件串口读入输入数据并用普通串口发送数据? – user2350908 2013-05-10 18:09:54
这将是最简单的解决方案,恕我直言。 – 2013-05-11 13:53:28
为什么你在写/检查“RCV”/“RDY”/“ACK”吗?您链接到的手册根本没有提及这些代码 - 仅仅是一个序列,时间戳和阅读。 – GregHNZ 2013-05-05 21:55:44
@GregHNZ它只是一个代码,我发现读取串行输入。我尝试了其他简单的,但这个给我一个更清洁的输出。我正在做这样的事情。 23513 10112.06r) 23514 10112.47 0r) 23515 10112.89 00I) 23516 101L&ir) 23517 1011&ér) – user2350908 2013-05-05 22:32:58