Code: Select all
*
*
MKR ENV Shield - Read Sensors
This example reads the sensors on-board the MKR ENV shield
and send them to the Adafruit IOT Cloud
The circuit:
- Arduino MKR board
- Arduino MKR ENV Shield attached
*/
#include <Adafruit_MAX31865.h>
Adafruit_MAX31865 thermo = Adafruit_MAX31865(7, 8, 10, 9);
#define RREF 4303.0
// The 'nominal' 0-degrees-C resistance of the sensor
// 100.0 for PT100, 1000.0 for PT1000
#define RNOMINAL 1001.2
#include <ArduinoJson.h>
#include <avr/dtostrf.h>
#include <SPI.h>
/////////////////////////
#include <WiFiNINA.h>
#include "arduino_secrets.h"
char ssid[] = SECRET_SSID; // your network SSID (name)
char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;
char server[] = "io.adafruit.com"; // name address for Adafruit IOT Cloud
///////////////////////////
float setpoint = 71.5;
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 20000; // delay between updates, in milliseconds
// Initialize the client library
WiFiClient client;
unsigned long currentMillis;
unsigned long OneSecStart;
unsigned long OneSecDelay = (1 * 1000); //one sec
unsigned long PWMperiodSetpoint = (30 * 60);
unsigned long PWMperiod = (30 * 60);
unsigned long minPWMperiod = (20 * 60);
unsigned long PWMindex = 0;
unsigned long Onperiod = 240;
unsigned long minOnperiod = 240;
unsigned long maxOnperiod = 900;
unsigned long relay = 0;
unsigned long TiOnTime = 20;
unsigned long wificount = 0;
float batteryLevel=4;
float x = 0.2;
float ki = 0.0033333;
int readIndex = 0;
float tempreading = 0;
float TempSetAdjusted=75;
float TempSet = 75;
//float TempSetmin = 69.0;
float reading = TempSet-0.1;
//**************************************
void setup()
{
Serial.begin(9600); // open the serial port at 9600 bps:
connectToWIFI();
OneSecStart = millis(); //<<<<<<<< Add this line
pinMode(5, OUTPUT);
thermo.begin(MAX31865_2WIRE); // set to 2WIRE or 4WIRE as necessary
readIndex = 0;
tempreading = 0;
PWMindex = Onperiod;
} //***** END OF setup() *****
void loop()
{
unsigned long currentMillis = millis();
if (currentMillis - OneSecStart > OneSecDelay)
{
while (currentMillis - OneSecStart > OneSecDelay)
{
OneSecStart += OneSecDelay; // get ready for next one sec
}
float temp = 0;
++readIndex;
++PWMindex;
temp = thermo.temperature(RNOMINAL, RREF) * 1.8 + 31.4;
tempreading += temp / 10.0;
if (readIndex >= 10) {
batteryLevel = analogRead(ADC_BATTERY) * 3.3f / 1023.0f / 1.2f * (1.2f+0.33f);
if (Serial)
{
Serial.print(currentMillis / 60000.0, 4);
Serial.print(" "); Serial.print(tempreading, 4);
Serial.print(" "); Serial.print((float) Onperiod);
Serial.print(" "); Serial.print(relay);
Serial.print(" "); Serial.print((float)PWMperiod);
Serial.print(" ");Serial.print(batteryLevel);
Serial.print(" ");Serial.println(TempSet);
}
++wificount;
if (wificount==3)
{
//httpSRequest();
//printWifiStatus();
setpoint=httpRRequest(); // send/get data to/from Cloud
wificount=0;
}
// read data from Cloud
if (setpoint>64.9 && setpoint<75.1)
{
if ((setpoint-TempSet)>0.2)
{
TempSet+=0.2;
}else if((setpoint-TempSet)<-0.2)
{
TempSet-=0.2;
}else
{
TempSet=setpoint;
}
}
reading=tempreading;
tempreading = 0;
readIndex = 0;
x+=ki*(TempSet-reading);
if(x>0){
x=0;
}else if (x<-3){
x=-3;
}
TempSetAdjusted=TempSet;// +x;
}
if (PWMindex >= (minPWMperiod) && TempSetAdjusted<=reading)
{
PWMperiod = PWMindex-1;
Onperiod *=(PWMperiodSetpoint);
if (PWMperiod>(200*60)){
Onperiod /=200*60;
}else {
Onperiod /=PWMperiod;
}
if(Onperiod>maxOnperiod){
Onperiod=maxOnperiod;
}else if (Onperiod<minOnperiod){
Onperiod=minOnperiod;
}
PWMindex = 0;
relay = 100;
digitalWrite(5, HIGH); // will turn the relay on
}
if (PWMindex >= Onperiod)
{
relay = 0;
digitalWrite(5, LOW); // will turn the relay off
}
}
} //****** END OF loop() *****
// this method makes a HTTP connection to the server:
float httpRRequest()
{
// JSon
/*
* GET: /api/v2/{username}/feeds/{feed_key}/data/last
{
"id": "string",
"value": "string",
"feed_id": 0,
"group_id": 0,
"expiration": "string",
"lat": 0,
"lon": 0,
"ele": 0,
"completed_at": "string",
"created_at": "string",
"updated_at": "string",
"created_epoch": 0
}
*/
/*
* https://io.adafruit.com/api/docs/#operation/createGroupData
*
* POST /{username}/groups/{group_key}/data
*
* JSON:
*
{
"location": {
"lat": 0,
"lon": 0,
"ele": 0
},
"feeds": [
{
"key": "string",
"value": "string"
}
],
"created_at": "string"
}
*/
// close any connection before send a new request.
// This will free the socket on the Nina module
client.stop();
Serial.println("\nStarting connection to server...");
if (client.connect(server, 80))
{
Serial.println("connected to server");
// Make a HTTP request:
client.println("GET /api/v2/" IO_USERNAME "/feeds/ctrldata.setpoint/data/last HTTP/1.1");
client.println("Host: io.adafruit.com");
client.println("Connection: close");
client.println("Content-Type: application/json");
client.println("X-AIO-Key: " IO_KEY);
// Terminate headers with a blank line
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return 60.0;
}
// Check HTTP status
char status[32] = {0};
client.readBytesUntil('\r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return 60.0;
}
// Skip HTTP headers
char endOfHeaders[] = "\r\n\r\n";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response1"));
return 60.0;
}
// Skip Adafruit headers
char endOfHeaders2[] = "\r";
if (!client.find(endOfHeaders2)) {
Serial.println(F("Invalid response2"));
return 60.0;
}
//Deserialize JSon
const size_t capacityr = JSON_OBJECT_SIZE(12) + 170;
StaticJsonDocument<capacityr> docr;
DeserializationError error = deserializeJson(docr, client);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return 60.0;
}
const size_t capacity = JSON_ARRAY_SIZE(3) + 3*JSON_OBJECT_SIZE(2) + 2*JSON_OBJECT_SIZE(3) + 130;
StaticJsonDocument<capacity> doc;
// Add the "location" object
JsonObject location = doc.createNestedObject("location");
location["lat"] = 0;
location["lon"] = 0;
location["ele"] = 0;
// Add the "feeds" array
JsonArray feeds = doc.createNestedArray("feeds");
JsonObject feed1 = feeds.createNestedObject();
feed1["key"] = "tempctrl";
feed1["value"] = tempreading;
JsonObject feed2 = feeds.createNestedObject();
feed2["key"] = "onperiodctrl";
feed2["value"] = (float) Onperiod;
JsonObject feed3 = feeds.createNestedObject();
feed3["key"] = "heatctrl";
feed3["value"] = relay;
JsonObject feed4 = feeds.createNestedObject();
feed4["key"] = "tempsetctrl";
feed4["value"] = TempSet;
// Make a HTTP request:
client.println("POST /api/v2/" IO_USERNAME "/groups/" IO_GROUP "/data HTTP/1.1");
client.println("Host: io.adafruit.com");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(measureJson(doc));
client.println("Content-Type: application/json");
client.println("X-AIO-Key: " IO_KEY);
// Terminate headers with a blank line
client.println();
// Send JSON document in body
serializeJson(doc, client);
// note the time that the connection was made:
//lastConnectionTime = millis();
Serial.println("data sent!");
const char* value = docr["value"];
Serial.println("data received!");
return atof(value);
} else {
// if you couldn't make a connection:
Serial.println("connection failed");
return 60.0;
}
}
void connectToWIFI()
{
// 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");
}
int attemps=0;
// attempt to connect to Wifi network:
while (status != WL_CONNECTED && attemps<3) {
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 20 seconds for connection:
delay(20000);
attemps++;
}
if (status != WL_CONNECTED){
Serial.println("Not connected to wifi");
} else {
Serial.println("Connected to wifi");
delay(2000);
printWifiStatus();
}
}
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");