Arduino一些有用的代码

玩了好几年的Arduino,走过一些坑,收集了一些有用的辅助代码。

查找i2c设备地址代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <Wire.h>  

void setup(){
Wire.begin();
Serial.begin(9600);
Serial.println("\nI2C Scanner");
}
void loop(){
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for (address = 1; address < 127; address++ ){
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0){
Serial.print("I2C device found at address 0x");
if (address < 16)
Serial.print("0");
Serial.print(address, HEX);
Serial.println(" !");
nDevices++;
}else if (error == 4){
Serial.print("Unknow error at address 0x");
if (address < 16)
Serial.print("0");
Serial.println(address, HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(5000); // wait 5 seconds for next scan
}

有时候买来的模块资料提供的i2c地址不正确,导致模块不能正常使用,只需要把模块按i2c接线到Arduino并烧录程序查看串口监视器就可以得到正确的i2c地址了!

设置蓝牙模块代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#define AT 2//en接2号引脚
#define LED 13
void setup()
{

pinMode(LED,OUTPUT);
pinMode(AT,OUTPUT);
digitalWrite(AT,HIGH);
Serial.begin(38400);//这里应该和你的模块通信波特率一致
delay(100);
Serial.println("AT");
delay(100);
Serial.println("AT+NAME=Arduino");//命名模块名
delay(100);
Serial.println("AT+ROLE=0");//设置主从模式:0从机,1主机
delay(100);
Serial.println("AT+PSWD=1234");//设置配对密码,如1234
delay(100);
Serial.println("AT+UART=9600,0,0");//设置波特率9600,停止位1,校验位无
delay(100);
Serial.println("AT+RMAAD");//清空配对列表
}
void loop()
{

digitalWrite(LED, HIGH);
delay(500);
digitalWrite(LED, LOW);
delay(500);
}

参考:蓝牙HC05模块探究-设置AT指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <SoftwareSerial.h>   // 引用程式庫

// 定義連接藍牙模組的序列埠
SoftwareSerial BT(8, 9); // 接收腳, 傳送腳
char val; // 儲存接收資料的變數

void setup() {
Serial.begin(9600); // 與電腦序列埠連線
Serial.println("BT is ready!");

// 設定藍牙模組的連線速率
// 如果是HC-05,請改成38400
BT.begin(9600);
}

void loop() {
// 若收到「序列埠監控視窗」的資料,則送到藍牙模組
if (Serial.available()) {
val = Serial.read();
BT.print(val);
}

// 若收到藍牙模組的資料,則送到「序列埠監控視窗」
if (BT.available()) {
val = BT.read();
Serial.print(val);
}
}

HC-06AT命令设置

文章目录
,