Arduino示例代码讲解:Serial Call and Response in ASCII ASCII连续呼叫和回答

Arduino示例代码讲解:Serial Call and Response in ASCII ASCII连续呼叫和回答

  • Serial Call and Response in ASCII ASCII连续呼叫和回答
    • 功能概述
        • 硬件部分:
        • 软件部分:
    • 代码逐行解释
        • 定义变量
        • `setup()` 函数
        • `loop()` 函数
        • `establishContact()` 函数
    • 工作原理
    • 示例
      • 功能概述
        • 硬件部分:
        • 软件部分:
      • 代码逐行解释
        • 导入库
        • 定义变量
        • `setup()` 函数
        • `draw()` 函数
        • `serialEvent()` 函数
      • 工作原理

Serial Call and Response in ASCII ASCII连续呼叫和回答

这段代码是一个Arduino示例程序,用于通过串行通信与另一端(例如计算机或其他设备)进行交互。它在启动时发送一个特定的字符串("0,0,0"),并等待接收端的响应。一旦接收到响应,它会定期读取三个传感器的值,并将这些值以ASCII编码的字符串形式发送回去。它适用于需要通过串行通信动态读取和发送传感器数据的场景。

/*
  Serial Call and Response in ASCII
 Language: Wiring/Arduino

 This program sends an ASCII A (byte of value 65) on startup
 and repeats that until it gets some data in.
 Then it waits for a byte in the serial port, and
 sends three ASCII-encoded, comma-separated sensor values,
 truncated by a linefeed and carriage return,
 whenever it gets a byte in.

 Thanks to Greg Shakar and Scott Fitzgerald for the improvements

  The circuit:
 * potentiometers attached to analog inputs 0 and 1
 * pushbutton attached to digital I/O 2



 Created 26 Sept. 2005
 by Tom Igoe
 modified 24 Apr 2012
 by Tom Igoe and Scott Fitzgerald

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/SerialCallResponseASCII

 */

int firstSensor = 0;    // first analog sensor
int secondSensor = 0;   // second analog sensor
int thirdSensor = 0;    // digital sensor
int inByte = 0;         // incoming serial byte

void setup()
{
   
  // start serial port at 9600 bps and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
   
    ; // wait for serial port to connect. Needed for Leonardo only
  }


  pinMode(2, INPUT);   // digital sensor is on digital pin 2
  establishContact();  // send a byte to establish contact until receiver responds
}

void loop()
{
   
  // if we get a valid byte, read analog ins:
  if (Serial.available() > 0) {
   
    // get incoming byte:
    inByte = Serial.read();
    // read first analog input:
    firstSensor = analogRead(A0);
    // read second analog input:
    secondSensor = analogRead(A1);
    // read  switch, map it to 0 or 255L
    thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
    // send sensor values:
    Serial.print(firstSensor);
    Serial.print(",");
    Serial.print(secondSensor);
    Serial.print(",");
    Serial.println(thirdSensor);
  }
}

void establishContact() {
   
  while (Serial.available() <= 0) {
   
    Serial.println("0,0,0");   // send an initial string
    delay(300);
  }
}


功能概述

硬件部分:
  • 使用两个电位器分别连接到Ardu

你可能感兴趣的:(从零开始学习机器人,microsoft,嵌入式硬件,单片机,机器人,arduino,人工智能)