arduino之网络通信

网络连接

需要包含Ethernet.h头文件

限于篇幅,就只列出关键代码。

第一步需要设置mac地址和静态ip,定义一个EthernerClient类型变量用来进行连接。

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 <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress staticIP(10, 0, 0, 20);
EthernetClient client;
void connectToInternet()
{
// Attempt to connect to Ethernet with DHCP
if (Ethernet.begin(mac) == 0)
{
Serial.print("[ERROR] Failed to Configure Ethernet using DHCP");
Ethernet.begin(mac, staticIP);
}
delay(1000);
// Connection successful
Serial.println("[INFO] Connection Successful");
Serial.print("");
printConnectionInformation();
Serial.println("-----------------------------------------------");
Serial.println("");
}
void printConnectionInformation()
{
// Print Connection Information
Serial.print("[INFO] IP Address: ");
Serial.println(Ethernet.localIP());
Serial.print("[INFO] Subnet Mask: ");
Serial.println(Ethernet.subnetMask());
Serial.print("[INFO] Gateway: ");
Serial.println(Ethernet.gatewayIP());
Serial.print("[INFO] DNS: ");
Serial.println(Ethernet.dnsServerIP());
}

WIFI连接

头文件 WIFI.h

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <SPI.h>
#include <WiFi.h>
/***************************************************************************
* Internet Connectivity Setup - Variables & Functions
**************************************************************************/
char ssid[] = "YOUR_SSID"; // Network SSID (name)
char pass[] = "YOUR_PASSWORD"; // Network Password (use for WPA,
// or use as key for WEP)
int keyIndex = 0; // Network Key Index Number
int status = WL_IDLE_STATUS;
WiFiClient client;
void connectToInternet()
{
status = WiFi.status();
// Check for the presence of the shield
if (status == WL_NO_SHIELD)
{
Serial.println("[ERROR] WiFi Shield Not Present");
// Do nothing
while (true);
}
// Attempt to connect to WPA/WPA2 Wifi network
while ( status != WL_CONNECTED)
{
Serial.print("[INFO] Attempting Connection - WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
}
// Connection successful
Serial.print("[INFO] Connection Successful");
Serial.print("");
printConnectionInformation();
Serial.println("-----------------------------------------------");
Serial.println("");
}
void printConnectionInformation()
{
// Print Network SSID
Serial.print("[INFO] SSID: ");
Serial.println(WiFi.SSID());
// Print Router's MAC address
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("[INFO] BSSID: ");
Serial.print(bssid[5], HEX);
Serial.print(":");
Serial.print(bssid[4], HEX);
Serial.print(":");
Serial.print(bssid[3], HEX);
Serial.print(":");
Serial.print(bssid[2], HEX);
Serial.print(":");
Serial.print(bssid[1], HEX);
Serial.print(":");
Serial.println(bssid[0], HEX);
// Print received signal strength
long rssi = WiFi.RSSI();
Serial.print("[INFO] Signal Strength (RSSI): ");
Serial.println(rssi);
// Print encryption type
byte encryption = WiFi.encryptionType();
Serial.print("[INFO] Encryption Type: ");
Serial.println(encryption, HEX);
// Print WiFi Shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("[INFO] IP Address: ");
Serial.println(ip);
// Print MAC address
byte mac[6];
WiFi.macAddress(mac);
Serial.print("[INFO] MAC Address: ");
Serial.print(mac[5], HEX);
Serial.print(":");
Serial.print(mac[4], HEX);
Serial.print(":");
Serial.print(mac[3], HEX);
Serial.print(":");
Serial.print(mac[2], HEX);
Serial.print(":");
Serial.print(mac[1], HEX);
Serial.print(":");
Serial.println(mac[0], HEX);
}
void setup()
{
Serial.begin(9600);
connectToInternet();
}
void loop()
{
// Do nothing
}

通讯协议

HTTP

Get请求

部分代码省略,使用client.connect连接服务,client.println发送http get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
char server[] = {"www.httpbin.org"};
int port = 80;
void doHttpGet()
{
String requestData = "requestVar=test";
if (client.connect(server, port)) //WIFIClient或者EthernetClient
{
Serial.println("[INFO] Server Connected - HTTP GET Started");
// Make HTTP GET request
client.println("GET /get?" + requestData + " HTTP/1.1");
client.println("Host: " + String(server));
client.println("Connection: close");
client.println();
Serial.println("[INFO] HTTP GET Completed");
}
else
{
Serial.println("[ERROR] Connection Failed");
}
Serial.println("-----------------------------------------------");
}

POST请求

post请求与get请求类似

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
void doHttpPost()
{
String requestData = "requestData={\"requestVar:test\"}";
if (client.connect(server, port))
{
Serial.println("[INFO] Server Connected - HTTP POST Started");
// Make HTTP POST request
client.println("POST /post HTTP/1.1");
client.println("Host: " + String(server));
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");
client.print("Content-Length: ");
client.println(requestData.length());
client.println();
client.println(requestData);
Serial.println("[INFO] HTTP POST Completed");
}
else
{
Serial.println("[ERROR] Connection Failed");
}
Serial.println("-----------------------------------------------");
}

MQTT

MQTT是机器-机器协议,使用发布者-订阅者模型,发布者发布数据在服务器上(broker),订阅者接受数据,订阅者和发布者不需要知道对方。它们都连接broker,异步通信。 broker会通知订阅者发布者发布的主题。

需要PubSubClient.h

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
39
40
41
42
43
44
45
46
47
48
#include <SPI.h>
#include <WiFi.h>
#include <PubSubClient.h>
// IP address of the Mosquitto server
char server[] = {"test.mosquitto.org"};
int port = 1883;
char topic[] = {"codifythings/testMessage"};
PubSubClient pubSubClient(server, 1883, callback, client);
void callback(char* topic, byte* payload, unsigned int length)
{
// Print payload
String payloadContent = String((char *)payload);
Serial.println("[INFO] Payload: " + payloadContent);
}
void setup()
{
// Initialize serial port
Serial.begin(9600);
// Connect Arduino to internet
connectToInternet();
//Connect MQTT Broker
Serial.println("[INFO] Connecting to MQTT Broker");
if (pubSubClient.connect("arduinoClient"))
{
Serial.println("[INFO] Connection to MQTT Broker Successfull");
pubSubClient.subscribe(topic);
Serial.println("[INFO] Successfully Subscribed to MQTT Topic ");
Serial.println("[INFO] Publishing to MQTT Broker");
pubSubClient.publish(topic, "Test Message");
}
else
{
Serial.println("[INFO] Connection to MQTT Broker Failed");
}
}
void loop()
{
// Wait for messages from MQTT broker
pubSubClient.loop();
}
文章目录
  1. 1. 网络连接
  2. 2. WIFI连接
  3. 3. 通讯协议
    1. 3.1. HTTP
      1. 3.1.1. Get请求
      2. 3.1.2. POST请求
      3. 3.1.3. MQTT
|