DHT11 sensor with wrong values, wanting to add values to the reading that comes from sensor - arduino

I need assistance, I'm new to Arduino and I'm running a DHT11 sensor on NodeMCU 1.0 board, I find on many trends that this sensor is inaccurate mostly on the humidity readings, which brings me to my question, I want to add/subtract a percentage from the reading that comes from the sensor that displays on the HTML page. Could anyone assist, please?
PS I attached the code im using.
include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include "DHT.h"
// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
MDNSResponder mdns;
// Replace with your network details
const char* ssid = "Temperature_Server";
const char* password = "vishaworld.com";
ESP8266WebServer server(80);
String webPage = "";
// DHT Sensor
const int DHTPin = 4;
DHT dht(DHTPin, DHTTYPE);
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];
float h, t, f;
void setup(void) {
IPAddress Ip(10, 10, 10, 10);
IPAddress NMask(255, 255, 255, 0);
WiFi.mode(WIFI_AP);
WiFi.softAPConfig(Ip, Ip, NMask);
WiFi.softAP(ssid, password);
delay(1000);
Serial.begin(9600);
Serial.println("");
// Wait for connection
delay(5000);
Serial.println("");
Serial.print("SoftAP IP address: ");
Serial.println(WiFi.localIP());
dht.begin();
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", []() {
webPage = "";
webPage += "<!DOCTYPE HTML>";
webPage += "<html>";
webPage += "<head></head><body><h1>Temperature and Humidity</h1><h3>Temperature in Celsius: ";
webPage += "<meta http-equiv=\"refresh\" content=\"6\">" ;
webPage += celsiusTemp;
webPage += "*C</h3><h3>Temperature in Fahrenheit: ";
webPage += fahrenheitTemp;
webPage += "*F</h3><h3>Humidity: ";
webPage += humidityTemp;
webPage += "%</h3><h3>";
webPage += "</body></html>";
server.send(200, "text/html", webPage);
});
server.begin();
Serial.println("HTTP server started");
}
void loop(void) {
server.handleClient();
// 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(true);
// 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!");
strcpy(celsiusTemp, "Failed");
strcpy(fahrenheitTemp, "Failed");
strcpy(humidityTemp, "Failed");
}
else {
// Computes temperature values in Celsius + Fahrenheit and Humidity
float hic = dht.computeHeatIndex(t, h, false);
dtostrf(hic, 6, 2, celsiusTemp);
float hif = dht.computeHeatIndex(f, h);
dtostrf(hif, 6, 2, fahrenheitTemp);
dtostrf(h, 6, 2, humidityTemp);
}
delay(2000);
}

I would probably put the code to modify the humidity reading after it is read from the sensor. That way the reading of the humidity from the sensor along with the correction are in the same location hence easy to find.
A snippet from your code:
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// modify the humidity reading to provide a correction to the value
h = h + h * humidityCorrectionPercentage;
Then near the top of the file where the humidity sensor define is located I would make a change something like the following:
// Uncomment one of the lines below for whatever DHT sensor type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
// humidity sensor reading modification to modify the reading to more accurate value
// percentage in decimal form so 10% is 0.10 or 25% is 0.25
// use positive vale to increase the reading and a negative value to decrease the reading.
// specify a value of zero if no modification of the reading is needed.
const float humidityCorrectionPercentage = .10;

Related

Waterproofed water-temperature DS18B20 only returns -127 for degree in Celsius

