当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Arduino Serial.write()用法及代码示例


说明

将二进制数据写入串行端口。该数据作为一个字节或一系列字节发送;要发送代表数字的字符,请改用print() 函数。

用法

Serial.write(val)
Serial.write(str)
Serial.write(buf, len)

参数

Serial: 串口对象。请参阅每个板上的可用串行端口列表序列主页面.
val:作为单个字节发送的值。
str:作为一系列字节发送的字符串。
buf:作为一系列字节发送的数组。
len:要从数组发送的字节数。

返回

write() 将返回写入的字节数,尽管读取该数字是可选的。数据类型:size_t

示例代码

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.write(45); // send a byte with the value 45

  int bytesSent = Serial.write("hello");  //send the string "hello" and return the length of the string.
}

注意事项和警告

从 Arduino IDE 1.0 开始,串行传输是异步的。如果传输缓冲区中有足够的空白空间,Serial.write() 将在任何字符通过串行传输之前返回。如果发送缓冲区已满,则Serial.write() 将阻塞,直到缓冲区中有足够的空间。为避免阻塞对 Serial.write() 的调用,您可以首先使用 availableForWrite() 检查传输缓冲区中的可用空间量。

相关用法


注:本文由纯净天空筛选整理自arduino.cc大神的英文原创作品 Serial.write()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。