why cant i turn off led's on arduino using android and esp8266 -
i have tried make android application turn on or off led's using arduino.
esp8266 esp-01 provides access point .
but cant turn off led's using there error
also when see data in serial monitor partially gibberish
i have taken code allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/
but modified me because not working me on 2 , 3 pins
i have used arduino uno.
the code arduino follows:
#include <softwareserial.h> #define debug true softwareserial esp8266(10,11); // make rx arduino line pin 2, make tx arduino line pin 3. // means need connect tx line esp arduino's pin 2 // , rx line esp arduino's pin 3 void setup() { serial.begin(115200); esp8266.begin(115200); // esp's baud rate might different pinmode(2,output); digitalwrite(2,low); pinmode(3,output); digitalwrite(3,low); pinmode(4,output); digitalwrite(4,low); pinmode(6,output); digitalwrite(6,low); sendcommand("at+rst\r\n",2000,debug); // reset module sendcommand("at+cwmode=2\r\n",1000,debug); // configure access point delay(1000); sendcommand("at+cifsr\r\n",1000,debug); // ip address sendcommand("at+cipmux=1\r\n",1000,debug); // configure multiple connections sendcommand("at+cipserver=1,80\r\n",1000,debug); // turn on server on port 80 serial.println("server ready"); } void loop() { if(esp8266.available()) // check if esp sending message { if(esp8266.find("+ipd,")) { delay(1000); // wait serial buffer fill (read serial data) // connection id can disconnect int connectionid = esp8266.read()-48; // subtract 48 because read() function returns // ascii decimal value , 0 (the first decimal number) starts @ 48 esp8266.find("pin="); // advance cursor "pin=" int pinnumber = (esp8266.read()-48); // first number i.e. if pin 13 1st number 1 int secondnumber = (esp8266.read()-48); if(secondnumber>=0 && secondnumber<=9) { pinnumber*=10; pinnumber +=secondnumber; // second number, i.e. if pin number 13 2nd number 3, add first number } digitalwrite(pinnumber, !digitalread(pinnumber)); // toggle pin // build string send device requesting pin toggle string content; content = "pin "; content += pinnumber; content += " "; if(digitalread(pinnumber)) { content += "on"; } else { content += "off"; } sendhttpresponse(connectionid,content); // make close command string closecommand = "at+cipclose="; closecommand+=connectionid; // append connection id closecommand+="\r\n"; sendcommand(closecommand,1000,debug); // close connection } } } /* * name: senddata * description: function used send data esp8266. * params: command - data/command send; timeout - time wait response; debug - print serial window?(true = yes, false = no) * returns: response esp8266 (if there reponse) */ string senddata(string command, const int timeout, boolean debug) { string response = ""; int datasize = command.length(); char data[datasize]; command.tochararray(data,datasize); esp8266.write(data,datasize); // send read character esp8266 if(debug) { serial.println("\r\n====== http response arduino ======"); serial.write(data,datasize); serial.println("\r\n========================================"); } long int time = millis(); while( (time+timeout) > millis()) { while(esp8266.available()) { // esp has data display output serial window char c = esp8266.read(); // read next character. response+=c; } } if(debug) { serial.print(response); } return response; } /* * name: sendhttpresponse * description: function sends http 200, html utf-8 response */ void sendhttpresponse(int connectionid, string content) { // build http response string httpresponse; string httpheader; // http header httpheader = "http/1.1 200 ok\r\ncontent-type: text/html; charset=utf-8\r\n"; httpheader += "content-length: "; httpheader += content.length(); httpheader += "\r\n"; httpheader +="connection: close\r\n\r\n"; httpresponse = httpheader + content; // there bug in code: last character of "content" not sent, cheated adding space sendcipdata(connectionid,httpresponse); } /* * name: sendcipdata * description: sends cipsend=<connectionid>,<data> command * */ void sendcipdata(int connectionid, string data) { string cipsend = "at+cipsend="; cipsend += connectionid; cipsend += ","; cipsend +=data.length(); cipsend +="\r\n"; sendcommand(cipsend,1000,debug); senddata(data,1000,debug); } /* * name: sendcommand * description: function used send data esp8266. * params: command - data/command send; timeout - time wait response; debug - print serial window?(true = yes, false = no) * returns: response esp8266 (if there reponse) */ string sendcommand(string command, const int timeout, boolean debug) { string response = ""; esp8266.print(command); // send read character esp8266 long int time = millis(); while( (time+timeout) > millis()) { while(esp8266.available()) { // esp has data display output serial window char c = esp8266.read(); // read next character. response+=c; } } if(debug) { serial.print(response); } return response; }
the code android follow :
mainactivity:
package com.example.autohome; import android.app.activity; import android.app.alertdialog; import android.content.context; import android.content.sharedpreferences; import android.os.asynctask; import android.os.bundle; import android.view.view; import android.widget.button; import android.widget.edittext; import org.apache.http.httpresponse; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httpget; import org.apache.http.impl.client.defaulthttpclient; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.net.uri; import java.net.urisyntaxexception; public class mainactivity extends activity implements view.onclicklistener { public final static string pref_ip = "pref_ip_address"; public final static string pref_port = "pref_port_number"; // declare buttons , text inputs private button buttonpin11,buttonpin12,buttonpin13; private edittext edittextipaddress, edittextportnumber; // shared preferences objects used save ip address , port user doesn't have // type them next time he/she opens app. sharedpreferences.editor editor; sharedpreferences sharedpreferences; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); sharedpreferences = getsharedpreferences("http_helper_prefs",context.mode_private); editor = sharedpreferences.edit(); // assign buttons buttonpin11 = (button)findviewbyid(r.id.buttonpin11); buttonpin12 = (button)findviewbyid(r.id.buttonpin12); buttonpin13 = (button)findviewbyid(r.id.buttonpin13); // assign text inputs edittextipaddress = (edittext)findviewbyid(r.id.edittextipaddress); edittextportnumber = (edittext)findviewbyid(r.id.edittextportnumber); // set button listener (this class) buttonpin11.setonclicklistener(this); buttonpin12.setonclicklistener(this); buttonpin13.setonclicklistener(this); // ip address , port number last time user used app, // put empty string "" first time. edittextipaddress.settext(sharedpreferences.getstring(pref_ip,"")); edittextportnumber.settext(sharedpreferences.getstring(pref_port,"")); } @override public void onclick(view view) { // pin number string parametervalue = ""; // ip address string ipaddress = edittextipaddress.gettext().tostring().trim(); // port number string portnumber = edittextportnumber.gettext().tostring().trim(); // save ip address , port next time app used editor.putstring(pref_ip,ipaddress); // set ip address value save editor.putstring(pref_port,portnumber); // set port number save editor.commit(); // save ip , port // pin number button clicked if(view.getid()==buttonpin11.getid()) { parametervalue = "2"; } else if(view.getid()==buttonpin12.getid()) { parametervalue = "3"; } else { parametervalue = "4"; } // execute http request if(ipaddress.length()>0 && portnumber.length()>0) { new httprequestasynctask( view.getcontext(), parametervalue, ipaddress, portnumber, "pin" ).execute(); } } /** * description: send http request specified ip address , port. * send parameter "parametername" value of "parametervalue". * @param parametervalue pin number toggle * @param ipaddress ip address send request * @param portnumber port number of ip address * @param parametername * @return ip address' reply text, or error message fails receive 1 */ public string sendrequest(string parametervalue, string ipaddress, string portnumber, string parametername) { string serverresponse = "error"; try { httpclient httpclient = new defaulthttpclient(); // create http client // define url e.g. http://myipaddress:myport/?pin=13 (to toggle pin 13 example) uri website = new uri("http://"+ipaddress+":"+portnumber+"/?"+parametername+"="+parametervalue); httpget getrequest = new httpget(); // create http object getrequest.seturi(website); // set url of request httpresponse response = httpclient.execute(getrequest); // execute request // ip address server's reply inputstream content = null; content = response.getentity().getcontent(); bufferedreader in = new bufferedreader(new inputstreamreader( content )); serverresponse = in.readline(); // close connection content.close(); } catch (clientprotocolexception e) { // http error serverresponse = e.getmessage(); e.printstacktrace(); } catch (ioexception e) { // io error serverresponse = e.getmessage(); e.printstacktrace(); } catch (urisyntaxexception e) { // url syntax error serverresponse = e.getmessage(); e.printstacktrace(); } // return server's reply/response text return serverresponse; } /** * asynctask needed execute http requests in background not * block user interface. */ private class httprequestasynctask extends asynctask<void, void, void> { // declare variables needed private string requestreply,ipaddress, portnumber; private context context; private alertdialog alertdialog; private string parameter; private string parametervalue; /** * description: asynctask class constructor. assigns values used in other methods. * @param context application context, needed create dialog * @param parametervalue pin number toggle * @param ipaddress ip address send request * @param portnumber port number of ip address */ public httprequestasynctask(context context, string parametervalue, string ipaddress, string portnumber, string parameter) { this.context = context; alertdialog = new alertdialog.builder(this.context) .settitle("http response ip address:") .setcancelable(true) .create(); this.ipaddress = ipaddress; this.parametervalue = parametervalue; this.portnumber = portnumber; this.parameter = parameter; } /** * name: doinbackground * description: sends request ip address * @param voids * @return */ @override protected void doinbackground(void... voids) { alertdialog.setmessage("data sent, waiting reply server..."); if(!alertdialog.isshowing()) { alertdialog.show(); } requestreply = sendrequest(parametervalue,ipaddress,portnumber, parameter); return null; } /** * name: onpostexecute * description: function executed after http request returns ip address. * function sets dialog's message reply text server , display dialog * if it's not displayed (in case closed accident); * @param avoid void parameter */ @override protected void onpostexecute(void avoid) { alertdialog.setmessage(requestreply); if(!alertdialog.isshowing()) { alertdialog.show(); // show dialog } } /** * name: onpreexecute * description: function executed before http request sent ip address. * function set dialog's message , display dialog. */ @override protected void onpreexecute() { alertdialog.setmessage("sending data server, please wait..."); if(!alertdialog.isshowing()) { alertdialog.show(); } } } }
layout file:
<?xml version="1.0" encoding="utf-8"?> <scrollview xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <linearlayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margintop="20dp" android:text="ip address:" android:id="@+id/textview" /> <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="e.g. 192.168.0.10" android:id="@+id/edittextipaddress" /> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="port number:" android:id="@+id/textview2" /> <edittext android:layout_width="match_parent" android:layout_height="wrap_content" android:inputtype="number" android:ems="10" android:hint="e.g. 80" android:id="@+id/edittextportnumber" /> <button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="pin 11" android:id="@+id/buttonpin11" /> <button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="pin 12" android:id="@+id/buttonpin12" /> <button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="pin 13" android:id="@+id/buttonpin13" /> </linearlayout> </scrollview>
when response not gibberish program works. when gibberish there problem
please forgive me if post lacking information. apologize mistakes in post first
you getting gibberish because arduino can't provide enough current esp8266, when transmitting/receiving data. esp8266 module try draw peak currents of 320ma while arduino 3.3v regulated output rated 50ma, must use external power supply.
Comments
Post a Comment