Communication between Arduino and android via ethernet shield - android

I'm using Android to toggle my led light with Arduino and ethernet shield. It didn't work despite having no problems during compilation neither on Android nor Arduino. I connected the ethernet shield with my computer and I gave it the same address as my computer.
This is my Android code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/********************************/
/* Define all the buttons */
/********************************/
Switch led1 = (Switch) findViewById(R.id.Led1);
/*******************************************************/
/* Set an onclick/onchange listener for every button */
/*******************************************************/
led1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* Switch is led 1 */
new Background_get().execute("led1=1");
} else {
new Background_get().execute("led1=0");
}
}
});
}
#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_main, 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);
}
/*****************************************************/
/* This is a background process for connecting */
/* to the arduino server and sending */
/* the GET request withe the added data */
/*****************************************************/
private class Background_get extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
/* Change the IP to the IP you set in the arduino sketch */
URL url = new URL("http://169, 254, 128, 184/?" + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder result = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
result.append(inputLine).append("\n");
in.close();
connection.disconnect();
return result.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
And this is the Arduino code:
#include <SPI.h>
#include <Ethernet.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
};
IPAddress ip(169, 254, 128, 184);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
// Pin 5
pinMode(5, OUTPUT);
}
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;
String buffer = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
Serial.write(c);
buffer += c;
// 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
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();
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
buffer = "";
} else if (c != '\r') {
if (buffer.indexOf("GET /?led1=1") >= 0) { // If led1 = 1
digitalWrite(5, HIGH); // led 1 > on
}
if (buffer.indexOf("GET /?led1=0") >= 0) { // If led1 = 0
digitalWrite(5, LOW); // led 1 > off
}
} else {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}

Program your Arduino:
#include "etherShield.h"
#include "ETHER_28J60.h"
int led2 = 7;
int led1 = 6;
static uint8_t mac[6] = {0xAA, 0xBB, 0xCC, 0xDD, 0xBB, 0xAA}; // this just needs to be unique for your network,
// so unless you have more than one of these boards
// connected, you should be fine with this value.
static uint8_t ip[4] = {192, 168, 0, 15}; // the IP address for your board. Check your home hub
// to find an IP address not in use and pick that
// this or 10.0.0.15 are likely formats for an address
// that will work.
static uint16_t port = 80; // Use port 80 - the standard for HTTP
ETHER_28J60 e;
void setup(){
e.setup(mac, ip, port);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
}
void loop(){
char* params;
if (params = e.serviceRequest()){
if (strcmp(params, "?cmd=1") == 0){digitalWrite(led1, HIGH);}
if (strcmp(params, "?cmd=2") == 0){digitalWrite(led1, LOW); }
if (strcmp(params, "?cmd=3") == 0){digitalWrite(led2, HIGH);}
if (strcmp(params, "?cmd=4") == 0){digitalWrite(led2, LOW); }
e.respond();
}
}
Program your APP
Add Permission to Your Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity 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.main);
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();
httpclient.execute(new HttpGet(url));
} catch (Exception e) {}
}
public void onClick(View thisView) {
switch(thisView.getId()){
case R.id.led_1on: commandArduino("http://192.168.0.15/?cmd=1"); break;
case R.id.led_1off: commandArduino("http://192.168.0.15/?cmd=2"); break;
case R.id.led_2on: commandArduino("http://192.168.0.15/?cmd=3"); break;
case R.id.led_2off: commandArduino("http://192.168.0.15/?cmd=4"); break;
}
}
}
Reference:
http://www.instructables.com/id/Arduino-Android-LED-control-Using-Ethernet-Shield/

Related

how to reconnect after get data from my esp 8266 in android

