I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.
I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to client.connect(server, 80)
- I don't understand why it fails. I've tried adding client.stop()
and client.flush()
after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read
#include <SPI.h>
#include <WiFi101.h>
#include <string.h>
#include <stdlib.h>
#include <OneWire.h>
#include <DallasTemperature.h>
//WiFi Client Setup
char ssid[] = "HIDDEN"; // your network SSID (name)
char pass[] = "HIDDEN"; // your network password
int status = WL_IDLE_STATUS; // the WiFi radio's status
char server[] = "HIDDEN";
WiFiClient client;
// Setup for temperature sensor
#define ONE_WIRE_BUS A5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;
void setup() {
Serial.begin(9600);
WiFi.setPins(8,2,A3,-1);
while (!Serial) {
Serial.println("Waiting for serial");
}
//Connect to wifi shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
wifiConnect();
sensors.begin();
}
void loop() {
while (client.available()) {
char c = client.read();
Serial.write(c);
}
/*
Code to get temperature here
*/
httpRequest(temp);
delay(10000); // 5min
}
void httpRequest(String temp) {
String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connected to server");
client.println(request);
client.println("Authorization: Token HIDDEN");
client.println("Host: HIDDEN");
client.println("Connection: close");
client.println();
}
else {
Serial.println("Connection failed");
}
}
void wifiConnect() {
//Attempt to connect to WiFi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000);
}
Serial.println("You're connected to the network");
}