用C#

时间:2016-12-22 15:24:10

标签: c# serialization arduino serial-port

我有一个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);
        }
    }

编辑:我将输出一个与{Arduino输出数据相对应的string数组。如果我将所有内容记录为字节数组,我没有关于数组的开始和结束的信息。 我可以将代码编辑为:

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

我在C#软件中如何拥有相同的Arduino数组值(但作为一个字符串),考虑到起始值是每次0xa5而结束是0x01。

1 个答案:

答案 0 :(得分:1)

Arduino发送几个字节的电报。您可以将其读入字节数组:

byte[] telegram = byte[msp.BytesToRead];
msp.Read(telegram, 0, msp.BytesToRead);

要从字节数组中获取数据,您必须解释字节(参见下面的示例)。 当然,您可以从Telegram类的属性创建一个字符串:

    class Telegram {
    public Telegram(byte[] tel) {
        // Check start bytes ( 0xa5, 0x5a );
        Info = tel[2];
        Counter = tel[3];
        Channel1 = BitConverter.ToInt16(new byte[] { tel[5], tel[4] }, 0); // Switch lo/hi byte
        Channel2 = BitConverter.ToInt16(new byte[] { tel[7], tel[6] }, 0);// Switch lo/hi byte
        // check tel[8] == 1 for end of telegram
     }    
     public int Info { get; private set; }
     public int Counter { get; private set; }
     public int Channel1 { get; private set; }
     public int Channel2 { get; private set; }
}