Quantcast
Channel: ThingSpeak IoT Community - Forum: Arduino
Viewing all articles
Browse latest Browse all 172

Geert on aquaponics sensor, send to thingspeak, what is wrong?

$
0
0

Dear all, 

 

I try to post my arduino uno sensor results to thingspeak, and I try differnt options, and cannot figure it out. Any help possible? I might give up on thingspeak. 

 

Geert

 

sketch :

/* a sketch to make sensors work and let them post to thingspeak (probably)

Sensors used:
1 EC conductivity sensor "el cheapo" pin A0 (A1:GND; A2:5v)
DS18B20 water temperature pin D2
2 BMP085 Air pressure and temp in box: pin A4, A5
3 Rain sensor pin A3, D3
4 DHT22 air and humidity pin D6
Sending data:
ESP8266 pin D9, D10 D11;
Streaming service: Thingspeak

Relays: to be implemented

 

This sketch is compiled from individual sketches for each part.

ElCheapo Arduino EC-PPM/water temperature measurment
Parts:
-Arduino - Uno/Mega
-Standard American two prong plug
-1 kohm resistor
-DS18B20 Waterproof Temperature Sensor

See http://www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

write to thingspeak, from library example writemultiplevoltages ThingSpeak ( https://www.thingspeak.com ) is an analytic IoT platform service that allows you to aggregate, visualize and
analyze live data streams in the cloud.

Copyright 2016, The MathWorks, Inc.

*/

//************************** Libraries Needed To Compile The Script [See Read me In Download] ***************//
// Both below Library are custom ones [ SEE READ ME In Downloaded Zip If You Dont Know how To install] Use them or add a pull up resistor to the temp probe

#include <OneWire.h>
#include <DallasTemperature.h>

// DHT variables
#include "DHT.h"

#define DHTPIN 6 // what digital pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321

// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

// BMP pressure declare

#include <Wire.h>

#define BMP085_ADDRESS 0x77 // I2C address of BMP085

const unsigned char OSS = 0; // Oversampling Setting

// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;

// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;

short temperature;
long pressure;

// Use these for altitude conversions
const float p0 = 101325; // Pressure at sea level (Pa)
float altitude;

// BMP declare finish

// WIFI VARIABLES

#include <SoftwareSerial.h>
#define SSID "ESW-Apartment 709"
#define PASS "merlinsbeard"
#define DST_IP "184.106.153.149"
SoftwareSerial espSerial(10, 11); // RX, TX
// reset on pin9 (LOW to reset)
//*-- IoT Information
// myChannelNumber = 147606; myWriteAPIKey = "UIAY9F4A7J1KTQ3S";

// GET /update?key=IPYZZQG01957FQ42
String GET = "GET /update?key=IPYZZQG01957FQ42";

// WiFi variables end

//************************* User Defined Variables ********************************************************//

//##################################################################################
//----------- Do not Replace R1 with a resistor lower than 300 ohms ------------
//##################################################################################

int R1 = 1000;
int Ra = 25; //Resistance of powering Pins
int ECPin = A0;
int ECGround = A1;
int ECPower = A2; // originally A4 is used by air pressure measurement

//*********** Converting to ppm [Learn to use EC it is much better**************//
// Hana [USA] PPMconverion: 0.5
// Eutech [EU] PPMconversion: 0.64
//Tranchen [Australia] PPMconversion: 0.7
// Why didnt anyone standardise this?

float PPMconversion = 0.64;

//*************Compensating for temperature ************************************//
//The value below will change depending on what chemical solution we are measuring
//0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

 

//********************** Cell Constant For Ec Measurements *********************//
//Mine was around 2.9 with plugs being a standard size they should all be around the same
//But If you get bad readings you can use the calibration script and fluid to get a better estimate for K
float K = 2.88;

 

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 2 // Data wire For Temp Probe is plugged into pin 10 on the Arduino // with me on 2
const int TempProbePossitive = 8; //Temp Probe power connected to pin 9 // I don' have that?
const int TempProbeNegative = 9; //Temp Probe Negative connected to pin 8 //should I do that?

 

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float Temperature = 10;
float EC = 0;
float EC25 = 0;
int ppm = 0;

float raw = 0;
float Vin = 5;
float Vdrop = 0;
float Rc = 0;
float buffer = 0;

/*Arduino Rain Sensor sketch*/

int rainsense = 3; // analog sensor input pin 0
//int buzzerout= 10; // digital output pin 10 - buzzer output
int countval = 0; // counter value starting from 0 and goes up by 1 every second

void bmp085Calibration();
boolean connectWiFi();
void GetEC();
//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
//EC and water temp
Serial.begin(9600);
pinMode(TempProbeNegative , OUTPUT ); //seting ground pin as output for tmp probe
digitalWrite(TempProbeNegative , LOW );//Seting it to ground so it can sink current
pinMode(TempProbePossitive , OUTPUT );//ditto but for positive
digitalWrite(TempProbePossitive , HIGH );
pinMode(ECPin, INPUT);
pinMode(ECPower, OUTPUT); //Setting pin for sourcing current
pinMode(ECGround, OUTPUT); //setting pin for sinking current
digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly
// wifi setup
pinMode(10, INPUT); // softserial RX for ESP
pinMode(11, OUTPUT); // softserial TX for ESP
pinMode(9, OUTPUT); // ESP reset

 

espSerial.begin(9600); // for ESP, can't be faster than 19200 for softserial
espSerial.setTimeout(2000);
// wifi setup end

delay(100);// gives sensor time to settle
sensors.begin();
delay(100);
//** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
// Consule Read-Me for Why, or just accept it as true
R1 = (R1 + Ra); // Taking into acount Powering Pin Resitance

// Serial.println("ElCheapo Arduino EC-PPM measurments");
//Serial.println("By: Michael Ratcliffe Mike@MichaelRatcliffe.com");
//Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
//Serial.println("");
// Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
// Serial.println("");
// Serial.println("Measurments at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:");

//rainsensor
pinMode(rainsense, INPUT);

//BMP pressure
Wire.begin();
bmp085Calibration();

/* //WIFI
debug.begin( _baudrate );
pinMode(9, OUTPUT); //ESP reset
sendDebug("AT");
debug.println("AT+RST");// added
delay(5000);
if (Serial.find("OK"))
{
Serial.println("RECEIVED: OK
Data ready to sent!");
connectWiFi();
}*/
//******************************************* End of Setup **********************************************************************//

}

//************************************* Main Loop - Runs Forever ***************************************************************//
//Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop
void loop()
{

// ec-watertemp sensor
GetEC(); //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water

//rainsensor

int rainSenseReading = analogRead(rainsense);
Serial.print("rain intensity 0 (hard) - 1023 (no rain) : ");
Serial.println(rainSenseReading); // serial monitoring message
delay(250);// rain sensing value from 0 to 1023.
// from heavy rain - no rain.
if (countval >= 35) {
Serial.print("Heavy rain");
// digitalWrite(buzzerout, HIGH); //raise an alert after x time
}
//raining for long duration rise buzzer sound
// there is no rain then reset the counter value
if (rainSenseReading < 350) {
countval++; // increment count value
}
else if (rainSenseReading > 350) { // if not raining
// digitalWrite(buzzerout, LOW); // turn off buzzer
countval = 0; // reset count to 0
}
delay(1000);
// finish rainsensor
//BMP pressure
temperature = bmp085GetTemperature(bmp085ReadUT());
pressure = bmp085GetPressure(bmp085ReadUP());
altitude = (float)44330 * (1 - pow(((float) pressure / p0), 0.190295));

Serial.print("Temperature: ");
Serial.print(temperature, DEC);
Serial.println(" *0.1 deg C");
Serial.print("Pressure: ");
Serial.print(pressure, DEC);
Serial.println(" Pa");
Serial.print("Altitude: ");
Serial.print(altitude, 2);
Serial.println(" m");
Serial.println();

// BMP finish

//dht sensor
// get, calculate and print temperature and humity to serial

// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(false);

// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
return;
}

Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);

 

//printing everything
PrintReadings(); // Cals Print routine [below main loop]

 

// delay from ec
// delay(60000);// original is 5000, now 1 minute to bottom loop

// SEND DATA OVER WIFI
boolean sent=false;
for(int i=0;i<7;i++) //try 7 times 20 08
{
if(sendData(Temperature, EC25, rainSenseReading, t, h, temperature, pressure)) //perhaps?
{
sent = true;
break;
}
}
if (!sent){
Serial.println(F("failed 7 times to send"));

}

// delay from ec
delay(60000);// original is 5000, now 1 minute

}

boolean sendData(int W, int C, int S, int A, int H, int B, int P)
{
Serial.print(F("reset ESP8266.."));
//test if the module is ready

digitalWrite(9, LOW); // reset the ESP module
delay(100);
digitalWrite(9, HIGH);

espSerial.println("AT+RST");
// espSerial.print("AT+UART_DEF=9600,8,1,0,0");
delay(500);

//if(espSerial.find("ready"))
//// {
//Serial.print(F("module is ready.."));
// }
// else
//{
// Serial.println(F("module has no response."));
//return false;
//}

//connect to the wifi
boolean connected=false;

for(int i=0;i<7;i++) // 7 times 20 08
{
if(connectWiFi())
{
connected = true;
break;
}
}
if (!connected){
Serial.println(F("tried 7 times to connect, please reset"));
return false;
}
delay(500);

//set the single connection mode
espSerial.println("AT+CIPMUX=0");
delay(2000); // double delay here 20 08

espSerial.flush();

String cmd;
cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += DST_IP;
cmd += "\",80";
espSerial.println(cmd);
Serial.println(cmd);
delay(2000); // insert delay here 10/11
if(espSerial.find("Error")) return false;

//"&field1=" + W + "&field2=" + C + "&field3=" + S + "&field4=" + A + "&field5=" + H + "&field6=" + B + "&field7=" + P+ "
"
String action ;
action = "GET /update?key=IPYZZQG01957FQ42"; //int W, int C, int S, int A, int H, int B, int P
//action += "&field1="; //"&field2="+ C + "&field3=" + S +"&field4=" + A +"&field5="+ H + "&field6=" + B +"&field7=" + P +"
";
action += "&field1=";
action += W;
action += "&field2=";
action += C;
action += "&field3=";
action += S;
action += "&field4=";
action += A;
action += "&field5=";
action += H;
action += "&field6=";
action += B;
action += "&field7=";
action += P;
action += "

";

 

espSerial.print("AT+CIPSEND=");
// espSerial.println("GET /update?key=IPYZZQG01957FQ42&field1=", W,"&field2=", C,"&field3=",S ,"&field4=",A,"&field5=",H ,"&field6=",B,"&field7=", P,"
");
espSerial.println(action.length());
Serial.println(action);
//delay(2000); // insert delay here 10/11
if(espSerial.find(">"))
{
Serial.print(">");
} else
{
espSerial.println("AT+CIPCLOSE");
Serial.println(F("connect timeout"));
return false;
}

//espSerial.println(action);
// Serial.println(action);
delay(2000); //tried 5000 instead of 1000 no difference 30 08

if (espSerial.find("SEND OK"))
{
Serial.print(F("send OK.."));
}
if (espSerial.find("200 OK"))
{
Serial.println(F(" receive OK!"));
return true;
}
else {
return false;
}
}

boolean connectWiFi() {
espSerial.println("AT+CWMODE=1");
delay(3000);//increased from 2000 to 3000, no difference
String cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";
// Serial.println(cmd);
espSerial.println(cmd);
delay(5000);//increased from 5000 to 10000 20 08

if(espSerial.find("OK")) {
Serial.print(F("connected to wifi.."));
return true;
} else
{
Serial.println(F("cannot connect to wifi"));
return false;
}
}

/* // Thingspeak send

String wtemp = String(Temperature); // water temp turn integer to string
String cond = String(EC25); // conductivity turn integer to string
String splash = String(rainSenseReading); // splash turn integer to string
String atemp = String(t); // air temp turn integer to string
String hum = String(h); // humidity turn integer to string
String btemp = String(temperature); // box temp turn integer to string
String pres = String(pressure); // press turn integer to string

updateTS(wtemp, cond, splash, atemp, hum, btemp, pres);
};

*/
//************************************** End Of Main Loop **********************************************************************//

 

//************ This Loop Is called From Main Loop************************//
void GetEC() {

//*********Reading Temperature Of Solution *******************//
sensors.requestTemperatures();// Send the command to get temperatures
Temperature = sensors.getTempCByIndex(0); //Stores Value in Variable

 

//************Estimates Resistance of Liquid ****************//
digitalWrite(ECPower, HIGH);
raw = analogRead(ECPin);
raw = analogRead(ECPin); // This is not a mistake, First reading will be low beause if charged a capacitor
digitalWrite(ECPower, LOW);

 

//***************** Converts to EC **************************//
Vdrop = (Vin * raw) / 1024.0;
Rc = (Vdrop * R1) / (Vin - Vdrop);
Rc = Rc - Ra; //acounting for Digital Pin Resitance
EC = 1000 / (Rc * K);

//*************Compensating For Temperaure********************//
EC25 = EC / (1 + TemperatureCoef * (Temperature - 25.0));
ppm = (EC25) * (PPMconversion * 1000);

;
}
//************************** End OF EC Function ***************************//

 

//***This Loop Is called From Main Loop- Prints to serial usefull info ***//
void PrintReadings() {
Serial.print("Rc: ");
Serial.print(Rc);
Serial.print(" EC: ");
Serial.print(EC25);
Serial.print(" Siemens ");
Serial.print(ppm);
Serial.print(" ppm ");
Serial.print(Temperature);
Serial.println(" *C ");

/*
//********** Usued for Debugging ************
Serial.print("Vdrop: ");
Serial.println(Vdrop);
Serial.print("Rc: ");
Serial.println(Rc);
Serial.print(EC);
Serial.println("Siemens");
//********** end of Debugging Prints *********
*/
};
/* // updateTS(wtemp, cond, splash, atemp, hum, btemp, pres);
void updateTS(String W, String C , String S, String A, String H , String B, String P)
{
// ESP8266 Client

String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
cmd += IP;
cmd += "\",80";
sendDebug(cmd);
debug.println(cmd);// added
delay(2000);
if ( Serial.find( "Error" ) )
{
debug.print( "RECEIVED: Error
Exit1" );
return;
}

cmd = GET + "&field1=" + W + "&field2=" + C + "&field3=" + S + "&field4=" + A + "&field5=" + H + "&field6=" + B + "&field7=" + P+ "
";
Serial.print( "AT+CIPSEND=" );
Serial.println( cmd.length() );
if (Serial.find( ">" ) )
{
debug.print(">");
debug.print(cmd);
Serial.print(cmd);
}
else
{
sendDebug( "AT+CIPCLOSE" );//close TCP connection
}
if ( Serial.find("OK") )
{
debug.println( "RECEIVED: OK" );
}
else
{
debug.println( "RECEIVED: Error
Exit2" );
}
}

void sendDebug(String cmd)
{
debug.print("SEND: ");
debug.println(cmd);
Serial.println(cmd);
}

/* boolean connectWiFi()
{
Serial.print(F("reset ESP8266.."));
//test if the module is ready

digitalWrite(9, LOW); // reset the ESP module
delay(100);
digitalWrite(9, HIGH);

debug.println("AT+RST");
delay(500);
Serial.println("AT+CWMODE=1");//WiFi STA mode - if '3' it is both client and AP
delay(2000);
//Connect to Router with AT+CWJAP="SSID","Password";
// Check if connected with AT+CWJAP?
String cmd = "AT+CWJAP=\""; // Join accespoint
cmd += SSID;
cmd += "\",\"";
cmd += PASS;
cmd += "\"";
sendDebug(cmd);
delay(5000);
if (Serial.find("OK"))
{
Serial.println("RECEIVED: OK");
return true;
}
else
{
Serial.println("RECEIVED: Error");
return false;
}

cmd = "AT+CIPMUX=0";// Set Single connection
sendDebug( cmd );
if ( Serial.find( "Error") )
{
debug.print( "RECEIVED: Error" );
return false;
}
};

 

*/

