Problem converting from Xively to ThingSpeak

Hello,

I have a program that ran great when sending the data to Xively.

Now that i want to post it to ThingSpeak everything works except the level indication from the ultrasonic distance sensor. I have some math in the equation to display the level in my tank. Max level is 275 gallons. The data being sent to Thingspeak alternates between the actual distance (which right now is around 196 gallons) and the max level of 275.

Its easier to understand by looking at my ThingSpeak channel below.

Click here to see the ThingSpeak data:

I also have a DHT connected and the data being sent to ThingSpeak works great.

Here is the code I am trying to use:

#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <dht.h>

//Set log period
#define LOG_PERIOD 15000  //Logging period in milliseconds, recommended value 15000-60000.
#define MAX_PERIOD 60000  //Maximum logging period without modifying this sketch
#define DHT22_PIN 3       //DI pin with sensor data
#define trigPin 6
#define echoPin 7

dht DHT;

// Local Network Settings
byte mac[]     = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network

// ThingSpeak Settings
byte server[]  = { 184, 106, 153, 149 }; // IP Address for the ThingSpeak API
String writeAPIKey = "WDSIVUV36PZVW0";    // Write API Key for a ThingSpeak Channel
const int updateInterval = 15000;        // Time interval in milliseconds to update ThingSpeak   
EthernetClient client;

// Variable Setup
long lastConnectionTime = 0; 
boolean lastConnected = false;
int resetCounter = 0;

//Variable declaration
int H;        //variable for humidity value
int T;    //variable for temperature value, sensor output in Celsius
int OilLevel;

unsigned long previousMillis;  //variable for time measurement

void setup()
{
  Ethernet.begin(mac);
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  

//--------------Begin Level loop--------------//
  int duration, distance, X;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  X = 275-(((duration/2) / 29.1) / 0.40727272); // Divide by 0.40727272 becasue 0-44" (tank height) equals
                                         // 0-112cm (inches to CM). 112 CM divided by 275 Gallons. 

//---------------End Level loop--------------//


//--------------Begin DHT22 loop--------------//
  unsigned long currentMillis = millis();
  
  if(currentMillis - previousMillis > LOG_PERIOD){
    previousMillis = currentMillis;
    int chk = DHT.read22(DHT22_PIN); //Change for DHT type
    H = DHT.humidity;
    T = ((DHT.temperature*9)/5)+32;
  }
   
  
//---------------End DHT22 loop--------------//

   String Humidity = String(int(H), DEC);
   String Temperature = String(int(T), DEC);
   String X1 = String(int(X), DEC);

   
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  
  // Disconnect from ThingSpeak
  if (!client.connected() && lastConnected)
  {
    Serial.println();
    Serial.println("...disconnected.");
    Serial.println();
    
    client.stop();
  }
  
  // Update ThingSpeak
  if(!client.connected() && (millis() - lastConnectionTime > updateInterval))
  {
    updateThingSpeak("field1="+Humidity+"&field2="+Temperature+"&field3="+X1);
  }
  
  lastConnected = client.connected();
}

void updateThingSpeak(String tsData)
{
 if(client.connect(server, 80)>0)
  { 
    Serial.println("Connected to ThingSpeak...");
    Serial.println();
        
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");

    client.print(tsData);
    
    lastConnectionTime = millis();
    
    resetCounter = 0;
    
  }
  Serial.println(analogRead(A0));
}
  delayMicroseconds(1000);

That's an awfully long delay to send a pulse.

   String Humidity = String(int(H), DEC);
   String Temperature = String(int(T), DEC);
   String X1 = String(int(X), DEC);

Is there a real need to cast an int to an int?

    client.print("\n\n");

Isn't that supposed to be \r\n?

    client.print(tsData);

Isn't that supposed to be println()?

PaulS:

  delayMicroseconds(1000);

Its a microsecond delay. Its what I've always used without any problems in the past.

   String Humidity = String(int(H), DEC);
   String Temperature = String(int(T), DEC);
   String X1 = String(int(X), DEC);

Isn't the above changing an int to a string value?

client.print("\n\n");
&
client.print(tsData);

I don't understand all the lines of code that ThingSpeak needs. This is based off of their example from the website.

Isn't the above changing an int to a string value?

Not even close.

First, it is creating THREE String instance. Second, the value is ALREADY an int. There is no reason to cast the int to an int.

String crap(X);

Creates ONE String instance that in the end is exactly the same as your code, but pisses away fewer resources. There really is no excuse for creating a String, then copying it and assigning it to another String.

After fiddling with it for a few hours this weekend I figured it out.

None of PaulS's suggestions helped.

I started playing around with the timing of the ultrasonic pulse.

Although Paul pointed out that it was a long delay. I turned it down to see if it made a difference; it made it worse. But, based off of that, I turned it up to 5000 micros and all of a sudden it worked. No problems at all. The data steadied out, right around the calculated 195 gallons.

Here is the code I am currently using. You will see small difference elsewhere besides the Microsecond delay, since it did save space, I left the changes.

#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include <dht.h>

//Set log period
#define LOG_PERIOD 15000  //Logging period in milliseconds, recommended value 15000-60000.
#define MAX_PERIOD 60000  //Maximum logging period without modifying this sketch
#define DHT22_PIN 3       //DI pin with sensor data
#define trigPin 6
#define echoPin 7

dht DHT;

// Local Network Settings
byte mac[]     = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network

// ThingSpeak Settings
byte server[]  = { 184, 106, 153, 149 }; // IP Address for the ThingSpeak API
String writeAPIKey = "WDSIVUVJPZVW0";    // Write API Key for a ThingSpeak Channel
const int updateInterval = 15000;        // Time interval in milliseconds to update ThingSpeak   
EthernetClient client;

// Variable Setup
long lastConnectionTime = 0; 
boolean lastConnected = false;
int resetCounter = 0;

int H, T;
int duration, distance, X;

unsigned long previousMillis;  //variable for time measurement

void setup()
{
  Ethernet.begin(mac);
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  //--------------Begin Level loop--------------//
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(5000);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  X = 275-(((duration/2) / 29.1) / 0.40727272); // Divide by 0.40727272 becasue 0-44" (tank height) equals
                                         // 0-112cm (inches to CM). 112 CM divided by 275 Gallons. 
//---------------End Level loop--------------//
//--------------Begin DHT22 loop--------------//
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis > LOG_PERIOD){
    previousMillis = currentMillis;
    int chk = DHT.read22(DHT22_PIN); //Change for DHT type
    H = DHT.humidity;
    T = ((DHT.temperature*9)/5)+32;
  }
//---------------End DHT22 loop--------------//

   
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  
  // Disconnect from ThingSpeak
  if (!client.connected() && lastConnected)
  {
    Serial.println();
    Serial.println("...disconnected.");
    Serial.println();
    
    client.stop();
  }
  // Update ThingSpeak
  if(!client.connected() && (millis() - lastConnectionTime > updateInterval))
  {
    updateThingSpeak("field1="+String(H)+"&field2="+String(T)+"&field3="+String(X));
  }
  lastConnected = client.connected();
}
void updateThingSpeak(String tsData)
{
 if(client.connect(server, 80)>0)
  { 
    Serial.println("Connected to ThingSpeak...");
    Serial.println();
        
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
    client.print("Content-Type: application/x-www-form-urlencoded\n");
    client.print("Content-Length: ");
    client.print(tsData.length());
    client.print("\n\n");

    client.print(tsData);
    
    lastConnectionTime = millis();
    
    resetCounter = 0; 
  } 
}