client connect POST problem with analogRead

Hi

I have have cobbled together a script to make a HTTP post to a local webserver every 10 seconds with the reading from analogue input A0.

The script verifies ok, but when I upload to my Mega 2560 I get no serial output and no POST.

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

byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01 }; // RESERVED MAC ADDRESS
EthernetClient client;

int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
String postdata;

void setup() {
  Serial.begin(9600);

  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
  }

  pinMode(ledPin, OUTPUT);
}

void loop()
{

  postdata = "sensorpina0=" + analogRead(sensorPin);

  Serial.print(postdata);
  if (client.connect("10.33.67.138", 80))
  {
    client.println("POST /api/test.html HTTP/1.1");
    client.println("Host: 10.33.67.138");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.println(postdata.length());
    client.println();
    client.print(postdata);
  }

  if (client.connected())
  {
    client.stop();
  }

  // Wait before posting again
  delay(10000);
}

If I change this line:
postdata = "sensorpina0=" + analogRead(sensorPin);

To something like this, removing the analogRead,...
postdata = "sensorpina0=357";

the POST works and so does the serial.print. But I cannot get the value from analogRead to work.

Can anyone help?

You can't add a String and an int ( analogRead(sensorPin) ) together. You need to convert the analogRead(sensorPin) to a String first; String(analogRead(sensorPin))

Maybe ditch the String class all together:

char buffer[32];
sprintf( buffer, "sensorpina0=%d", analogRead(sensorPin));
Serial.println(buffer);

mistergreen:
String(analogRead(sensorPin))

Just what I was missing - thank you :slight_smile: