當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Arduino Serial.available()用法及代碼示例

說明

獲取可用於從串行端口讀取的字節數(字符)。這是已經到達並存儲在串行接收緩衝區(包含 64 個字節)中的數據。

Serial.available() 繼承自 Stream 實用程序類。

用法

Serial.available()

參數

Serial:串口對象。請參閱 Serial main page 上每個板的可用串行端口列表。

返回

可讀取的字節數。

示例代碼

下麵的代碼返回一個通過串口接收到的字符。

int incomingByte = 0; // for incoming serial data

void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // reply only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print("I received: ");
    Serial.println(incomingByte, DEC);
  }
}

Arduino 超級示例:
此代碼將 Arduino Mega 的一個串行端口接收到的數據發送到另一個。例如,這可用於通過 Arduino 板將串行設備連接到計算機。

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

void loop() {
  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial1.print(inByte, DEC);
  }
  // read from port 1, send to port 0:
  if (Serial1.available()) {
    int inByte = Serial1.read();
    Serial.print(inByte, DEC);
  }
}

相關用法


注:本文由純淨天空篩選整理自arduino.cc大神的英文原創作品 Serial.available()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。