风筝
发表于: 2020-2-5 10:47:12 | 显示全部楼层

在本篇文章中,我们将主要介绍如何建立从Arduino到另一个Arduino的串口连接。每个Arduino开发板都连接一个轻触开关和一个LED。如果按下Arduino的轻触开关,另一个Arduino的LED将点亮。


所需的材料清单

–  跳线

–  面包板

–  Arduino开发板

–  轻触开关

–  LED指示灯

–  电阻(1k欧姆)

components_arduino_seeeduino.jpg

为了演示Arduino与Arduino之间的通信,使用了两种不同类型的Arduino。第一个Arduino是Seeeduino Nano,它是与Arduino Nano兼容的变体。第二个Arduino是Seeeduino V4.2,它与Arduino Uno完全兼容(有关更多信息,请参阅https://www.seeedstudio.com/seeeduino-boards-c-987.html)。两个Arduino只会发送两个字节中的其中一个:“ 0”或“ 1”。如果发送的是“ 0”,则LED将熄灭。如果已发送“ 1”,则LED将点亮。


Arduino的连线方式:

arduino2arduino_sketch.jpg

两个Arduino设置接线方式基本相同:一个轻触开关、一个LED和一个1k电阻。轻触开关连接到GND和数字引脚2。 LED连接到GND和1k电阻。电阻连接到数字引脚3。串口连接需要三根线:GND、接收和发送。接收线连接到数字引脚10。发送线连接到数字引脚11。为了使串口行连接正常工作,将一个Arduino的接收线连接到另一个Arduino的发送线。可以不需要GND线,因为两个Arduino在使用相同的电源供电时可能共有相同的GND信号。尽管如此,为了完整起见,已将其添加到接线图中。

serial_connection_setup_arduino.jpg


源代码

首先,设置轻触开关(INPUT_PULLUP)和LED(OUTPUT)的引脚。然后,开始串口连接。在loop函数中,检查是否从串口连接接收到一个字节。数字输出设置为接收的字节:“ 0” / false熄灭LED,或“ 1” / true点亮LED。接下来,发送轻触开关的当前状态。如果未按下轻触开关,则将“ 0”发送到另一个Arduino。否则,发送“ 1”。在loop函数结束时,添加了250ms的延迟。

  1. /*
  2. * This program is part of a tutorial that shows how to communicate from an Arduino to another Arduino via a serial connection.
  3. * The status of a tact switch is sent to the other Arduino. If the switch is pressed, an LED is turned on.
  4. * This program has to be transferred to both Arduinos in order to make the application work.
  5. */
  6. #include <SoftwareSerial.h>
  7. const int IN_TACT_SWITCH = 2; // input pin for tactile switch
  8. const int OUT_LED = 3; // output pin for LED
  9. SoftwareSerial sserial(10,11); // receive pin=10, transmit pin=11
  10. void setup() {
  11.   pinMode(IN_TACT_SWITCH, INPUT_PULLUP); // set the LED pin to input pullup mode
  12.   pinMode(OUT_LED, OUTPUT); // set the LED pin to output mode
  13.   sserial.begin(9600); // start serial connection
  14. }
  15. void loop() {
  16.   // receive
  17.   if (sserial.available() > 0) {
  18.     byte incomingByte = 0;
  19.     incomingByte = sserial.read();
  20.     if (incomingByte != -1) {
  21.       Serial.print(incomingByte);
  22.       digitalWrite(OUT_LED, incomingByte); // switch LED on or off
  23.     }
  24.   }
  25.   // send
  26.   sserial.write(!digitalRead(IN_TACT_SWITCH)); // Tact switch (used in the corresponding tutorial) is inverted. Therefore, inverted status is sent to other Arduino
  27.   
  28.   delay(250); // delay required to avoid flooding the other Arduino ("DoS attack")
  29. }
复制代码

代码执行

将源代码上传到两个Arduino开发板。 如果一切均已正确执行,当按下其中一个Arduino的轻触开关时,则另一个Arduino的LED灯会亮起。

yellow_led.jpg

按下Arduino Uno的轻触开关,Arduino Nano的黄色LED亮起。

green_led.jpg

按下Arduino Nano的轻触开关,Arduino Uno的绿色LED亮起。


跳转到指定楼层
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1480



手机版|

GMT+8, 2024-4-27 08:43 , Processed in 0.035816 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表