【发布时间】:2016-12-22 15:24:09
【问题描述】:
我有一个 Arduino,它通过串行端口发送一些由模拟引脚显示的信息。无论如何,在 Arduino 代码(我无法修改)中使用 Serial.write() 而不是 Serial.print() 以打印 char 的缓冲区。因此,如果我在我的 C# 软件中使用“简单”ReadLine() 读取信息,则数据难以理解。如何使用 C# 读取这些类型的数据?
这是 Arduino 代码:
#include <compat/deprecated.h>
#include <FlexiTimer2.h>
#define TIMER2VAL (1024/256) // 256Hz - frequency
volatile unsigned char myBuff[8];
volatile unsigned char c=0;
volatile unsigned int myRead=0;
volatile unsigned char mych=0;
volatile unsigned char i;
void setup() {
pinMode(9, OUTPUT);
noInterrupts();
myBuff[0] = 0xa5; //START 0
myBuff[1] = 0x5a; //START 1
myBuff[2] = 2; //myInformation
myBuff[3] = 0; //COUNTER
myBuff[4] = 0x02; //CH1 HB
myBuff[5] = 0x00; //CH1 LB
myBuff[6] = 0x02; //CH2 HB
myBuff[7] = 0x00; //CH2 LB
myBuff[8] = 0x01; //END
FlexiTimer2::set(TIMER2VAL, Timer2);
FlexiTimer2::start();
Serial.begin(57600);
interrupts();
}
void Timer2()
{
for(mych=0;mych<2;mych++){
myRead= analogRead(mych);
myBuff[4+mych] = ((unsigned char)((myRead & 0xFF00) >> 8)); // Write HB
myBuff[5+mych] = ((unsigned char)(myRead & 0x00FF)); // Write LB
}
// SEND
for(i=0;i<8;i++){
Serial.write(myBuff[i]);
}
myBuff[3]++;
}
void loop() {
__asm__ __volatile__ ("sleep");
}
这是从串口读取的C#方法
public void StartRead()
{
msp.Open(); //Open the serial port
while (!t_suspend)
{
i++;
String r = msp.ReadLine();
Console.WriteLine(i + ": " + r);
}
}
编辑:我会输出一个 string 数组,对应于 Arduino 输出的数据。如果我将所有内容记录为字节数组,则我没有关于数组开始和结束的信息。
我可以将代码编辑为:
public void StartRead()
{
msp.Open(); //Open the serial port
ASCIIEncoding ascii = new ASCIIEncoding();
while (!t_suspend)
{
i++;
int r = msp.ReadByte();
String s = ascii.getString((byte)r); // here there is an error, it require an array byte[] and not a single byte
Console.WriteLine(i + ": " + r);
}
}
考虑到起始值是每次 0xa5 并且结束是 0x01,我如何在我的 C# 软件中拥有相同的 Arduino 数组值(但作为字符串)。
【问题讨论】:
-
因为Arduino发送单字节,你必须读取单字节
ReadByte()。 -
好的,但是输出是
char。如果我使用ReadByte()它返回一个整数,我不知道如何将此整数转换为字符。 -
ReadLine()读取以换行符结尾的行。您只是发送 8 个字节,不一定都是可打印的字符,所以我不知道您为什么希望它可以理解。 -
此外,您的两个模拟通道都在写入
myBuff[5],而没有写入myBuff[7]。 -
你正在用 9 个值初始化你的缓冲区。
标签: c# serialization arduino serial-port