#include <DS18B20.h>
#include <math.h>
const int MAXRETRY = 4;
const uint32_t msSAMPLE_INTERVAL = 2500;
const uint32_t msMETRIC_PUBLISH = 30000;
DS18B20 ds18b20(D0, true); //Sets Pin D2 for Temp Sensor and
// this is the only sensor on bus
char szInfo[64];
int Outside;
double celsius;
double Inside;
double Close_Curtain_Threshold = 0;
uint32_t msLastMetric;
uint32_t msLastSample;
int servoPin = A5;
int rssival = 0;
Servo CurtainServo;
int servoPos = 0;
const String key = "FOM7BJ4R1JOZG2KE";
void myHandler(const char *event, const char *data){
String strdata = String(data);
Outside = strdata.toInt();
}
void setup() {
Time.zone(-5);
Particle.variable("Inside_Temp", Inside);
Particle.variable("Outside_Temp", Outside );
Particle.variable("Curtain", Close_Curtain_Threshold );
Particle.subscribe("Outside_Temp_M3171_18", myHandler);
Serial.begin(115200);
CurtainServo.attach( A5 );
Particle.function("servo", servoControl);
}
void loop() {
if (millis() - msLastSample >= msSAMPLE_INTERVAL){
getTemp();
}
if (millis() - msLastMetric >= msMETRIC_PUBLISH){
Serial.println("Publishing now.");
publishData();
}
Close_Curtain_Threshold = (Outside - Inside);
Particle.publish("thingSpeakWrite_All", "{ \"1\": \"" + String(Inside) + "\"," +
"\"2\": \"" + String(Outside) + "\"," +
"\"k\": \"" + key + "\" }", 60, PRIVATE);
delay(30000);
}
void publishData(){
if(!ds18b20.crcCheck()){ //make sure the value is correct
return;
}
sprintf(szInfo, "%2.2f", Inside);
Particle.publish("InsideTemp_M3171_18", szInfo, PRIVATE);
msLastMetric = millis();
}
void getTemp(){
float _temp;
int i = 0;
do {
_temp = ds18b20.getTemperature();
} while (!ds18b20.crcCheck() && MAXRETRY > i++);
if (i < MAXRETRY) {
celsius = _temp;
Inside = ds18b20.convertToFahrenheit(_temp);
Serial.println(Inside);
}
else {
celsius = Inside = NAN;
Serial.println("Invalid reading");
}
msLastSample = millis();
}
int servoControl(String command)
{
// Convert
int newPos = command.toInt();
// Make sure it is in the right range
// And set the position
servoPos = constrain( newPos, 0 , 180);
// Set the servo
CurtainServo.write( servoPos );
// done
return 1;
}
/* begin particle webhook code snippit to add to particle webhook interface on console
{
"event": "thingSpeakWrite_",
"url": "https://api.thingspeak.com/update",
"requestType": "POST",
"form": {
"api_key": "{{k}}",
"field1": "{{1}}",
"field2": "{{2}}",
"field3": "{{3}}",
"field4": "{{4}}",
"field5": "{{5}}",
"field6": "{{6}}",
"field7": "{{7}}",
"field8": "{{8}}",
"lat": "{{a}}",
"long": "{{o}}",
"elevation": "{{e}}",
"status": "{{s}}"
},
"mydevices": true,
"noDefaults": true
}
*/
Comments