hello im having stuck after i sending data from esp8266
i connected esp8266 with my arduino
this is my arduino code
#include <SoftwareSerial.h>
//#include <OneWire.h>
//#include <DallasTemperature.h>
//#include <stdlib.h>
//#include "Wire.h"
//#define DS3231_I2C_ADDRESS 0x68
//#define ONE_WIRE_BUS 5
//WIFI
#include <SPI.h>
#include <WiFi.h>
// 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);
int wifiTx = 4;
int wifiRx = 3;
#define DEBUG true
char com;
String data;
SoftwareSerial wifi(wifiTx, wifiRx);
//wifi
char ssid[] = "waifu"; // your network SSID (name)
char pass[] = "chronoangel"; // your network password
//int status = WL_IDLE_STATUS; // the Wifi radio's status
void setup() {
// put your setup code here, to run once:
Wire.begin();
Serial.begin(9600);
wifi.begin(115200);
sensors.begin();
//sekon, menit,jam, day of week, hari, bulan taun
//setDS3231time(0,15,2,1,13,7,16);
//\start_wifi();
esp();
}
void loop() {
test_wifi();
//loop_esp();
}
void esp()
{
sendCommand("AT\r\n",2000,DEBUG);
sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
sendCommand("AT+CWMODE=1\r\n",1000,DEBUG); // configure as access point
sendCommand("AT+CWJAP=\"waifu\",\"chronoangel\"\r\n",3000,DEBUG);
delay(10000);
//Serial.println("\nCek IP");
//sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
Serial.println("\nGet PORT");
sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
Serial.println("\nSet IP");
sendCommand("AT+CIPSTA=\"192.168.1.7\"\r\n",1000,DEBUG); // set ip address
sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
Serial.println("\nServer Ready");
}
void test_wifi()
{
if(wifi.available())
{
char toSend = (char)wifi.read();
Serial.print(toSend);
}
//Read from usb serial to wifi
if(Serial.available())
{
char toSend = (char)Serial.read();
wifi.print(toSend);
}
}
and this is my android studio code
package com.example.chronoangel.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.IP);
editTextPort = (EditText) findViewById(R.id.Port);
buttonConnect = (Button) findViewById(R.id.connect);
//buttonClear = (Button)findViewById(R.id.clear);
textResponse = (TextView) findViewById(R.id.textData);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
#Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(editTextAddress.getText().toString(), Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}};
//class to get data from esp8266
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port) {
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
this is my view of my program :
my problem is similiar to this page :
http://stackoverflow.com/questions/34274774/esp8266-wifi-server-to-android-client
but i think in there didnt have clue either how to reconnected after send a data
the program run after i click connect on android app
in my serial arduino after i send AT+ COMMAND
AT+CIPSEND = 0,2
then i send data "ab" to my android
the data was not send, but if ii send AT+COMMAND
AT+CIPCLOSE=0
the data was send,but i must click connect again to get the data from esp
my question is can we get continous data after click connect ?
how suppose i do with the android to connect again after arduino send a message ?
This is more an advice than an answer, because I think there is no other way than to close the connection everytime.
But i highly recommend to use your own Software for your ESP8266 rather than to use the AT-Commands. They are nice for the start, to connect to a network and so on. But they are limited. Since you're using arduino allready, i would suggest to use the IDE to write some code for your ESP.
You can find a lot of code and help here.
https://create.arduino.cc/projecthub/Metavix/programming-the-esp8266-with-the-arduino-ide-in-3-simple-601c16
And the ESP8266WiFi.h offers a lot of functions that are ready to use.

Android HttpUrlConnection with Arduino Uno

Happy new year all :)
I am working on a home automation project using Arduino Uno and Android application what can communicate through my TP-Link router.
I am having a java.io.IOException: unexpected end of stream on Connection
once I send a query to the Arduino and I'm not being able to solve it.
01-01 16:51:47.771 10592-11256/com.projects.mahmoudmahdi.etherdroid E/EtherDroid: java.io.IOException: unexpected end of stream on Connection{192.168.1.215:80, proxy=DIRECT# hostAddress=192.168.1.215 cipherSuite=none protocol=http/1.1} (recycle count=0)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:904)
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:788)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:501)
at com.projects.mahmoudmahdi.etherdroid.MainActivity$commandArduino.doInBackground(MainActivity.java:50)
at com.projects.mahmoudmahdi.etherdroid.MainActivity$commandArduino.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.io.EOFException: \n not found: size=0 content=...
at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
at com.android.okhttp.internal.http.HttpConnection.readHeaders(HttpConnection.java:220)
at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:199)
at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80) 
at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:904) 
at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:788) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:443) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:388) 
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:501) 
at com.projects.mahmoudmahdi.etherdroid.MainActivity$commandArduino.doInBackground(MainActivity.java:50) 
at com.projects.mahmoudmahdi.etherdroid.MainActivity$commandArduino.doInBackground(MainActivity.java:31) 
at android.os.AsyncTask$2.call(AsyncTask.java:295) 
at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
My Arduino Sketch:
#include <UIPEthernet.h>
int relay = 2;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 215 }; // ip in lan (that's what you need to use in your browser. (F("192.168.1.200"))
byte gateway[] = { 192, 168, 1, 10 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(80); //server port
String readString;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
pinMode(relay, OUTPUT);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print(F("server is at "));
Serial.println(Ethernet.localIP());
}
void loop() {
// Create a client connection
EthernetClient client = server.available();
if (client) {
//clearing string for next read
readString = "";
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
Serial.print(c);
}
//if HTTP request has ended
if (c == '\n') {
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
//stopping client
client.stop();
//controls the Arduino if you press the buttons
if (readString.indexOf("?relay1on") > 0) {
digitalWrite(relay, LOW);
Serial.println("relay is on");
}
if (readString.indexOf("?relay1off") > 0) {
digitalWrite(relay, HIGH);
Serial.println("relay is off");
}
}
}
}
}
}
My Android Code:
package com.projects.mahmoudmahdi.etherdroid;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private class commandArduino extends AsyncTask<URL, Void, Integer> {
#Override
protected Integer doInBackground(URL... url) {
int response = 0;
if (isNetworkAvailable()) {
// params comes from the execute() call: params[0] is the url.
try {
HttpURLConnection urlConnection = (HttpURLConnection) url[0].openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
switch (urlConnection.getResponseCode()) {
case HttpURLConnection.HTTP_OK:
Log.d("RESPONSE", "**OK**");
break; // fine, go on
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
Log.d("RESPONSE", "**gateway timeout**");
break;// retry
case HttpURLConnection.HTTP_UNAVAILABLE:
Log.d("RESPONSE", "**unavailable**");
break;// retry, server is unstable
default:
Log.d("RESPONSE", "**unknown response code**.");
break; // abort
}
urlConnection.disconnect();
Log.d("RESPONSE", "Aborting download of dataset.");
} catch (Exception e) {
Log.e("EtherDroid", "STACKTRACE");
Log.e("EtherDroid", Log.getStackTraceString(e));
}
}
return response;
}
}
static boolean relay1 = false;
commandArduino cmdAdn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button Relay1 = (Button) findViewById(R.id.relay1);
Relay1.setOnClickListener(this);
}
private boolean isNetworkAvailable() {
boolean available = false;
/** Getting the system's connectivity service */
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
/** Getting active network interface to get the network's status */
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable())
available = true;
/** Returning the status of the network */
return available;
}
public void onClick(View thisView) {
cmdAdn = new commandArduino();
switch (thisView.getId()) {
case R.id.relay1:
if (!relay1) {
relay1 = true;
try {
cmdAdn.execute(new URL("http://192.168.1.215/?relay1on"));
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "relay1 on", Toast.LENGTH_SHORT).show();
} else {
relay1 = false;
try {
cmdAdn.execute(new URL("http://192.168.1.215/?relay1off"));
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "relay1 off", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
In general terms, you're missing:
Send data in the response
Giving time for the socket to send data before closing
Reading Android's response before closing the connection.
More in detail, make sure to send some data after establishing the connection:
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("</html>");
// Give it time to close
delay(1);
client.close();
Reference: https://www.arduino.cc/en/Tutorial/WebServer , here's the full example:
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(); // NOTE: You're missing this in your code
Serial.write(c);
// 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
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();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
// output the value of each analog input pin
for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
int sensorReading = analogRead(analogChannel);
client.print("analog input ");
client.print(analogChannel);
client.print(" is ");
client.print(sensorReading);
client.println("<br />");
}
client.println("</html>");
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
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
Ethernet.maintain();
}
}
Also, consider using json instead of html for Arduino's response. To do that, you'll need to change:
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: application/json");
client.println("Connection: close");
client.println();
client.println("{\"status\":\"ok\"}"); // Or whatever you want to change

send udp message from PC(windows)(client) to android phone(server) not working

I want to send a UDP message from PC(server) to my android phone 4.2(client) using WIFI connection. My phone and PC are connected via wireless router. But no message is received from phone to mobile.
I have understood from debugging that the program is waiting at socket.receive(packet);. So, there is no update on the UI.
I want to show message to the UI when server received a message from client and this process will be continue.
I would be grateful, if you could help me. Thank you. I have added necessary permission.
server:
package com.example.abuttontest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.System;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private TextView tv;
int i =0;
// String s;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
//TextView textMessage = (TextView) findViewById(R.id.textView2);
button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
/*cheack ping message*/
//boolean morgan= isOnline();
//String s = String.valueOf(morgan);
tv.setText("kkkkkkkkkk"); // print ping message
Log.d("MyTag#","This is sample log message");
}
});
/* Thread for receiving Data from CLient */
runThread();
}
private void runThread()
{
new Thread()
{
public void run()
{
Log.d("p2p", "1");
while (i++ < 1000)
{
Log.d("p2p", "2");
try {
/////////////////////
//System.out.println("aaa");
byte[] inbuf = new byte[1000]; // default size
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
Log.d("p2p", "3");
DatagramSocket socket = new DatagramSocket(6000);
socket.receive(packet);
Log.d("p2p", "4");
int numBytesReceived = packet.getLength();
//System.out.println(numBytesReceived);
String s = new String(inbuf);
//System.out.println(s);
//System.out.println(inbuf[2]);
socket.close();
Log.d("p2p", "5");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
tv.setText("#" + i);
}
});
Thread.sleep(300);
}
catch (InterruptedException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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();
if (id == R.id.one)
{
Toast.makeText(getApplicationContext(), "Toast Message ONE", Toast.LENGTH_LONG).show();
}
if (id == R.id.two)
{
Toast.makeText(getApplicationContext(), "Toast Message TWO", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
client:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*packets in the IP layer are called the datagrams */
/*After creating a packet, the process of sending or receiving it involves calling the send or receive method of DatagramSocket. More specifically, you create a packet, then you create a socket. After you create the socket, you call the send method of DatagramSocket to send the datagram packet or use the receive method of DatagramSocket to receive a packet. You can also use the same DatagramSocket to send and receive multiple packets, each going to different destinations and coming from different sources.*/
public class client
{
public static void main(String args[])
{
System.out.println("from client");
try{
//InetAddress ipaddress = InetAddress.getByName("localhost");
// InetAddress ipaddress = InetAddress.getByName("192.168.0.103");
// while(true)
// {
InetAddress ipaddress = InetAddress.getByName("192.168.0.102");
int port = 6000;
//byte[] buffer = new byte[1024]; // empty byte array
String msg ="hello goooooooogle"; // send this message to the server
byte [] b_array = msg.getBytes();
//on SERVER side DatagramSocket able to receive packets on 8080 port
DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number)
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
// }
}
catch(Exception e)
{
System.out.println(e);
}
}
}
In your MainActivity you have not mentioned the port number which your server has to listen on.

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?
I try to refactor your code
//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
const int analogInPin = A1;
////////////////////////////////////////////////////////////////////////
//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() {
boolean reading = false;
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 == '?') {
//found the ?, begin reading the info
reading = true;
}
if (reading){
Serial.print(c);
switch (c) {
case '1':
pinOn(7, client);
break;
case '2':
pinOff(7, client);
break;
case '4':
print_thermistor(&client);
break;
case '5':
print_light(&client);
break;
}
}
if (c == '\n' && currentLineIsBlank)
break;
if (c == '\n') {
currentLineIsBlank = true;
} else if (c != '\r') {
currentLineIsBlank = false;
}
}
}
delay(500); // give the web browser time to receive the data
client.stop(); // close the connection:
}
}
void print_thermistor(EthernetClient *client) {
float th;
th = analogRead(THERMISTORPIN);
Serial.print("Analog th ");
Serial.println(th);
// convert the value to resistance
th = (1023 / th) - 1;
th = SERIESRESISTOR / th;
Serial.print("Thermistor resistance ");
Serial.println(th);
client->print("Thermistor resistance: ");
client->println(th);
client->println("\n");
}
void print_light(EthernetClient *client) {
int sensorValue;
sensorValue = analogRead(analogInPin);
client->print("Light Level: ");
client->println(sensorValue);
client->println("\n");
}
void pinOff(int pin, EthernetClient client){
digitalWrite(pin, HIGH);
}
void pinOn(int pin, EthernetClient client){
digitalWrite(pin, LOW);
}

Establishing a serial communication between Android and ATMega16 microcontroller via PL2303 USB-Uart

Constituents of our current set up include:
1) A hardware device to read cards and send the unique code every time a card is processed. Consists an RFID Card Reader, ATMega16 Microcontroller and PL2303 USB-UART for serial communication with the Android device.
2) An Android App that receives the unique code (Sent by the microcontroller) every time a card is processed by the hardware device.
The code that we are using to receive the unique-code from the hardware :
The code uses Android USB Host API
package com.example.admin.hardware;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
UsbManager manager;
byte[] bytes;
UsbEndpoint end;
UsbInterface inter;
UsbDevice device;
UsbDeviceConnection conn;
TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if(device == null)
{
Toast.makeText(this, "NO DEVICE CONNECTED!", Toast.LENGTH_LONG).show();
}
else
{
data = (TextView) findViewById(R.id.data);
String name = device.getDeviceName();
//int vendorID = device.getVendorId();
inter = device.getInterface(0);
int i = inter.getEndpointCount();
end = inter.getEndpoint(0);
Toast.makeText(this, "Name Of The "+name, Toast.LENGTH_LONG).show();
//RETURNS 128 if USB_DIR_IN and 0 if USB_DIR_OUT
int direction = end.getDirection();
Toast.makeText(this, "Direction of The EndPoint "+String.valueOf(direction), Toast.LENGTH_LONG).show();
manager = (UsbManager) getSystemService(Context.USB_SERVICE);
conn = manager.openDevice(device);
conn.claimInterface(inter, true);
new Thread(new Runnable(){
#Override
public void run() {
try {
conn.bulkTransfer(end, bytes, 32, 0);
}
catch(Exception e){
data.setText(e.getMessage());
}
}
}).start();
}
}
#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_main, 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);
}
}
What I expect to see:
The data received from the hardware device should be stored in the byte array.
What is actually happening:
The program gives "Buffer start or length out of bounds" error!
Any help will be greatly appreciated!
You never initialize the array bytes.
Use byte[] bytes = new byte[32];.
Then conn.bulkTransfer(end, bytes, bytes.length, 0); to be safe in case you need to change the length of the array.

Categories

Resources