Android and arduino wifi

ESP8266 WiFi Android Controller

Самое первое что нам нужно сделать это установить в Arduino IDE две библиотеки:

На видео я показал где это можно сделать. После того как это сделано убедитесь что у вас также установлена поддержка плат ESP8266 и выбрана в разделе “Инструменты – Платы“. Если все выбрано то подключаем к ПК микроконтроллер ESP8266 и выбираем в “Инструменты – Порт” порт к которому подключен ESP8266.

Шаг 2 (копируем скетч в Arduino IDE):

#include ESP8266WiFi.h> #include OneWire.h> #include DallasTemperature.h> bool led1IsOn = false; bool led2IsOn = false; bool led3IsOn = false; const int LED_0 = 16; const int LED_1 = 5; const int LED_2 = 2; const int oneWireBus = 4; const char* ssid = ""; const char* password = ""; float temperatureC = 0.0f; // Create an instance of the server // specify the port to listen on as an argument WiFiServer server(80); OneWire oneWire(oneWireBus); DallasTemperature sensors(&oneWire); void setup()  Serial.begin(115200); pinMode(LED_0, OUTPUT); pinMode(LED_1, OUTPUT); pinMode(LED_2, OUTPUT); delay(1000); digitalWrite(LED_0, HIGH); digitalWrite(LED_1, HIGH); digitalWrite(LED_2, HIGH); delay(1000); digitalWrite(LED_0, LOW); digitalWrite(LED_1, LOW); digitalWrite(LED_2, LOW); delay(10); sensors.begin(); // Connect to WiFi network Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED)  delay(500); Serial.print("."); > Serial.println(""); Serial.println("WiFi connected"); // Start the server server.begin(); Serial.println("Server started"); // Print the IP address Serial.println(WiFi.localIP()); > void loop()  // Check if a client has connected sensors.requestTemperatures(); WiFiClient client = server.available(); if (!client)  return; > // Wait until the client sends some data Serial.println("new client"); while(!client.available()) delay(1); > // Read the first line of the request String req = client.readStringUntil('\r'); Serial.println(req); // Match the request controller(req, client); client.flush(); // Prepare the response String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; s += temperatureC; // Send the response to the client client.print(s); delay(1); Serial.println("Client disonnected"); // The client will actually be disconnected // when the function returns and 'client' object is detroyed > void controller(String req, WiFiClient client) if (req.indexOf("/temperature") != -1) temperatureC = sensors.getTempCByIndex(0); Serial.println("Showing temperature"); > else if(req.indexOf("/led1") != -1) setLedState(LED_0, led1IsOn); led1IsOn = !led1IsOn; > else if(req.indexOf("/led2") != -1) setLedState(LED_1, led2IsOn); led2IsOn = !led2IsOn; > else if(req.indexOf("/led3") != -1) setLedState(LED_2, led3IsOn); led3IsOn = !led3IsOn; > else  Serial.println("invalid request"); client.stop(); return; > > void setLedState(int led, bool state) if(!state) digitalWrite(led, HIGH); > else  digitalWrite(led, LOW);> > 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

ayoubElhoucine/Connect-Android-to-Arduino-via-Wifi

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Android wifi is a demo aplication that shows you how to connect and send messages to Arduino via wifi communication , the demo android app is also provided in google play under the link https://play.google.com/store/apps/details?id=com.tofaha.Android_wifi . the communication system based on sever/client communication , in which android app act like client and the arduino program as server.

in the android side the steps to communicate to arduino is very easy , the socket client is used for that , the socket client needs two parameters to find the tareget wifi module the first parameter is the wifi module IP address , and the seconde parameter is the port number , well the first thing you need to do is to open a socket connection , the server side (arduino with wifi module) has to be launched first and then the client (android device) will reach the server by the ip address and port number , you should be aware of where you instanciate the socket because it has to be instanciated in diffrent thread then the UI thread , if you do it in UI thread the app will crash , here sample how to open socket connection inside asyncTask:

class OpenConnection(private val ipAddress: String, private val portNumber: Int) : AsyncTask() < override fun doInBackground(vararg voids: Void): Void? < try < MyData.socket = Socket(ipAddress, portNumber) System.out.println("connection opened") >catch (e: IOException) < e.printStackTrace() >return null > > 

and to send messages to server , you will need printWriter object to write in socket ibject that you already created and the socket will do the rest , here how you can do it :

class SendMessages(msg: String) : AsyncTask()

internal var msg = "" init < this.msg = msg >override fun doInBackground(vararg voids: Void): Void? < try < val out = PrintWriter(BufferedWriter(OutputStreamWriter(MyData.socket .getOutputStream())), true) out.println(msg) println("message send") >catch (e: IOException) < e.printStackTrace() >return null > 

and to recieve messages from server , all you need to do is create an instance of bufferReader and pass the socket to it as parameter , and of course you need to do that inside loop with time out as optional , so whenever the server send message the socket object will receive it and bufferdReader will read the message from socket and you write it to the UI thread , here is the code (I used anko library in this code):

