Wifi Rev 2 未连接到 wifi

时间:2021-02-25 20:29:24

标签: c++ c arduino wifi arduino-ide

我在使用 Wifi Rev2 连接到 wifi 时遇到问题。我的IDE是1.8.13,固件目前是1.2.1。我一直在使用 1.0.0 固件并成功连接到 wifi 网络,但即使在成功连接到服务器后,我尝试发送的 post 请求也没有通过。

使用 Wifi Rev 2 发送 post 请求需要哪些固件/IDE/wifi 库配置,为什么将固件更新到 1.0.0 以上的任何版本会阻止我的程序连接到 wifi?

#include <SPI.h>
#include <WiFiNINA.h>
#include "arduino_secrets.h"
#include "DHT.h"
#define DHTPIN 2
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
int status = WL_IDLE_STATUS;
char server[] = "www.mywebsite.com";
unsigned long lastConnectionTime = 0;           
const unsigned long postingInterval = 2L * 1000L;
WiFiClient client;
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(9600);
  pinMode(WATER_PUMP_PIN, OUTPUT);
  dht.begin();
 
   // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }
 
   // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }

  // you're connected now, so print out the data:
  Serial.println("You're connected to the network");
  printWiFiData();
}

void loop() {
   if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

void printWiFiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP address : ");
  Serial.println(ip);

  Serial.print("Subnet mask: ");
  Serial.println((IPAddress)WiFi.subnetMask());

  Serial.print("Gateway IP : ");
  Serial.println((IPAddress)WiFi.gatewayIP());

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);
}

void httpRequest() {
   
    client.stop();

    Serial.println("\nStarting connection to server...");

    String PostData = String("{\"variable\":\"temperature\", \"value\":") + "404.2" + String(",\"unit\":\"C\"}");
    if (client.connect(server,80)) {                     
    Serial.println("connected to server");
    // Make a HTTP request:   
    client.println("POST /data? HTTP/1.1");
    client.println("Host: www.mywebsite.com");
    client.println("_ssl: false");                       
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(PostData.length());
    client.println();
    client.print(PostData);
    lastConnectionTime = millis();
  }
  else {
    // if you couldn't make a connection:
    Serial.println("connection failed");
  }
}
void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}

此代码已被精简为仅相关功能

0 个答案:

没有答案