For a project in university, I have to measure various quality of the water, including the temperature. The temperature sensor is DS18B20, and I use an Arduino Mega board to run the whole show. Individual running with DS18B20 only fails to return any meaningful number. Instead of 25C (or something like that), it returns -127.
The code below is from Dallas Temperature (with small changes, like having delay and removing some comment lines)
// Include the libraries we need
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 48
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("Dallas Temperature IC Control Library Demo");
// Start up the library
sensors.begin();
}
void loop(void)
{
delay(500);
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
delay(2500);
}
This one is actually from the Wiki page of DFRobot (where my sensor is originated from)
#include <OneWire.h>
int DS18S20_Pin = 48; //DS18S20 Signal pin on digital 48
//Temperature chip i/o
OneWire ds(DS18S20_Pin); // on digital pin 48
void setup(void) {
Serial.begin(9600);
}
void loop(void) {
float temperature = getTemp();
Serial.println(temperature);
delay(100); //just here to slow down the output so it is easier to read
}
float getTemp(){
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
if ( !ds.search(addr)) {
//no more sensors on chain, reset search
ds.reset_search();
return -1000;
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return -1000;
}
if ( addr[0] != 0x10 && addr[0] != 0x28) {
Serial.print("Device is not recognized");
return -1000;
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion, with parasite power on at the end
byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for (int i = 0; i < 9; i++ ) { // we need 9 bytes
data[i] = ds.read();
}
ds.reset_search();
byte MSB = data[1];
byte LSB = data[0];
float tempRead = ((MSB << 8) | LSB); //using two's compliment
float TemperatureSum = tempRead / 16;
return TemperatureSum;
}
This specific code returns -1000 every time, which I presume is the equivalence of -127 above.
Edit: The problem was identified as faulty electric wire. Yes, hardware problem.
From the library:
// Error Codes
#define DEVICE_DISCONNECTED_C -127
https://github.com/milesburton/Arduino-Temperature-Control-Library/blob/b34be08d603242bb534e7b717dac48baf60c5113/DallasTemperature.h#L36
So you're device is not connected / not communicating. Check your wiring and your pin numbers.

Arduino not saving to SD correctly

I've built simple project with my daughter that takes two temp readings and writes the to a file on a Micro SD card.
The code is fairly simple (if not a bit messy) and is creating the file, but only ever seems to write the same row of data twice (from the setup()) and then never writes again, although doesn't seem to produce an error.
The code is:
#include <Wire.h> //Required for Realtime Clock
#include "RTClib.h" //Required for Realtime Clock
#include <SPI.h> //Required for SD card reader
#include <SD.h> //Required for SD card reader
#include <dht11.h> //Required for Temp/humidity reader
#define DHTPIN 4 //Pin for temp sensor
#define LEDPIN 7 //Pin for led (status)
#define DHTTYPE DHT11 //define which temp sensor we are using (DHT11)
dht11 DHT11; //Create instance of DHT11 class to read sensor values
File myFile;
String filename;
uint32_t start_min; //Store time the current loop started so we can work out how long we've been running for
RTC_DS3231 RTC; //Create instance of real Time clock class
void setup() {
Serial.begin(9600); //start serial monitor for output
Wire.begin();
//begin the rtc, let us know if it fails
if (! RTC.begin()) {
Serial.println("Couldn't find RTC");
abort();
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
//set RTC time and date to the time the app was compiled
RTC.adjust(DateTime(__DATE__, __TIME__));
//Get the current RTC time and sore it as a unix time
DateTime now = RTC.now();
start_min = now.unixtime();
//Setup Filename
String filename = String(start_min);
int start = filename.length() - 8;
int end = filename.length();
filename = filename.substring(2,10) + ".csv";
Serial.println(filename);
//Write Header row
myFile = SD.open(filename, FILE_WRITE);
if(myFile) {
myFile.println("timestamp|humidity|temperature1|temperature2");
myFile.flush();
myFile.close();
delay(1000);
}
else {
Serial.println("Error opening file");
}
}
void loop() {
//Get current RTC date and time
DateTime now = RTC.now();
//Convert to unix time
uint32_t _now = now.unixtime();
// work out if x mins have passed
if((_now - start_min) > (4*60)) {
//Turn LED on
digitalWrite(LEDPIN,HIGH);
Serial.print("Looped - ");
Serial.print(now.hour());
Serial.print(":");
Serial.println(now.minute());
int chk = DHT11.read(DHTPIN);
myFile = SD.open(filename, FILE_WRITE);
if(myFile) {
String output = String(now.getTimeStr());
output += "|";
output += String((float)DHT11.humidity,2);
output += "|";
output += String((float)DHT11.temperature, 2);
output += "|";
output += String(RTC.getTemperature());
Serial.println(output);
myFile.println(output);
myFile.close();
Serial.println("Write complete");
}
else {
Serial.println("Error opening file");
}
//reset start time
start_min = now.unixtime();
}
delay(5000);
//Turn LED off
digitalWrite(LEDPIN,0);
//wait 90 secs
delay(5000);
}
I'm using an Arduino Uno, a DHT11 for temp/humidity and a DS3231 RTC (also grabbing temp there to).
Once compiled and uploaded. this is the output:
Sketch uses 16798 bytes (52%) of program storage space. Maximum is 32256 bytes.
Global variables use 1290 bytes (62%) of dynamic memory, leaving 758 bytes for local variables. Maximum is 2048 bytes.
any help appreciate

SPI Problem Arduino Mega with pressure sensor MS5803-05BA

I need your help for a project.
I have actually 2 parallel sensors of the type: MS5803-05BA, which supports I2C and SPI connection. One sensor is on I2C bus and one sensor is on SPI. They are both sending to my Arduino Mega. The I2C works perfect with short cables.
Here the datasheet of the sensor:
https://www.amsys.de/downloads/data/MS5803-05BA-AMSYS-datasheet.pdf
For some informations who wants to do the same with I2C. Here you can find a good code. (You can find the other MS580X typs there too). For the communication between the sensor and the Arduino Mega you need an logic converter like this txs0108e, which can be bought with a break out board (you need pull up resistors on the sensor side!):
https://github.com/millerlp/MS5803_05
But to my problem: I have an sensor distance for about 3-5 meters and the I2C connections doesnt work. Yes I can try to fix the pullup resistors but it doesnt worked for me (I have tried some different lower resistors between 3-10kOhm). Therefore I want to switch to the SPI bus.
I have edit the code from https://github.com/millerlp/MS5803_05, https://github.com/vic320/Arduino-MS5803-14BA and https://arduino.stackexchange.com/questions/13720/teensy-spi-and-pressure-sensor.
The File is added. (You have to put the .h and .cpp files in the folder of the arduino code (.spi).
I have problems with the code from the SPI (ccp and header). There is no right communication. I have checked my cables twice. I couldnt find a problem and the connection with the txs0108e works for parallel I2C sensor. Both sensors are working on I2C.
Here is the main code (arduino .spi) for SPI and I2C parallel:
/_____ I N C L U D E S
#include <stdio.h>
#include <math.h>
#include <SPI.h>
#include <Wire.h>
#include "MS5803_05.h"
#include "MS5803_05_SPI.h"
const int miso_port = 50; //SDI
const int mosi_port = 51; //SDO
const int sck_port = 52; //SLCK
const int slaveSelectPin = 53; // CSB
MS_5803 sensor = MS_5803(512);
MS_5803_SPI sensor_spi = MS_5803_SPI(4096, slaveSelectPin);
void setup()
{
pinMode(miso_port, INPUT);
pinMode(mosi_port, OUTPUT);
pinMode(slaveSelectPin, OUTPUT);
pinMode(sck_port, OUTPUT);
Serial.begin(9600);
//SPI BUS
if (sensor_spi.initializeMS_5803_SPI()) {
Serial.println( "MS5803 SPI CRC check OK." );
}
else {
Serial.println( "MS5803 SPI CRC check FAILED!" );
}
//I2C BUS
delay(1000);
if (sensor.initializeMS_5803()) {
Serial.println( "MS5803 I2C CRC check OK." );
}
else {
Serial.println( "MS5803 I2C CRC check FAILED!" );
}
}
void loop()
{
Serial.println("SPI Sensor first pressure [mbar], than temperature[°C]:");
sensor_spi.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor_spi.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor_spi.temperature());
Serial.println("C");
////********************************************************
Serial.println("");
Serial.println("I2C Sensor first pressure [mbar], than temperature[°C]:");
sensor.readSensor();
// Show pressure
Serial.print("Pressure = ");
Serial.print(sensor.pressure());
Serial.println(" mbar");
// Show temperature
Serial.print("Temperature = ");
Serial.print(sensor.temperature());
Serial.println("C");
delay(2000);
}
}
The first connection with SPI is here (.cpp):
#include "MS5803_05_SPI.h"
#include <SPI.h>
#define CMD_RESET 0x1E // ADC reset command
#define CMD_ADC_READ 0x00 // ADC read command
#define CMD_ADC_CONV 0x40 // ADC conversion command
#define CMD_ADC_D1 0x00 // ADC D1 conversion
#define CMD_ADC_D2 0x10 // ADC D2 conversion
#define CMD_ADC_256 0x00 // ADC resolution=256
#define CMD_ADC_512 0x02 // ADC resolution=512
#define CMD_ADC_1024 0x04 // ADC resolution=1024
#define CMD_ADC_2048 0x06 // ADC resolution=2048
#define CMD_ADC_4096 0x08 // ADC resolution=4096
#define CMD_PROM_RD 0xA0 // Prom read command
#define spi_write SPI_MODE3
#define spi_write2 SPI_MODE1
// Create array to hold the 8 sensor calibration coefficients
static unsigned int sensorCoeffs[8]; // unsigned 16-bit integer (0-65535)
// D1 and D2 need to be unsigned 32-bit integers (long 0-4294967295)
static uint32_t D1 = 0; // Store uncompensated pressure value
static uint32_t D2 = 0; // Store uncompensated temperature value
// These three variables are used for the conversion steps
// They should be signed 32-bit integer initially
// i.e. signed long from -2147483648 to 2147483647
static int32_t dT = 0;
static int32_t TEMP = 0;
// These values need to be signed 64 bit integers
// (long long = int64_t)
static int64_t Offset = 0;
static int64_t Sensitivity = 0;
static int64_t T2 = 0;
static int64_t OFF2 = 0;
static int64_t Sens2 = 0;
// Some constants used in calculations below
const uint64_t POW_2_33 = 8589934592ULL; // 2^33 = 8589934592
SPISettings settings_write(500000, MSBFIRST, spi_write);
SPISettings settings_write2(500000, MSBFIRST, spi_write2);
//-------------------------------------------------
// Constructor
MS_5803_SPI::MS_5803_SPI( uint16_t Resolution, uint16_t cs) {
// The argument is the oversampling resolution, which may have values
// of 256, 512, 1024, 2048, or 4096.
_Resolution = Resolution;
//Chip Select
_cs=cs;
}
boolean MS_5803_SPI::initializeMS_5803_SPI(boolean Verbose) {
digitalWrite( _cs, HIGH );
SPI.begin();
// Reset the sensor during startup
resetSensor();
if (Verbose)
{
// Display the oversampling resolution or an error message
if (_Resolution == 256 | _Resolution == 512 | _Resolution == 1024 | _Resolution == 2048 | _Resolution == 4096){
Serial.print("Oversampling setting: ");
Serial.println(_Resolution);
} else {
Serial.println("*******************************************");
Serial.println("Error: specify a valid oversampling value");
Serial.println("Choices are 256, 512, 1024, 2048, or 4096");
Serial.println("*******************************************");
}
}
// Read sensor coefficients
for (int i = 0; i < 8; i++ )
{
SPI.beginTransaction(settings_write2);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low
unsigned int ret;
unsigned int rC = 0;
SPI.transfer(CMD_PROM_RD + i * 2); // send PROM READ command
/*
ret = SPI.transfer(0x00); // send 0 to read the MSB
rC = 256 * ret;
ret = SPI.transfer(0x00); // send 0 to read the LSB
rC = rC + ret;
*/
// send a value of 0 to read the first byte returned:
rC = SPI.transfer( 0x00 );
rC = rC << 8;
rC |= SPI.transfer( 0x00 ); // and the second byte
sensorCoeffs[i] = (rC);
digitalWrite( _cs, HIGH );
delay(3);
}
//SPI.endTransaction(); // interrupt can now be accepted
// The last 4 bits of the 7th coefficient form a CRC error checking code.
unsigned char p_crc = sensorCoeffs[7];
// Use a function to calculate the CRC value
unsigned char n_crc = MS_5803_CRC(sensorCoeffs);
if (Verbose) {
for (int i = 0; i < 8; i++ )
{
// Print out coefficients
Serial.print("C");
Serial.print(i);
Serial.print(" = ");
Serial.println(sensorCoeffs[i]);
delay(10);
}
Serial.print("p_crc: ");
Serial.println(p_crc);
Serial.print("n_crc: ");
Serial.println(n_crc);
}
// If the CRC value doesn't match the sensor's CRC value, then the
// connection can't be trusted. Check your wiring.
if (p_crc != n_crc) {
return false;
}
// Otherwise, return true when everything checks out OK.
return true;
}
// Sends a power on reset command to the sensor.
void MS_5803_SPI::resetSensor() {
SPI.beginTransaction(settings_write);
digitalWrite(_cs, LOW); //csb_lo(); // pull CSB low to start the command
SPI.transfer(CMD_RESET); // send reset sequence
delay(3); // wait for the reset sequence timing delay(3)
digitalWrite(_cs, HIGH); //csb_hi(); // pull CSB high to finish the command
SPI.endTransaction(); // interrupt can now be accepted
}
The Code can be downloaded at: https://forum.arduino.cc/index.php?topic=670661.0
There you can find the schematic and output picture too.
Thanks a lot :).

Error in sending data to cloud server and arduino lagging

The code im working on, is suppose to show temperature, humidity and able to take and show heart rate on the lcd. After data is shown, it will send data to "ThingSpeak". After sending, there will be a http code error -401 which is ok as it can only send data very 15 sec. But after awhile, it will change it error http code -301... and then it will hang. Another issue is when i try to use the temperature sensor with the heart rate sensor, the lcd will hang and it will not work till i reset.
#include "ThingSpeak.h"
#include "SPI.h"
#include "DHT.h"
#include <Ethernet.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(10, 9, 5, 4, 3, 2); //numbers of interface pins
#define redLED 8
int sensorPin = A8;
float tempC;
#define DHTPIN 6
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
float h;
#define USE_ARDUINO_INTERRUPTS true // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h> // Includes the PulseSensorPlayground Library.
// Variables
const int PulseWire = A9; // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int blinkPin = 22; // The on-board Arduino LED, close to PIN 13.
int Threshold = 550; // Determine which Signal to "count as a beat" and which to ignore.
PulseSensorPlayground pulseSensor; // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
unsigned long myChannelNumber = ;
const char * myWriteAPIKey = "";
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(172, 17, 171, 199);
IPAddress myDns(172, 17, 171, 254);
float get_temperature(int pin)
{
float temperature = analogRead(pin); // Calculate the temperature based on the reading and send that value back
float voltage = temperature * 5.0;
voltage = voltage / 1024.0;
return ((voltage - 0.5) * 100);
}
EthernetClient client;
void setup()
{
lcd.begin(16, 2);
pinMode(redLED, OUTPUT);
pulseSensor.analogInput(PulseWire);
pulseSensor.blinkOnPulse(blinkPin); //auto-magically blink Arduino's LED with heartbeat.
pulseSensor.setThreshold(Threshold);
pulseSensor.begin();
dht.begin();
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
Serial.println("Initialize Ethernet with DHCP:");
if (Ethernet.begin(mac) == 0)
{
Serial.println("Failed to configure Ethernet using DHCP");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware)
{
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true)
{
delay(10); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF)
{
Serial.println("Ethernet cable is not connected.");
}
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip, myDns);
}
else
{
Serial.print(" DHCP assigned IP ");
Serial.println(Ethernet.localIP());
}
// give the Ethernet shield a second to initialize:
delay(1000);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop()
{
h = dht.readHumidity();
{
tempC = get_temperature(sensorPin);
}
if (tempC < 31)
{
lcd.setCursor(0, 0);
lcd.print(tempC);
lcd.print(" "); //print the temp
lcd.print((char)223); // to get ° symbol
lcd.print("C");
lcd.print(" ");
lcd.print(h);
lcd.print("%");
delay(750);
}
else if (tempC > 31)
{
lcd.setCursor(0, 0);
lcd.print(tempC);
lcd.print(" "); //print the temp
lcd.print((char)223); // to get ° symbol
lcd.print("C");
lcd.print(" ");
lcd.print(h);
lcd.print("%");
delay(750);
}
int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int".
// "myBPM" hold this BPM value now.
if (pulseSensor.sawStartOfBeat())
{
lcd.setCursor(0,1);
lcd.print("BPM:"); // Print phrase "BPM: "
lcd.println(myBPM); // Print the value inside of myBPM.
lcd.print(" ");
delay(100);
}
// Write to ThingSpeak channel.
ThingSpeak.setField(1, tempC);
ThingSpeak.setField(2, h);
ThingSpeak.setField(3, myBPM);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if (x == 200)
{
Serial.println("Channel update successful.");
}
else
{
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}

Porting Arduino Sketch from Ethernet to Wifi

I have a sketch working with an Arduino Uno and an Ethernet Shield - and it's working fine. Now I've gotten my hands on some Arduino Uno WiFi, and I want to port the sketch from ethernet to wifi - but I've run into a wall now. Most of the guide/FAQ/help I can find is for a WiFi Shield, and not a WiFi Arduino, so I'm stuck here.
Below is my (original Ethernet) code. I can post my somewhat modified Wifi code, but I can't even compile it without errors.
// Hartmann fugtighedsmåler v 0.1
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
#include <Ethernet.h>
#include <SPI.h>
#include <DHT.h>
#define DHTPIN 2 // Siger sig selv
#define DHTTYPE DHT11 // Typen af sensor.
float h = 0;
float t = 0;
byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02}; // Macadresse på kortet
IPAddress server(10,16,9,229); // Server adressen på SQL'en
EthernetClient client;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
Ethernet.begin(mac);
dht.begin();
}
void loop() {
readTempHum();
delay(300000); // Loop timer i millis - 5 minutter
}
void get_request(float t, float h) {
Serial.println("Connecting to Client...");
if (client.connect(server, 10080)) {
Serial.println("--> connection ok\n");
client.print("GET /test.php?");
// Placering af PHP script til upload til DB
client.print("t="); // Temp
client.print(t);
client.print("&h="); // Fugtighed
client.print(h);
client.println(" HTTP/1.1");
client.print( "Host: " );
client.println(server);
client.println("Connection: close");
client.println();
client.println();
client.stop();
Serial.println("--> finished transmission\n");
} else {
Serial.println("--> connection failed\n");
}
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
{
Serial.print("Humidity: ");
Serial.print(h);
Serial.print("%\t");
Serial.print("Temperature:");
Serial.print(t);
Serial.println("*C");
get_request(t,h);
}
}
I've also posted this on the Arduino Forum. I'm sorry if you see my double-post, and I'll post the solution to my problem here as well.
New sketch:
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT);
delay(10000);
}
void loop() {
readTempHum();
// doRequest(connector, server, resource, method);
delay(300000);
}
void doRequest(const char* conn, const char* server, const char* command, const char* method, float t, float h){
CiaoData data = Ciao.write(conn, server, command, method);
}
void readTempHum() {
h = dht.readHumidity();
t = dht.readTemperature();
const char* connector = "rest";
const char* server = "10.16.9.229";
const char* method = "GET";
const char* resource = "/test.php?t=";
{
doRequest(connector, server, resource, method,t,h);
}
}
Now, I've ran into a new problem. The value from the sensor (t and h) are supposed to be output in the HTTP/GET command like this:
test.php?t=1&h=2
But I can't seem to make that work. If I try to define the resource as this
const char* resource = "/test.php?t="+t+"&h="+h;
I get an error (obviously), but if I try to declare it as a string, I the same error again.
Error:
HumidSQL3_Wifi_master:24: error: invalid operands of types 'const char [13]' and 'float' to binary 'operator+'
const char* resource = "/test.php?t="+t+"&h="+h;
Now, I hope that some of you could help me out a bit here :/
If it is the Arduino.org Arduino UNO WiFi Developer Edition, then use WiFi Link with UNO WiFi Serial1 library
Okay - so I made it work. I had to start from scratch, and with the help from Juraj (I'll accept your answer as well) it works now.
Below are the final sketch ("final", as the DHT11 sensor only were for testing purpose, as a proof-of-concept)
// Hartmann fugtighedsmåler v 0.2.2
// Lavet af Jan Andreasen
// Skriver til DB på FDKTO517
// WiFi udgave, testversion
#include <Wire.h>
#include <UnoWiFiDevEd.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT11
#define CONNECTOR "rest"
#define SERVER_ADDR "10.16.9.229"
float h = 0;
float t = 0;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Ciao.begin();
dht.begin();
pinMode(2, INPUT); // I'm not sure if this is required, just saw it now
delay(10000); // A 10 second delay from start to initialization
}
void loop() {
readTempHum();
delay(300000); // A 5 minute delay between measurements
}
void readTempHum() {
h = dht.readHumidity(); // Reads the humidity from sensor
t = dht.readTemperature(); // Reads the temperature from sensor
String uri = "/test.php?t="; // URL to the PHP-file
uri += t; // Insert the T-value
uri +="&h=";
uri += h; // Insert the H-value
CiaoData data = Ciao.write(CONNECTOR, SERVER_ADDR, uri); // Make a basic HTTP request to the specified server using REST and the URL specified above
}
Maybe not the prettiest code you've seen, however, it works now.

Resources