Hi guys. I have been trying connect my Android with my ESP8266 by AP, but i don't know why sometimes works and sometimes NOT! If any of u can help me.
Codes:
ESP8266
#define D1 10
#define D2 2
#define D3 0
#define D4 4
#define D5 5
#define D6 9
#define D7 13
#define D8 12
#define D9 14
#define D10 16
char flag1;
String esid;
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <WiFiUDP.h>
String s = "";
String s0 = "";
String string1 = "";
String s1 = "1";
String s2 = "2";
String s9 = "9";
String s10 = "10";
String s11 = "11";
String s12 = "12";
String s13 = "13";
String s14 = "14";
ESP8266WebServer server(8888);
unsigned int localPort = 8888;
WiFiUDP UDP;
boolean udpConnected = false;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
char ReplyBuffer[] = "5"; // a string to send back
int serv0 = 0;;
int serv1 = 0;;
int serv = 0;
int serv2 = 0;
int led2 = 0;
const int analogInPin = A0;
boolean connectUDP();
void handleRoot() {
server.send(200, "text/html", "<h1>You are connected</h1>");
}
void setup()
{
// delay(10);//1000
Serial.begin(115200);
EEPROM.begin(512);
Serial.println();
pinMode(D2, OUTPUT);
digitalWrite(D2, LOW);
Serial.print("Configuring access point...");
/* You can remove the password parameter if you want the AP to be open. */
//WiFi.mode(WIFI_STA);
//WiFi.softAP("RedeESP");
IPAddress myIP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(myIP);
server.on("/", handleRoot);
server.begin();
Serial.println("HTTP server started");
udpConnected = connectUDP();
if (udpConnected)
{
}
}
void loop()
{
server.handleClient();
if (udpConnected)
{
// if there’s data available, read a packet
int packetSize = UDP.parsePacket();
if (packetSize)
{
Serial.println("");
Serial.print("Received packet of size ");
Serial.print("From ");
IPAddress remote = UDP.remoteIP();
for (int i = 0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(UDP.remotePort());
// read the packet into packetBufffer
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
if (packetSize > 1 && packetSize < 3)
{
serv0 = packetBuffer[0];
serv0 = serv0 - 48;
serv1 = packetBuffer[1];
serv1 = serv1 - 48;
serv = serv1 + (serv0 * 10);
}
if (packetSize > 2 && packetSize < 4)
{
serv0 = packetBuffer[0];
serv0 = serv0 - 48;
serv1 = packetBuffer[1];
serv1 = serv1 - 48;
serv2 = packetBuffer[2];
serv2 = serv2 - 48;
serv = serv2 + (serv1 * 10) + (serv0 * 100);
}
if (packetSize > 3 && packetSize < 5)
{
serv0 = packetBuffer[0];
serv0 = serv0 - 48;
serv1 = packetBuffer[1];
serv1 = serv1 - 48;
serv2 = packetBuffer[2];
serv2 = serv2 - 48;
char serv3 = packetBuffer[3];
serv3 = serv3 - 48;
serv = serv3 + (serv2 * 10) + (serv1 * 100) + (serv0 * 1000);
}
if (packetSize > 0 && packetSize < 2)
{
serv = packetBuffer[0];
serv = serv - 48;
}
s = "";
for (int j = 0; j < packetSize; j++)
{
s += (String)packetBuffer[j];
}
Serial.println("string");
Serial.println(s);
string1 = s;
s = "";
if (serv == 11)
{
led2 = 1;
digitalWrite(D2, HIGH);
UDP.println("11");
serv = 0;
}
if (serv == 12)
{
led2 = 0;
digitalWrite(D2, LOW);
UDP.println("12");
serv = 0;
}
}
}
}
boolean connectUDP() {
boolean state = false;
Serial.println("");
Serial.println("Connecting to UDP");
if (UDP.begin(localPort) == 1) {
Serial.println("Connection successful");
state = true;
}
else {
}
return state;
}
Android
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Boolean led2,flag;
static WifiManager wifiManager;
Context context;
WifiConfiguration conf;
public static String networkSSID="RedeESP";
public static String networkPass="";
byte[] buf = new byte[1024];// Utilizado para enviar informação para o ESP em forma de Byte
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
led2=flag=true;
context=this;
// this is for thread policy the AOS doesn't allow to transfer data using wifi module so we take the permission
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// conected with a wifi button.. it connect to esp module when it is pressed
//remember the nework ssid and pasword needs to be the same as given here
//other it won't connect
public void wifi_connect(View v){
wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if(flag){
turnOnOffWifi(context, flag);
flag=false;
Toast.makeText(getApplicationContext(), "turning on...", Toast.LENGTH_SHORT).show();
//wifi configuration .. all the code below is to explain the wifi configuration of which type the wifi is
//if it is a WPA-PSK protocol then it would work
conf = new WifiConfiguration();
conf.SSID = "\"" + networkSSID + "\"";
conf.preSharedKey = "\"" + networkPass + "\"";
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
conf.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
conf.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
int netid= wifiManager.addNetwork(conf);
wifiManager.disconnect();
wifiManager.enableNetwork(netid, true);
wifiManager.reconnect();
} else {
turnOnOffWifi(context, flag);
flag = true;
Toast.makeText(getApplicationContext(), "turning off...", Toast.LENGTH_SHORT).show();
}
}
// when LED 3 BUTTON is pressed
public void led_2(View v){
if(led2){
led2=false;
Client a=new Client();
buf=null;
buf=("11").getBytes();
Toast.makeText(getApplicationContext(), "turning off...", Toast.LENGTH_SHORT).show();
a.run();
Toast.makeText(MainActivity.this, "LED 2 ON", Toast.LENGTH_SHORT).show();
}else{
led2=true;
Client a=new Client();
buf=null;
buf=("12").getBytes();
a.run();
Toast.makeText(MainActivity.this, "LED 2 OFF", Toast.LENGTH_SHORT).show();
}
}
public static void turnOnOffWifi(Context context, boolean isTurnToOn) {
wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(isTurnToOn);
}
//used to send data to esp module
public class Client implements Runnable{
private final static String SERVER_ADDRESS = "192.168.4.1";//public ip of my server
private final static int SERVER_PORT = 8888;
public void run(){
InetAddress serverAddr;
DatagramPacket packet;
DatagramSocket socket;
try {
serverAddr = InetAddress.getByName(SERVER_ADDRESS);
socket = new DatagramSocket(); //DataGram socket is created
packet = new DatagramPacket(buf, buf.length, serverAddr, SERVER_PORT);//Data is loaded with information where to send on address and port number
socket.send(packet);//Data is send in the form of packets
socket.close();//Needs to close the socket before other operation... its a good programming
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}