Arduino可以通过不同的无线模块进行无线通信,其中两个常用的模块是无线射频(RF)模块和蓝牙模块。以下是这两种模块的简要介绍以及基本的Arduino代码示例:

1. 无线射频(RF)模块

无线射频模块用于在短距离内进行无线通信。常见的RF模块包括nRF24L01和433MHz RF模块。

nRF24L01模块
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(9, 10);  // CE, CSN

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openWritingPipe(0xF0F0F0F0E1LL);  // 设置接收端地址
}

void loop() {
  const char text[] = "Hello, Arduino!";
  radio.write(&text, sizeof(text));
  delay(1000);
}

433MHz RF模块
#include <VirtualWire.h>

const int transmitPin = 12;

void setup() {
  Serial.begin(9600);
  vw_set_ptt_inverted(true);
  vw_set_tx_pin(transmitPin);
  vw_setup(2000);  // 速率: 2000 bps
}

void loop() {
  const char *msg = "Hello, Arduino!";
  vw_send((uint8_t *)msg, strlen(msg));
  vw_wait_tx();  // 等待传输完成
  delay(1000);
}

2. 蓝牙模块

蓝牙模块用于在设备之间进行无线通信,适用于短距离通信。

HC-05蓝牙模块
#include <SoftwareSerial.h>

SoftwareSerial bluetooth(2, 3);  // RX, TX

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

void loop() {
  if (bluetooth.available() > 0) {
    char receivedChar = bluetooth.read();
    Serial.print("Received: ");
    Serial.println(receivedChar);
  }
}

请注意,无线通信的稳定性和距离取决于环境和使用的模块。确保在使用之前详细阅读每个模块的规格和文档,以确保正确连接和配置。


转载请注明出处:http://www.zyzy.cn/article/detail/11011/Arduino