I'm trying to get a server working that allows my Arduino to send temperature data every 2 minutes. I was able to get the server to work with the temperature data being sent every millisecond, but the moment I tried to make It send every 2 minutes using the milis() function, the server just would be on an infinite load. On top of this, the server will only load correctly if client.stop() is in the code.
#include <WiFiNINA.h>
#include "Adafruit_Sensor.h"
#include "Adafruit_AM2320.h"
char ssid[] = "---"; // your network SSID (name) between the ""
char pass[] = "----"; // your network password between the ""
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS; // connection status
WiFiServer server(80); // server socket
WiFiClient client;
Adafruit_AM2320 am2320 = Adafruit_AM2320();
int ledPin = 2;
unsigned long previousMillis = 0; // will store last time temperature was sent
const long interval = 10000; // interval at which to send temperature (milliseconds)
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
while (!Serial);
enable_WiFi();
connect_WiFi();
server.begin();
am2320.begin();
printWifiStatus();
// Initialize previousMillis
previousMillis = millis();
}
void loop() {
unsigned long currentMillis = millis();
client = server.available();
// Check if it's time to send temperature
if (currentMillis - previousMillis >= interval) {
// Save the last time you sent temperature
previousMillis = currentMillis;
if (client) {
Serial.print("Client connected");
// Prepare HTTP response
// blank line indicates end of headers
// Send temperature data
client.print(am2320.readTemperature());
Serial.print(am2320.readTemperature());
Serial.print("Sending temperature");
// Close the connection after response (optional)
}
}
// Handle other tasks or conditions here
}
// Handle other tasks or conditions here
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
void enable_WiFi() {
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE) {
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv < "1.0.0") {
Serial.println("Please upgrade the firmware");
}
}
void connect_WiFi() {
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
}