Serial Call and Response (handshaking) —— Arduino Documentation#
Serial Call and Response (handshaking) —— Arduino Documentation
原来的例子用到了传感器。如果仅仅只关注通信的握后,可以改造一下,改为只在串口发送和接收数据。
设计题: 模拟停等协议或 TCP 建立连接的协议,实现串口间的大量数据传输。
原始代码:
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:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port 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(); // 1 ???
// read first analog input, divide by 4 to make the range 0-255:
firstSensor = analogRead(A0) / 4;
// delay 10ms to let the ADC recover:
delay(10);
// read second analog input, divide by 4 to make the range 0-255:
secondSensor = analogRead(1) / 4;
// read switch, map it to 0 or 255L
thirdSensor = map(digitalRead(2), 0, 1, 0, 255);
// send sensor values:
Serial.write(firstSensor);
Serial.write(secondSensor);
Serial.write(thirdSensor);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.print('A'); // send a capital A
delay(300);
}
}
代码的握手看起来有些简单。
inByte = Serial.read()
所读到的值后面没有用到啊?原始代码中还有 processing 代码,用到了 read 的值,且握手更复杂。