// Stores all of the bmp085's calibration values into global variables
// Calibration values are required to calculate temp and pressure
// This function should be called at the beginning of the program
void bmp085Calibration()
{
ac1 = bmp085ReadInt(0xAA);
ac2 = bmp085ReadInt(0xAC);
ac3 = bmp085ReadInt(0xAE);
ac4 = bmp085ReadInt(0xB0);
ac5 = bmp085ReadInt(0xB2);
ac6 = bmp085ReadInt(0xB4);
b1 = bmp085ReadInt(0xB6);
b2 = bmp085ReadInt(0xB8);
mb = bmp085ReadInt(0xBA);
mc = bmp085ReadInt(0xBC);
md = bmp085ReadInt(0xBE);
}

// Calculate temperature given ut.
// Value returned will be in units of 0.1 deg C
short bmp085GetTemperature(unsigned int ut)
{
long x1, x2;

x1 = (((long)ut - (long)ac6) * (long)ac5) >> 15;
x2 = ((long)mc << 11) / (x1 + md);
b5 = x1 + x2;

return ((b5 + 8) >> 4);
}

// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up)
{
long x1, x2, x3, b3, b6, p;
unsigned long b4, b7;

b6 = b5 - 4000;
// Calculate B3
x1 = (b2 * (b6 * b6) >> 12) >> 11;
x2 = (ac2 * b6) >> 11;
x3 = x1 + x2;
b3 = (((((long)ac1) * 4 + x3) << OSS) + 2) >> 2;

// Calculate B4
x1 = (ac3 * b6) >> 13;
x2 = (b1 * ((b6 * b6) >> 12)) >> 16;
x3 = ((x1 + x2) + 2) >> 2;
b4 = (ac4 * (unsigned long)(x3 + 32768)) >> 15;

b7 = ((unsigned long)(up - b3) * (50000 >> OSS));
if (b7 < 0x80000000)
p = (b7 << 1) / b4;
else
p = (b7 / b4) << 1;

x1 = (p >> 8) * (p >> 8);
x1 = (x1 * 3038) >> 16;
x2 = (-7357 * p) >> 16;
p += (x1 + x2 + 3791) >> 4;

return p;
}

// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
unsigned char data;

Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();

Wire.requestFrom(BMP085_ADDRESS, 1);
while (!Wire.available())
;

return Wire.read();
}

// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
unsigned char msb, lsb;

Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(address);
Wire.endTransmission();

Wire.requestFrom(BMP085_ADDRESS, 2);
while (Wire.available() < 2)
;
msb = Wire.read();
lsb = Wire.read();

return (int) msb << 8 | lsb;
}

// Read the uncompensated temperature value
unsigned int bmp085ReadUT()
{
unsigned int ut;

// Write 0x2E into Register 0xF4
// This requests a temperature reading
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF4);
Wire.write(0x2E);
Wire.endTransmission();

// Wait at least 4.5ms
delay(5);

// Read two bytes from registers 0xF6 and 0xF7
ut = bmp085ReadInt(0xF6);
return ut;
}

// Read the uncompensated pressure value
unsigned long bmp085ReadUP()
{
unsigned char msb, lsb, xlsb;
unsigned long up = 0;

// Write 0x34+(OSS<<6) into register 0xF4
// Request a pressure reading w/ oversampling setting
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF4);
Wire.write(0x34 + (OSS << 6));
Wire.endTransmission();

// Wait for conversion, delay time dependent on OSS
delay(2 + (3 << OSS));

// Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
Wire.beginTransmission(BMP085_ADDRESS);
Wire.write(0xF6);
Wire.endTransmission();
Wire.requestFrom(BMP085_ADDRESS, 3);

// Wait for data to become available
while (Wire.available() < 3)
;
msb = Wire.read();
lsb = Wire.read();
xlsb = Wire.read();

up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8 - OSS);

return up;
}


Viewing all articles
Browse latest Browse all 172

Trending Articles