to close the connection that what you do : socket.close() method :

class CLoseConnection : AsyncTask()

override fun doInBackground(vararg params: Void?): Void? < try < MyData.socket?.close() System.out.println("connection closed") >catch (e: IOException) < e.printStackTrace() >return null > 

Server Side (Arduino with wifi module)

in the server side I use arduino with wifi module(ESP8266) , well the first thing you need to consider is how to communicate arduino with the module , the communication will be done by the serial communication(Rx/Tx) , arduino board contains UART(Universal Asynchronious Receiver Transmmiter) , and the number of UART that arduino board contain is depend on the type of arduino like arduino uno has only one UART , so we are going to use the library of the serialSoftwar in arduino and by this library we can write and read to serial buffer (Rx/Tx) , after that we attach the Rx and Tx pin to Tx and Rx pin of the ESP8266 , this is how to communicate arduino with ESP8266 :

Communicate arduino with esp module

#include SoftwareSerial ESP8266(2,3); //(Rx/Tx) that means you have to attach pin 2 with esp Tx and pin 3 with esp Rx 

ESP configuration and setup with AT commands

after the communication is established you now need to configure ESP as you need it to work , and that will be done by the ATcommand , in arduino IDE we will type the ATcommand and write it to the serialSoftware :

void sendESP8266Cmdln(String cmd, int waitTime) < ESP8266.println(cmd); delay(waitTime); clearESP8266SerialBuffer(); >void setup() < Serial.begin(9600); ESP8266.begin(115200); // change this value to your wifi module (esp8266) baud rate do< ESP8266.println("AT"); delay(1000); if(ESP8266.find((char*)"OK")) < Serial.println("Module is ready"); delay(1000); clearESP8266SerialBuffer(); //configure ESP as station sendESP8266Cmdln("AT+CWMODE=1",1000); //Join Wifi network sendESP8266Cmdln("AT+CWJAP="+ssid+","+pass,6500); //Get and display my IP sendESP8266Cmdln("AT+CIFSR", 1000); //Set multi connections sendESP8266Cmdln("AT+CIPMUX=1", 1000); //Setup web server on port 80 sendESP8266Cmdln("AT+CIPSERVER=1,3333",1000); Serial.println("Server setup finish"); FAIL_8266 = false; >else < Serial.println("Module have no response."); delay(500); FAIL_8266 = true; >>while(FAIL_8266); ESP8266.setTimeout(100); > 

Receive messages from client

after the configuration and setup of the ESP now you are ready to send and recieve data from client : to recieve data from client is very easy step , first you need to prepare the server and that will be done in the setup part , after that you write this code inside the loop method :

to send data to client , well in this case to establish the client you need communication id , so if there are for exemple 5 client , so you need 5 communication id to send to each client , and in the case there is only one client you can use 0 as the value of the communication id :

connectionId = 0 ; void sendStringResponse(int connectionId, String content) < sendCIPData(connectionId,content); >void loop() < if ( Serial.available() )< String s = Serial.readString(); sendStringResponse(connectionId , s + "\r\n"); >> 

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Demo of a clear and simple way to interface Android and Arduino over a WiFi connection

License

hmartiro/android-arduino-wifi

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Demo of a clear and robust way of creating a serial communication link between an Arduino and an Android device using WiFi.

  • WiFi server using the WiFly Shield and associated library on Arduino
  • WiFi client socket implemented using AsyncTask in Android
  • UI for connecting, disconnecting, reading, and writing
  • Exception handling and error management to prevent crashes
  • Parsing of complete newline-delimited messages from the stream
  • Timeout detection using a ping system
  • Lots of comments

Requirements:

  • Android device with WiFi enabled
  • Arduino with a WiFly shield
  • Android Studio and an Arduino IDE
  • A WiFi network to connect to and a not-blocked port
  • Arduino — set your WiFi network name and password in Credentials.h .
  • Arduino — set your desired port number in wifi_demo.ino .
  • Flash the Arduino, then turn it on and open the serial monitor at 115200bps.
  • Wait for the WiFly to get an IP address.
  • Open the Android app, enter the address and port, and hit connect.
  • You should now be able to send messages and have them echoed back.
  • You can also type messages into the Aruino serial monitor to send them to the Android device (select newline endings).

Important files:

  • WiFly takes a long time (~20s) to connect to a network on startup (watch the LEDs).
  • After disconnecting from a client, the WiFly takes about 6 seconds before it can connect to another client (again, watch the LEDs).
  • I had an issue with a version of the WiFly library where it would not initialize until it heard a *READY* message from the chip, which never came. If you get stuck at WiFly.begin(), look into this.

About

Demo of a clear and simple way to interface Android and Arduino over a WiFi connection

Источник

Читайте также:  Чтобы посмотреть доступные сети включите wifi
Оцените статью
Adblock
detector