我目前正在尝试使用WiFi和DNS将我的ESP8266连接到Azure MySQL数据库。看起来WiFi库本身不支持DNS,只有IP但Azure不支持静态IP,因此我需要使用DNS。
这是我到目前为止的代码:
#include <WiFi.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include <Dns.h>
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char hostname[] = "something.mysql.database.azure.com"; //replace something with database name
IPAddress server_ip;
char user[] = "root"; // MySQL user login username
char password[] = "secret"; // MySQL user login password
// WiFi card example
char ssid[] = "WiFiSSID"; // your SSID
char pass[] = "secret"; // your SSID Password
WiFiClient client; // Use this for WiFi instead of EthernetClient
MySQL_Connection conn((Client *)&client);
void setup() {
Serial.begin(115200);
while (!Serial); // wait for serial port to connect. Needed for Leonardo only
// Begin WiFi section
int status = WiFi.begin(ssid, pass);
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while(true);
}
// print out info about the connection:
else {
Serial.println("Connected to network");
IPAddress ip = WiFi.localIP();
// Particle.process(); Seemingly need to call this for WiFi.dnsServerIP() to be available but gives "out of scope error".
DNSClient dns;
dns.begin(WiFi.dnsServerIP());
dns.getHostByName(hostname, server_ip);
}
// End WiFi section
Serial.println("Connecting...");
if (conn.connect(server_ip, 3306, user, password)) {
delay(1000);
}
else
Serial.println("Connection failed.");
conn.close();
}
void loop() {
}
这是我得到的错误:
Arduino: 1.8.5 (Windows 10), Board: "SparkFun ESP8266 Thing Dev, 80 MHz, 512K (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
C:\Users\Mathi\OneDrive\Documents\Arduino\wifi_hostname_sketchB\wifi_hostname_sketchB.ino: In function 'void setup()':
wifi_hostname_sketchB:65: error: 'class WiFiClass' has no member named 'dnsServerIP'
dns.begin(WiFi.dnsServerIP());
^
Multiple libraries were found for "Ethernet.h"
Used: C:\Users\Mathi\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.1\libraries\Ethernet
Not used: D:\Programs\Arduino IDE\Arduino\libraries\Ethernet
exit status 1
'class WiFiClass' has no member named 'dnsServerIP'
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
我尝试过使用Particle.process函数,但它一直给我一个'超出范围'的错误。大多数人通过更改固件来修复此问题,但没有帮助我。
我从https://github.com/ChuckBell/MySQL_Connector_Arduino获得了大部分代码 我按照指南使用WiFi访问MySQL数据库,但这不包括DNS。
答案 0 :(得分:1)
请勿使用DNSclient,它不适用于WiFi,请改用WiFi.hostByName。花了我两天时间找到这个宝石。
IPAddress server_ip;
WiFi.hostByName("www.google.com",server_ip);
Serial.println(server_ip); // server_ip will contain the ip address of google.com
答案 1 :(得分:0)
WiFi库WiFiWebClient example使用主机名连接到网络服务器。
char server[] = "www.google.com"; // name address for Google (using DNS)
if (client.connect(server, 80)) {
答案 2 :(得分:-2)
由于Microsoft Azure仅支持DNS,而ESP8266 WiFi库仅支持静态IP,因此它们无法协同工作。您可以使用谷歌云,因为这支持静态IP。