Skip to content

Instantly share code, notes, and snippets.

@prasertsakd
Created April 29, 2016 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasertsakd/cb3dc821d03aa7f51d5adf9c23871b74 to your computer and use it in GitHub Desktop.
Save prasertsakd/cb3dc821d03aa7f51d5adf9c23871b74 to your computer and use it in GitHub Desktop.
#include <ESP8266WiFi.h>
#include <WiFiUDP.h>
WiFiUDP UDP;
const char* ssid = "sensorNode";
const char* password = "1234567890";
boolean wifiConnected = false;
IPAddress ip = {192,168,0,255};
// UDP variables
unsigned int localPort = 8888;
boolean udpConnected = false;
void setup() {
// Initialise Serial connection
Serial.begin(115200);
// Initialise wifi connection
wifiConnected = connectWifi();
// only proceed if wifi connection successful
if(wifiConnected){
udpConnected = connectUDP();
if (udpConnected){
// initialise pins
pinMode(5,OUTPUT);
}
}
}
void loop() {
// check if the WiFi and UDP connections were successful
if(wifiConnected){
if(udpConnected){
UDP.beginPacket(ip, 8888);
UDP.write("Hello");
UDP.endPacket();
}
}
delay(500);
}
// connect to UDP – returns true if successful or false if not
boolean connectUDP(){
boolean state = false;
Serial.println("");
Serial.println("Connecting to UDP");
if(UDP.begin(localPort) == 1){
Serial.println("Connection successful");
state = true;
}
else{
Serial.println("Connection failed");
}
return state;
}
// connect to wifi – returns true if successful or false if not
boolean connectWifi(){
boolean state = true;
int i = 0;
WiFi.begin(ssid, password);
Serial.println("");
Serial.println("Connecting to WiFi");
// Wait for connection
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
if (i > 10){
state = false;
break;
}
i++;
}
if (state){
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else {
Serial.println("");
Serial.println("Connection failed.");
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment