I've been trying to get the BME680 to work and for the most part it seems to be working great. I do have one issue and that is with the gas sensor.
I write all the contents of the BME680 out to a webpage and all of the other values remain consistent.
Temperature: 77.29 *F
Humidity: 59.12 %
Pressure: 1010.45 millibars
Air Quality: 3.24 KOhms
On every refresh of the page the values for Temperature, Humidity, and Pressure all remain close to their values. They correct for a little while and show the minor fluctuations correctly. When it starts to rain the pressure goes down, the humidity goes up, etc... The issue is the Gas Sensor. On ever refresh the value keeps increasing. Regardless of whether I refresh it once per minute or per hour it keeps increasing. I'm clearly doing something wrong.
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <WiFi101.h>
#include <WiFiUdp.h>
#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/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 keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(80);
#define SEALEVELPRESSURE_HPA (1023.03)
Adafruit_BME680 bme; // I2C
void setup() {
//Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); // set the LED pin mode
bme.begin();
// Set up oversampling and filter initialization
bme.setTemperatureOversampling(BME680_OS_8X);
bme.setHumidityOversampling(BME680_OS_2X);
bme.setPressureOversampling(BME680_OS_4X);
bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
bme.setGasHeater(320, 150); // 320*C for 150 ms
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
//Serial.println("WiFi shield not present");
while (true); // don't continue
}
// attempt to connect to WiFi network:
while ( status != WL_CONNECTED) {
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the web server on port 80
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
//Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
//Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
if (! bme.performReading()) {
client.print("Failed to perform reading :(<br>");
return;
}
// the current weather condidtions
client.print("Temperature: ");
client.print((bme.temperature * 9/5) + 32);
client.print(" *F<br>");
client.print("Humidity: ");
client.print(bme.humidity);
client.print(" %<br>");
client.print("Pressure: ");
client.print(bme.pressure / 100.0);
client.print(" millibars<br>");
client.print("Air Quality: ");
client.print(bme.gas_resistance / 1000.0);
client.print(" KOhms<br>");
delay(2000);
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
}
else { // if you got a newline, then clear currentLine:
currentLine = "";
}
}
else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// close the connection:
client.stop();
//Serial.println("client disonnected");
}
}
I see two important points. Two for the beginning. Missing the ambient temperature and the sea-level.
Default ambient is: 25deg.C
Default sea-level is: 500 meter
Add this with correct values to your code. Then you have todo some automatic calibrations after burn in time. My own experience is that 2 weeks 24/7 is needed to get the sensor much old as needed. Next step look in the BOSCH original library and example code. Then start over again. Currently i'm rewriting the driver for the BME and BMP series for Tasmota (github). Lot's of work believe me. And i'm from the physics and chemical side. So some research helps always.
Related
I'm trying to send data from my Wemos to Node-red via MQTT. I created a nested object I want to send to MQTT. From the serial of Arduino IDE the output is this (and that's what I want):
[{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1}]
It seems all correct but the debug node show nothing. what am I missing?
Here's the code:
//LIBRARY
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include<Wire.h>
//JSON Array and mqtt data
#include <ArduinoJson.h>
#define MQTT_BUFFER 512
//MPU
const int MPU = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ;
// IP adress Raspberry Pi
const char* mqttServer = "raspi-hyperink";
const int mqttPort = 1883;
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
//MPU
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
//SERIAL
Serial.begin(115200);
// WiFiManager
// Local intialization.
WiFiManager wifiManager;
// Uncomment and run it once, if you want to erase all the stored information
//wifiManager.resetSettings();
// set custom ip for portal
//wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
// fetches ssid and pass from eeprom and tries to connect
// if it does not connect it starts an access point with the specified name
// here "AutoConnectAP"
// and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("AutoConnectAP");
// if you get here you have connected to the WiFi
Serial.println("Connected.");
//server.begin();
//CLIENT
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
server.begin();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
//RECONNECT FUNCTION
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("esp8266")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "hello world");
// ... and resubscribe
//client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop(){
WiFiClient(espClient) = server.available(); // Listen for incoming clients
if (espClient) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (espClient.connected()) { // loop while the client's connected
if (espClient.available()) { // if there's bytes to read from the client,
char c = espClient.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// Web Page Heading
client.println("<body><h1>ESP8266 Web Server</h1>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
espClient.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
if (!client.connected()) {
reconnect();
}
client.loop();
//compute the required size
const size_t CAPACITY = JSON_ARRAY_SIZE(5) + 5*JSON_OBJECT_SIZE(3);
//allocate the memory for the document
StaticJsonDocument<CAPACITY> doc;
//Create an empty array
JsonArray arr = doc.to<JsonArray>();
//definiamo quanti campioni registrare prima di inviarli tramite mqtt
for (int i=0; i<5; i++){
//MPU reading
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
//Create JSON Array
JsonObject obj = doc.createNestedObject();
obj["AcX"] = AcX;
obj["AcY"] = AcY;
obj["AcZ"] = AcZ;
delay(3000);
}
//MQTT PUBLISHING JSON PACKAGE
char mqttData[MQTT_BUFFER];
serializeJson(doc, mqttData);
Serial.println(mqttData);
client.publish("esp8266", mqttData);
//client.subscribe("esp8266");
client.subscribe("esp8266");
delay(10000);
//Inserire un ciclo WHILE dove
//mentre il wifi è connesso invia i dati all'mqtt
//altrimenti li salva e basta
}
This is the mqtt node
Node-red debug
Normally debug should show you what you are publishing to your MQTT broker. As simple troubleshooting I would start moving backwards:
Replace the NodeRED client by any other one. Is the problem still there? Very likely it will be meaning that the problem is not on the MQTT client.
So we move a step "backwards"
Replace the MQTT Broker, use another one from the internet, one that you know works fine. The problem, is it still there? If it's not there, voilà, you found the problem (the broker), if it's still there, it means that the issue is on client publishing your msgs. It might be the msg itself.
So we move a step "backwards"
Replace you msg by another one, much simpler. Does it work ?
You get the idea :)
Hi I'm using arduino uno and wifi shield. I'm trying to create using the wifi shield to connect to a servo motor through webserver. To be honest I dont really know what im doing. This code is able to control the servo motor once and the whole system is shutdown.
can someone look into my codes and see what is wrong? If can I hope the code is able to control the servo multiple time without stopping.
#include <SPI.h>
#include <WiFi.h>
#include <Servo.h>
char ssid[] = "wifi"; // your network SSID (name)
char pass[] = "asdfghjkl"; // your network password
int keyIndex = 0;
// your network key Index number (needed only for WEP)
Servo myservo;
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup() {
Serial.begin(9600); // initialize serial communication
myservo.attach(9);
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true); // don't continue
}
String fv = WiFi.firmwareVersion();
if (fv != "1.1.0") {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(1000);
}
server.begin(); // start the web server on port 80
printWifiStatus(); // you're connected now, so print out the status
}
void loop() {
WiFiClient client = server.available(); // listen for incoming clients
if (client) { // if you get a client,
Serial.println("new client"); // print a message out the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println();
// the content of the HTTP response follows the header:
client.print("Click here turn the Open the door <br>");
client.print("Click here turn the Close the door <br>");
// The HTTP response ends with another blank line:
client.println();
// break out of the while loop:
break;
} else { // if you got a newline, then clear currentLine:
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
// Check to see if the client request was "GET /H" or "GET /L":
if (currentLine.endsWith("GET /H")) {
// scale it to use it with the servo (value between 0 and 180)
myservo.write(800); // sets the servo position according to the scaled value
delay(15); // GET /H turns the LED on
}
if (currentLine.endsWith("GET /L")) {
// scale it to use it with the servo (value between 0 and 180)
myservo.write(2500); // sets the servo position according to the scaled value
delay(15); // GET /L turns the LED off
}
}
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield'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");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
Using the ethernet WebServer example code, I've got my arduino to host a website stored on an SD card. The website uses jquery to post the position of the mouse in the webbrowser back to the arduino. I would ultimately like to use this info to control a servo motor, however, the problem I have is that the client.stop line in each iteration of the void loop causes a large lag time in between when the mouse moves and when the arduino gets the information.
Is there a way to make this code only use the execute the stop.client line when the mouse stops moving. So effectively when there no information being sent from the to the arduino via the post method?
Here is my code.
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
String POST = "";
int count = 0;
const int chipSelect = 4;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,178,30);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
Serial.setTimeout(10);
//start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
client.setTimeout(1);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
//SD card stuff
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
return;
}
Serial.println("card initialized.");
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
String POST = "";
while(client.available()){
c = client.read();
// save the variables somewhere
POST += c;
}
if(POST != ""){
Serial.println(POST);
}
//load html/css/js for website only once
if (count <= 0){
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
//client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
File dataFile = SD.open("site.txt");
// if the file is available, write to it:
if (dataFile) {
while (dataFile.available()) {
//Serial.write(dataFile.read());
client.write(dataFile.read());
}
dataFile.close();
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening site.txt");
}
}
//count = 1;
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
if (count == 0){
delay(500);
}
else{
delay(1);
}
count=1;
// close the connection:
client.stop();
Serial.println("client disonnected");
}
}
yes, is possible but realy hard as you have to implement HTTP\1.1, also this will reamin slow as for every mouse position, browser have to send a full HTTP request, arduino read and intepretate it.
Best solution is to use websocket (there are already some serbsocket server lybrary for arduino), once a websocket is setted-up, you have a two way communication exactly like a Serial!
I was trying to upload a Xively feed with an Arduino connected via an Arduino GSM shield.
Xively does not publish any specific example for an Arduino GSM shield. I tried to use the Arduino GSM Pachube Client library changing "pachube.com" in "xively.com", but it did not work. It seems that my GSM shield is able to connect but cannot put the data to the server.
In my example I created a device called "Arduino GSM" with just one channel called "sensor1". In the request log I cannot read any request incoming, although the serial monitor shows that a connection with the server occurs.
This is the code I tried:
// Original GSM Pachube client modified for Xively
// Changes: pachube.com -> xively.com
// inserted APIKEY, FEEDID, USERAGENT
// inserted GPRS_APN, login, password
/*GSM Pachube client
This sketch connects an analog sensor to Pachube (http://www.pachube.com)
using a Telefonica GSM/GPRS shield.
This example has been updated to use version 2.0 of the Pachube.com API.
To make it work, create a feed with a datastream, and give it the ID
sensor1. Or change the code below to match your feed.
Circuit:
* Analog sensor attached to analog in 0
* GSM shield attached to an Arduino
* SIM card with a data plan
created 4 March 2012
by Tom Igoe
and adapted for GSM shield by David Del Peral
This code is in the public domain.
http://arduino.cc/en/Tutorial/GSMExamplesPachubeClient
*/
// libraries
#include <GSM.h>
// Pachube Client data -> changed in Xively Data
#define APIKEY "myapikey" // replace your pachube api key here
#define FEEDID 111111111 // replace your feed ID
#define USERAGENT "Arduino GSM" // user agent is the project name
// PIN Number
#define PINNUMBER ""
// APN data
#define GPRS_APN "WINDBIZ WEB" // replace your GPRS APN
#define GPRS_LOGIN "" // replace with your GPRS login
#define GPRS_PASSWORD "" // replace with your GPRS password
// initialize the library instance:
GSMClient client;
GPRS gprs;
GSM gsmAccess;
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
// IPAddress server(216,52,233,121); // numeric IP for api.pachube.com
char server[] = "api.xively.com"; // name address for pachube API
unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds
boolean lastConnected = false; // state of the connection last time through the main loop
const unsigned long postingInterval = 10*1000; //delay between updates to Pachube.com
void setup()
{
// initialize serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while(notConnected)
{
if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
}
void loop()
{
// read the analog sensor:
int sensorReading = analogRead(A0);
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available())
{
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected)
{
client.stop();
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && ((millis() - lastConnectionTime) > postingInterval))
{
sendData(sensorReading);
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
/*
This method makes a HTTP connection to the server.
*/
void sendData(int thisData)
{
// if there's a successful connection:
if (client.connect(server, 80))
{
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.print("Host: api.xively.com\n");
client.print("X-ApiKey: ");
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.print("Content-Type: text/csv\n");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("sensor1,");
client.println(thisData);
}
else
{
// if you couldn't make a connection:
Serial.println("connection failed");
Serial.println();
Serial.println("disconnecting.");
client.stop();
}
// note the time that the connection was made or attempted
lastConnectionTime = millis();
}
/*
This method calculates the number of digits in the
sensor reading. Since each digit of the ASCII decimal
representation is a byte, the number of digits equals
the number of bytes.
*/
int getLength(int someValue)
{
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0)
{
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
I'm trying to connect a DHT22 sensor to the Pachube online service.
I am understanding the code and have everything wired up correctly but I get this error:
DHT22 Library Demo
Requesting data at 6335
Sync Timeout
What does sync timeout mean? Is is a network problem?
How could I fix this?
Here is my code anyway:
/* Feed temperature and humidity to Pachube.
Based on the following examples:
Sample code from nethoncho's DHT22 library:
https://github.com/nethoncho/Arduino-DHT22
Tom Igoe's PachubeClient:
http://arduino.cc/en/Tutorial/PachubeCient
*/
#include <DHT22.h>
#include <SPI.h>
#include <Ethernet.h>
// Data wire is plugged into port 7 on the Arduino
// Connect a 4.7K resistor between VCC and the data pin (strong pullup)
#define DHT22_PIN 2
// Setup a DHT22 instance
DHT22 myDHT22(DHT22_PIN);
static unsigned long lWaitMillis;
// assign a MAC address for the ethernet controller.
// fill in your address here:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
// assign an IP address for the controller:
byte ip[] = {
192,168,0,30 };
byte gateway[] = {
192,168,1,2};
byte subnet[] = {
255, 255, 255, 0 };
// The address of the server you want to connect to (pachube.com):
byte server[] = {
173,203,98,29 };
// initialize the library instance:
Client client(server, 80);
boolean lastConnected = false; // state of the connection last time through the main loop
const long postingInterval = 180000; //delay between updates to Pachube.com
int backoff = 0;
void setup(void)
{
// start serial port
Serial.begin(9600);
Serial.println("DHT22 Library Demo");
// start the ethernet connection:
Ethernet.begin(mac, ip);
// give the ethernet module time to boot up:
delay(1000);
lWaitMillis = millis() + 5000;
}
void loop() {
// if there's incoming data from the net connection.
// send it out the serial port. This is for debugging
// purposes only:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if there's no net connection, but there was one last time
// through the loop, then stop the client:
if (!client.connected() && lastConnected) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
while(client.status() != 0) {
Serial.print("Client status: ");
Serial.println(client.status());
delay(5);
}
}
// if you're not connected, and ten seconds have passed since
// your last connection, then connect again and send data:
if(!client.connected() && (long)( millis() - lWaitMillis ) >= 0 ) {
if (readData()) {
int temp = myDHT22.getTemperatureC();
int humidity = myDHT22.getHumidity() + .5;
sendData(temp, humidity);
}
lWaitMillis += postingInterval;
if (lWaitMillis < millis()) {
lWaitMillis = millis() + postingInterval;
}
Serial.print("Next attempt at ");
Serial.println(lWaitMillis);
Serial.println();
}
// store the state of the connection for next time through
// the loop:
lastConnected = client.connected();
}
boolean readData()
{
DHT22_ERROR_t errorCode;
Serial.print("Requesting data at ");
Serial.println(millis());
errorCode = myDHT22.readData();
switch(errorCode)
{
case DHT_ERROR_NONE:
Serial.print("Got Data ");
Serial.print(myDHT22.getTemperatureC());
Serial.print("C ");
Serial.print(myDHT22.getHumidity());
Serial.println("%");
return true;
break;
case DHT_ERROR_CHECKSUM:
Serial.print("check sum error ");
Serial.print(myDHT22.getTemperatureC());
Serial.print("C ");
Serial.print(myDHT22.getHumidity());
Serial.println("%");
break;
case DHT_BUS_HUNG:
Serial.println("BUS Hung ");
break;
case DHT_ERROR_NOT_PRESENT:
Serial.println("Not Present ");
break;
case DHT_ERROR_ACK_TOO_LONG:
Serial.println("ACK time out ");
break;
case DHT_ERROR_SYNC_TIMEOUT:
Serial.println("Sync Timeout ");
break;
case DHT_ERROR_DATA_TIMEOUT:
Serial.println("Data Timeout ");
break;
case DHT_ERROR_TOOQUICK:
Serial.println("Polled too quick ");
break;
}
return false;
}
// this method makes a HTTP connection to the server:
void sendData(int temp, int humidity) {
// if there's a successful connection:
if (client.connect()) {
backoff = 0;
Serial.println("connecting...");
// send the HTTP PUT request.
// fill in your feed address here:
client.print("PUT /v2/feeds/36800.csv HTTP/1.1\n");
client.print("Host: api.pachube.com\n");
// fill in your Pachube API key here:
client.print("X-PachubeApiKey: a6714b6a217827edadfd003843c03c259a08add554eda3871b844612eddc6819\n");
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
int thisLength = 2 + getLength(temp) + 2 + 2 + getLength(humidity);
client.println(thisLength, DEC);
// last pieces of the HTTP PUT request:
client.print("Content-Type: text/csv\n");
client.println("Connection: close\n");
// here's the actual content of the PUT request:
client.print(0, DEC);
client.print(",");
client.println(temp, DEC);
client.print(1, DEC);
client.print(",");
client.println(humidity, DEC);
}
else {
// if you couldn't make a connection:
Serial.println("connection failed, resetting.");
Ethernet.begin(mac, ip);
delay(1000);
client.stop();
delay(1000);
}
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
int getLength(int someValue) {
// there's at least one byte:
int digits = 1;
// continually divide the value by ten,
// adding one to the digit count for each
// time you divide, until you're at 0:
int dividend = someValue /10;
while (dividend > 0) {
dividend = dividend /10;
digits++;
}
// return the number of digits:
return digits;
}
You're running into DHT_ERROR_SYNC_TIMEOUT sensor error, that means that the DHT sensor is running into some sync problem, I guess.
What arduino are you using? Is your board's frequence 8 or 16Mhz?
Give a try to the edit described here, too. If it still doesn't work, I would try using sensor itself (i.e. without connecting to patchube) with some test sketch you can easily find for DHT22, just to make sure the sensor is working properly.
I had similar problem when using Arduino Nano v3.0 + ENC28J60 Ethernet shield. I tried to connect RF receiver to digital PIN #2 but this never worked.
Then I used different pin for the RF module (PIN #4 in my case) and everything worked fine.