Arduino 串口篇 Arduino发送二进制 send binary via RS232-to-USB to PC

有用的链接在这里:http://hi.baidu.com/mizuda/item/06b7fdc1d0e45a0ec710b2dd

更加详细的内容请查阅Arduino官方:http://arduino.cc/en/Serial/Write

代码如下:

/*
*SendBinary sketch
*Send a header followed by two random integer values as binary data.
*/
int intValue; // an short integer value (16 bits = 2bytes) intvalue must be less than 0xffff(65535 = 255*256+255)
void setup(){
  Serial.begin(9600);
}
void loop(){
  Serial.print('H'); //send a header character
   intValue = random(591); //generate a random number between 0 and 590
  Serial.write(lowByte(intValue)); //send the low byte
  Serial.write(highByte(intValue)); //send the high byte
  
    // send another random integer
  intValue = random(599); // generate a random number between 0 and 599
  // send the two bytes that comprise an integer
  Serial.write(lowByte(intValue));  // send the low byte
  Serial.write(highByte(intValue)); // send the high byte
  //发送单字节很简单,使用Serial.write(byteVal);
  //发送整数,需发低字节 和高字节来组成整数,value= high*256+low

  delay(100000);
}

通过上面,我们可以看到

每次发送的都是头为H的二进制内容。

正如上面注释缩写,发送低位字节,发送高位字节。

//发送单字节很简单,使用Serial.write(byteVal);
  //发送整数,需发低字节 和高字节来组成整数,value= high*256+low

二进制是一些简单的内容。这些二进制文件也许是遵循一定规律的文档。在上位机上,我们可以编写软件来从串口获得这些来自下位机的二进制文件。通过分析矫正位,头文件等可以从中提取到单片机想传来的有用的信息。这些信息是经过一定协议的。用起来会比较简单。

我们可以看到上图中有些内容可以显示出来,而有些却不能,这是因为不是任何二进制内容都可以翻译成明文表的。ASCII表就那点,符号也不够分配的。

原文地址:https://www.cnblogs.com/spaceship9/p/3239727.html