Category Archives: arduino

php built in webserver not reacheable with ip:port via network cable

I have been trying to make things work for a while now but I did not succeed. I also have done a lot of research, in vain. I really hope that someone is able to help me find the root cause of that issue:

I am trying to connect to my localhost:8000 from another computer (which actually is an arduino ethernet but that doesn't make a difference I guess) by using an ip address. I set the ip address manually in network settings (192.168.1.5).

funny enough, the connection from the external device to 192.168.1.5:80 (which is the normal apache server) works, hence the problem cannot be IP-based.

However, the connection to the php built in webserver running on localhost:8000 does not work. I am trying to access it with '192.168.1.5:8000' obviously - I guess this can not be the mistake?

Now I am wondering what the cause of the problem is. Is anything preventing the connection to port 8000 or does the php built in webserver not respond to the manually given ip? Why does the apache respond to that IP though?

Thanks so much for any hint!! Steffen

Apache http server reply 418 ("I’m a teapot") – json argument, TCP request using PUT from arduino

I am trying to send data (json formatted string) as argument to Apache HTTP server with PUT method from arduino. The reply from server is 418 teapot reply. This is my first project using TCP request, http, php - so I do not have a solid background in this direction.

The string :

{%221%22:%22FE005F719444%22,%222%22:%22ooooooooooxo%22,%223%22:%22ooooooooooxo%2    2}

TCP request:

PUT /proxyJson/index.php/?YOUR_data=    {%221%22:%22FE005F719444%22,%222%22:%22ooooooooooxo%22,%223%22:%22ooooooooooxo%2    2} HTTP/1.1 200 OK
Host: 192.168.xx.xxx
User-Agent: 192.168.xx.xxy
Content-Type: text/html; charset=iso-8859-1
Content-Length: 0
Connection: close

Apache access log:

192.168.xx.xxy - - [27/Dec/2016:19:50:22 +0200] "GET /proxyJson/index.php/?    YOUR_data=    {%221%22:%22FE005F719444%22,%222%22:%22ooooooooooxo%22,%223%22:%22ooooooooooxo%2    2} HTTP/1.1" 400 226 

The script works just fine if enter data directly in browser.

php script result

What am I missing ? Thanks for reply and support.

George

Trying to connect ethernet shield to local apache server

So for the most part I have had really great luck with the ethernet shield that I recently purchased. I am now trying to upload analog data from the arduino to a local mysql db. My write_data.php file seems to be working perfectly and I can upload data to the data base whenever I call the write_data.php file in the url. Although the arduino always fails to connect. I am using a netgear router and I checked the allowed devices list on the netgear genie network admin and the arduino was listed, which makes sense because it has worked for all of my other projects. Would really apprieciate some advice and ideas here. Also, not sure if this would make a difference but I am using mamp as my local server enviroment. The censored files are below :

write_data.php:

<?php

    // Prepare variables for database connection

    $dbusername = "test";  // enter database username, I used "arduino"    in step 2.2
    $dbpassword = "test";  // enter database password, I used   "arduinotest" in step 2.2
    $server = "50.135.xxx.xxx"; // IMPORTANT: if you are using XAMPP enter "localhost", but if you have an online website enter its address, ie."www.yourwebsite.com"

    // Connect to your database

    $dbconnect = mysql_pconnect($server, $dbusername, $dbpassword);
    $dbselect = mysql_select_db("Test",$dbconnect);

    // Prepare the SQL statement

    $sql = "INSERT INTO Test.Sensor (value) VALUES   ('".$_GET["value"]."')";    

    // Execute SQL statement

    mysql_query($sql);

?>

arduino sketch:

#include SPI.h

#include Ethernet.h

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// Enter the IP address for Arduino, as mentioned we will use   192.168.0.16
// Be careful to use , insetead of . when you enter the address here

IPAddress ip(192,xxx,xx,xx);

int photocellPin = 2;  // Analog input pin on Arduino we connected the    SIG pin from sensor
int photocellReading;  // Here we will place our reading

char server[] = "50.135.xxx.xxx"; // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie. "www.yourwebpage.com")

// Initialize the Ethernet server library
EthernetClient client;

void setup() {

  // Serial.begin starts the serial connection between computer and Arduino
  Serial.begin(9600);

  // start the Ethernet connection
  Ethernet.begin(mac ,ip);

}



void loop() {

  photocellReading = analogRead(photocellPin); // Fill the    sensorReading with the information from sensor

  // Connect to the server (your computer or web page)  
  if (client.connect(server,8888)) {
    client.print("GET /write_data.php?"); // This
    client.print("value="); // This
    client.print(photocellReading); // And this is what we did in the   testing section above. We are making a GET request just like we would from   our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 50.135.xxx.xxx"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

  }

  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

  // Give the server some time to recieve the data and store it. I used 10 seconds here. Be advised when delaying. If u use a short delay, the server might not capture data because of Arduino transmitting new data too soon.
  delay(10000);
}

Arduino web application

I'am new in Arduino and I would like to create a web application that recover data from Arduino via ethernet shield and display them on its page in fact this data is defined as a String and contains "hello"+ temperature value in°C + a msg the size of the message is not fixed because it can be {TX2 est normal, TX1 est normal, Alarme, TX1 en Alarme, TX2 en Alarme, TX1 sur Antenne, TX2 sur Antenne} or it can be composed by three of this exemples means it can be TX2 est normalTX1 est normalTX1 sur Antenne. to send this data to web server I had create a class called server in BlueJ and a scoket in mmy Arduino my code Arduino is

#include <SoftwareSerial.h>
#include <Ethernet.h>
#include <SPI.h>
#include <string.h>
String data;
int variable=0;
String Etat;
char v='0';
float temp_in_celsius =0;  //Declare variable for Temp in C
byte mac[] ={ 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; //Assign mac address
IPAddress ip(10, 1, 15, 243); //Assign the IP Adress
IPAddress gateway(192,168,0,1);
IPAddress subnet(255,255,255,0);
IPAddress server(192,168,0,100);
EthernetClient client;
String hello="hello:";
void loop(){
variable= ETATVOR();
if (variable==1){
  Etat="TX1 est normal";
    //println(Etat);
}
if(variable==2){
   Etat="TX2 est normal";
   // println(Etat);
}
if(variable==3){
  Etat="TX1 en Alarme";
   // println(Etat);
   sendSMS();
}
if(variable==4){
  Etat="TX2 en Alarme";
    //println(Etat);
    sendSMS();
}
if(variable==5){
  Etat="TX1 sur Antenne";
    //println(Etat);
}
if(variable==6){
   Etat="TX2 sur Antenne";
    //println(Etat);
}
if(variable==7){
   Etat="Alarme";
  // println(Etat);
  sendSMS();
}
temp_in_celsius = getTemperature();
data = hello + temp_in_celsius+ Etat;
 if(client.available()){
  client.println(data);
   client.flush();
      delay(1000);
      while(client.connected()){
     if(client.available()){
      char c = client.read();    
      v = c;
      c=' ';
      delay(500);
      break;
     }
    }
   }
  if(!client.available()){
    delay(5000);
    if(client.connect(server, 9999))
      client.println("testing"); 
  }
  if(!client.connected()) 
    client.stop();

}
}

I n the server I defined a message and this message is in fact "data" which is sent by the Arduino via ethernet and to recover data I am going to divide the message in parts and make tests like this what do u think is it a good idea ?

while ( true ) {
                    message = b.readLine();
                    System.out.println("message");
                    System.out.println(message);
                    try{
                        System.out.println("read");
                          FileWriter fstream = new FileWriter("C:/Users/User/Desktop/ApplicationPFE/txt.txt");
                          BufferedWriter out = new BufferedWriter(fstream);
                          if(message.length()>5 && message.length()<14 && widthStr2!=message){
                            widthStr2=message;  
                            System.out.println("process");
                            String sc0 = message.substring(0,5);
                            if(!message.equals("testing") && sc0.equals("hello")){
                                if(message.length()==12){
                                    String sc1 = message.substring(5,6);
                                    String sc2 = message.substring(6,7); 
                                    String sc3 = "0"+message.substring(7,8); 
                                    String sc4 = message.substring(8,9);
                                    String sc5 = message.substring(9,10);
                                    String sc6 = message.substring(10,11);
                                    String sc7 = message.substring(11,12);
                                    String Tsc = sc1+sc2+sc3+sc4+sc5+sc6+sc7;
                                    out.write(Tsc);

Arduino Ethernet Shield can’t send data with keep-alive connections

I need request to server to received some data to(request.php) by post method to server(apache)
and then
i send some data to another web page (response.php) on server

Ethernet(or Esp8266) ========(request.php by post method)=====>>> server 
Ethernet(or Esp8266) <<<============(respond)============= server
......do somethings
Ethernet(or Esp8266) ========(response.php by post method)=====>>> server

when i use connections:close in two connections in htthp request header => it's ok
But when i use connection:keep-alive. i just received responding, I can't send data to server.

This is my code:

IN loop

void loop()
{
  Serial.println("========Request to server=========");
  Serial.println(httpRequest("var=123"));
  Serial.println("========End of request=========");
  delay(1000);


  Serial.println("========Response to server=========");
  String response = "";
  response=  "var=mydata";
  Serial.println(httpPost(response));
  Serial.println("========End of Responding to server=========");
  delay(1000);

}

REquest to server:

String httpRequest(String data){
   String result="";
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("POST /getStatus.php HTTP/1.0");
    client.println("Host: localhost");
    client.println("Accept: *" "/" "*");
    client.println("Content-Length: " + String(data.length()));
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println("Connection: keep-alive");
    client.println();
    client.print(data);

  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }

    unsigned long start = millis();
    int timeout = 2000;
    while (millis() - start < timeout){ 
      while (client.available()) {
        char c = client.read();
        result += c;
      }  
    }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
   return result;

}

Hearder responding from server has : connection: keep-alive

response to server

String httpPost(String data){
   String result="";
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    client.println("POST /setStatus.php HTTP/1.0");
    client.println("Host: localhost");
    client.println("Accept: *" "/" "*");
    client.println("Content-Length: " + String(data.length()));
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println("Connection: keep-alive");
    client.println();
    client.print(data);


  }
  else {
    // kf you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  unsigned long start = millis();
  int timeout = 3000;
  while (millis() - start < timeout){ 
    while (client.available()) {
      char c = client.read();
      result += c;
    }  
  }
  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  }
   return result;

}

What is problem?
I do that on 2 devices: Ethernet and Esp8266 and have the same problem.
I still received connection: keep-alive from server. It means server accepted my connect and keep it alive????

ESP8266 Send Data To a Website bad request

I want to send some text to Apache Server, but i get some errors i'm a new bie in ESP2866. it takes me all my Sunday, I can't find the reasons.

I received: "400 Bad request".......Request header field is missing ':' separator: then i received some errors: Wrong syntax....

:(

I send following header to server: ----------------------------------:

POST /receiver.php HTTP/1.1

Host: 192.168.1.9

Content-Type: application/x-www-form-urlencoded

Content-Length: 20

temp=35

------------------------------------I use this code in Arduino:

 String cmd,aaa;
  aaa="temp="+35;
  cmd= "POST /temp.php HTTP/1.1\r\n";
  cmd+="Host: 192.168.1.9\r\n";
  cmd+="Content-Type: text/plain\r\nContent-Length: "+aaa.length();
  cmd+="\r\n\r\n"+aaa+"\r\n\r\n";


  Serial.print("Sending to Server: ");
  aaa= "AT+CIPSEND=";
  aaa+=cmd.length();
  aaa+="\r\n";

  Serial.println(sendData(aaa, 1000));
  Serial.println(sendData(cmd,2000));

  delay(1000);
------------------------This is sendData function:

String sendData(String command, const int timeout)
{
  String response = "";

  esp.print(command); // send the read character to the esp8266

  long int time = millis();

  while ( (time + timeout) > millis())
  {
    while (esp.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp.read(); // read the next character.
      response += c;
    }
  }
  return response;
}

Please help me! thank you!

Arduino Ethernet shield slow to connect with android app

So I've created a webserver that outputs the values from a couple of analogue sensors when a command is received from an android app. However it lags whenever any button is pressed and only occasionally works, usually crashing the app. This is the arduino code:

//ARDUINO 1.0+ ONLY                                                            
//ARDUINO 1.0+ ONLY                                                            


#include <Ethernet.h>                                                          
#include <SPI.h>                                                               
// the value of the 'other' resistor                                           
#define SERIESRESISTOR 10000                                            

// What pin to connect the sensor to                                           
#define THERMISTORPIN A0                                                      
boolean reading = false;                                                       
const int analogInPin = A1;                                                    
int sensorValue = 0;                                                           

////////////////////////////////////////////////////////////////////////       
//CONFIGURE                                                                    
////////////////////////////////////////////////////////////////////////       
byte ip[] = { 192, 168, 0, 101 };   //Manual setup only                        
byte gateway[] = { 192, 168, 0, 1 }; //Manual setup only                       
byte subnet[] = { 255, 255, 255, 0 }; //Manual setup only                      

// if need to change the MAC address (Very Rare)                               
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };                           

EthernetServer server = EthernetServer(80); //port 80                          
////////////////////////////////////////////////////////////////////////       

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

    //Pins 10,11,12 & 13 are used by the ethernet shield                       

    pinMode(7, OUTPUT);                                                        



    Ethernet.begin(mac, ip, gateway, subnet); //for manual setup               

    server.begin();                                                            
    Serial.println(Ethernet.localIP());                                        

}                                                                              

void loop(){                                                                   

    // listen for incoming clients, and process qequest.                       
    checkForClient();                                                          

    tempReading();                                                             

} 

void tempReading(){                                                            
    sensorValue = analogRead(analogInPin);                                  
    EthernetClient client2 = server.available();                               
    if (client2) {                                                             

        // an http request ends with a blank line                              
        boolean currentLineIsBlank = true;                                     
        boolean sentHeader = false;                                            

        while (client2.connected()) {                                          

            if (client2.available()) {                                         

                if(!sentHeader){                                               
                    // send a standard http response header                    
                    client2.println("HTTP/1.1 200 OK");                        
                    client2.println("Content-Type: text/html");                
                    client2.println();                                         
                    sentHeader = true;                                         
                }                                                              

                float reading;                                                 

                reading = analogRead(THERMISTORPIN);                           

                Serial.print("Analog reading ");-                              
                Serial.println(reading);                                       

                // convert the value to resistance                             
                reading = (1023 / reading)  - 1;                               
                reading = SERIESRESISTOR / reading;                            
                Serial.print("Thermistor resistance ");                   
                Serial.println(reading);                                       


                delay(1000);                                                   
                float reading2;                                                
                char d = client2.read();                                       

                if(reading2 && d == ' ') reading2 = false;                     
                if(d == '?') reading2 = true; //found the ?, begin reading the info 

                if(reading2){                                                  


                    switch (d) {                                               
                      case '4':                                                
                        //add code here to trigger on 2                        
                        client2.print("Thermistor resistance: ");              
                        client2.println(reading);                              
                        client2.println("\n");                                 
                        break;                                                 
                      case '5':                                                
                        client2.print("Light Level: ");                        
                        client2.println(sensorValue);                          
                        client2.println("\n");                                 
                    }                                                          
                }                                                              

            }                                                                  

        }                                                                      
        delay(1); // give the web browser time to receive the data             
        client2.stop(); // close the connection:                               

    }                                                                          
}                                                                              



void checkForClient(){                                                         

    EthernetClient client = server.available();                                

    if (client) {                                                              

        // an http request ends with a blank line                              
        boolean currentLineIsBlank = true;                                     
        boolean sentHeader = false;                                            

        while (client.connected()) {                                           

            if (client.available()) {                                          

                if(!sentHeader){                                               
                    // send a standard http response header                    
                    client.println("HTTP/1.1 200 OK");                         
                    client.println("Content-Type: text/html");                 
                    client.println();                                          
                    sentHeader = true;                                         
                }                                                              

                char c = client.read();                                        

                if(reading && c == ' ') reading = false;                       
                if(c == '?') reading = true; //found the ?, begin reading the info 

                if(reading){                                                   
                    Serial.print(c);                                           

                    switch (c) {                                               
                      case '1':                                                
                        //add code here to trigger on 2                        
                        pinOn(7, client);                                      
                        break;                                                 
                      case '2':                                                
                        //add code here to trigger on 3                        
                        pinOff(7, client);                                     
                        break;                                                 


                    }                                                          

                }                                                              

                if (c == '\n' && currentLineIsBlank)  break;                   

                if (c == '\n') {                                               
                    currentLineIsBlank = true;                                 
                }else if (c != '\r') {                                         
                    currentLineIsBlank = false;                                
                }                                                              

            }                                                                  
        }                                                                      

        delay(1); // give the web browser time to receive the data             
        client.stop(); // close the connection:                                

    }
          void pinOff(int pin, EthernetClient client){                                   


    digitalWrite(pin, HIGH);                                                   

}                                                                              
void pinOn(int pin, EthernetClient client){                                    

    digitalWrite(pin, LOW);                                                    

}                                                                      

and this is the Android code:

package com.example.liam.arduinocontroller;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;


public class ControlClass extends ActionBarActivity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.
                ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_control_class);
        View led1on = findViewById(R.id.led_1on);
        View led1off = findViewById(R.id.led_1off);
        View led2on = findViewById(R.id.led_2on);
        View led2off = findViewById(R.id.led_2off);

        led1on.setOnClickListener(this);
        led1off.setOnClickListener(this);
        led2on.setOnClickListener(this);
        led2off.setOnClickListener(this);

    }

    public void commandArduino(String url) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpParams httpParameters = httpclient.getParams();
            HttpConnectionParams.setTcpNoDelay(httpParameters, true);
            httpclient.execute(new HttpGet(url));

        } catch (Exception e) {
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_control_class, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View thisView) {



            switch(thisView.getId())


            {
                case R.id.led_1on:
                    commandArduino("http://192.168.0.101/?2");
                    Toast.makeText(getApplicationContext(), "led_1on", Toast.LENGTH_LONG).show();
                    break;
                case R.id.led_1off:
                    commandArduino("http://192.168.0.101/?3");
                    Toast.makeText(getApplicationContext(), "led_1off", Toast.LENGTH_LONG).show();
                    break;
                case R.id.led_2on:
                    commandArduino("http://192.168.0.101/?4");
                    Intent intent = new Intent(this, TempDisplay.class);
                    startActivity(intent);
                    break;
                case R.id.led_2off:
                    commandArduino("http://192.168.0.101/?5");
                    Intent j = new Intent(this, LightDisplay.class);
                    startActivity(j);
                    break;
            }




    }
}

Any ideas?

Arduino Sending Data To Web Server

I'm working with a group and we are getting issues sending data from an Arduino to a Web Server we created.

Below is the code from our web server code locksys_server.ino

/*Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield. 

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 */

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


// 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 };
byte ip[] = { 
192, 168, 2, 3 };

char x;
char c1;
char data[13];

// 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:
Wire.begin(4);                // join i2c bus with address #4
Wire.onReceive(receiveEvent); // register event

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


void loop() {

    if(client.connect(ip, 80) ) {
        client.println("POST /Loksys/add.php HTTP/1.1");
        client.println("Host: 192.168.2.3:80");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.println("Content-Length: ");
        //client.println(data.length());
        client.println();
        client.print(data);
    }

}

void receiveEvent(int howMany)
{
  for (int i = 0; i < 12; i++)
  // while(1 < Wire.available()) // loop through all but the last
  {
    c1 = Wire.read(); // receive byte as a character
    Serial.print(c1);         // print the ch1aracter
    data[i] = c1;
  }
  // x = Wire.read();    // receive byte as an integer
  // Serial.println(x);         // print the integer
}

Below is the code from our add.php file

<?php
    function Connection(){
        $server="192.168.2.3";
        $user="root";
        $pass="";
        $db="LockSys";

        $connection = mysql_connect($server, $user, $pass);

        if (!$connection) {
            die('MySQL ERROR: ' . mysql_error());
        }

        mysql_select_db($db) or die( 'MySQL ERROR: '. mysql_error() );

        return $connection;
    }

    $link=Connection();



    $RFID=$_POST["data"];


    $query = "INSERT INTO `checkin` (`rfid`)
        VALUES ('$RFID')";

    mysqli_query($query,$link);
    mysqli_close($link);

    header("Location: locksysHome.php");
?>

We uploaded the Arduino code, but we aren't getting any updated values on the Web Server whenever we would pass values from the Aruino to the Web Server.