Arduino Sketches


Time to Code !
Blink Sketch

 void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(2, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(2, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);   // wait for a second
  digitalWrite(2, LOW);// turn the LED off by making the voltage LOW
  delay(1000);   // wait for a second
}
  
Read Serial Data
int incomingByte = 0;
String a;

void setup() {
Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
while(Serial.available()) { // Waits for Serial input from user
incomingByte = Serial.read(); // Reads one Character
//a=Serial.readString();
Serial.print("I received: ");
Serial.println(incomingByte,DEC);
//Serial.println(a);
}
}
  
Simple WebServer
#include <ESP8266WiFi.h> 

const char* ssid = "";
const char* password = "";
int ledPin = 2; // GPIO13
WiFiServer server(80);

void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
  
void loop() {
// Check if a client has connected
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 request = client.readStringUntil('\r');
Serial.println(request);
client.flush();
int value = LOW;
if (request.indexOf("/1") != -1)  {
digitalWrite(ledPin, HIGH);
value = HIGH;
}
if (request.indexOf("/0") != -1)  {
digitalWrite(ledPin, LOW);
value = LOW;
}
// Return the response
delay(1);
Serial.println("Client disonnected");
Serial.println("");
} 
HTML Formatted Server
#include <ESP8266WiFi.h> 
const char* ssid = "";
const char* password = "";
 
int ledPin = 2; // GPIO13
WiFiServer server(80);
 
void setup() {
  Serial.begin(115200);
  delay(10);
 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
   // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  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.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
 
}
 
void loop() {
  // Check if a client has connected
  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 request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
 
  // Match the request
 
  int value = LOW;
  if (request.indexOf("/LED=ON") != -1)  {
digitalWrite(ledPin, HIGH);
value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1)  {
digitalWrite(ledPin, LOW);
value = LOW;
  }
 
// Set ledPin according to the request
//digitalWrite(ledPin, value);
 
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html style=\"background-color:#222930; padding:180px;text-align: center; color: white; font-family: \"Trebuchet MS\", Helvetica, sans-serif\">"); 
  client.println("<div id=\"wrapper\">");
  client.print("<h1>Led pin is now: "); 
  if(value == HIGH) {
client.print("On");
  } else {
client.print("Off");
  }
  client.println("</h1><br><br>");
  client.println("<a href=\"/LED=ON\"\"><button style=\"background-color: #4CAF50; font-size: 24px; border: none; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);\">Turn On </button></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
  client.println("<a href=\"/LED=OFF\"\"><button style=\"background-color: #f44336; font-size: 24px; border: none; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);\">Turn Off </button></a><br />");  
  client.println("</div>");
  client.println("</html>");
 
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
 
}
Thunkable Code
#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#define LED 2 // Control Onboard LED of esp8266
//---------------------------------------------------------------
//Use Progmem to utilize esp8266's flash mem
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<center>
<h1>Control GPIO Using HTML</h1><br>
<a href="ledOn">LED ON</a><br>
<a href="ledOff">LED OFF</a><br>
<hr>
</center>
 
</body>
</html>
)=====";
//---------------------------------------------------------------
//SSID and Password of your WiFi router
const char* ssid = "IOT_Random_AP";
const char* password = "password";

ESP8266WebServer server(80); //Start Server on port 80 (Basic HTTP)

//===============================================================
// These Functions are to be declared before its called so that it can handle the web requests
//===============================================================

void handleRoot() { // This is Required to handle "/" requests
 Serial.println("You called root page");
 String s = MAIN_page; //Read HTML contents
 server.send(200, "text/html", s); //Send web page
}
 
void handleLEDon() { 
 Serial.println("LED on page");
 digitalWrite(LED,LOW); //LED is connected in reverse
 server.send(200, "text/html", "LED is ON"); //Send ADC value only to client ajax request
}
 
void handleLEDoff() { 
 Serial.println("LED off page");
 digitalWrite(LED,HIGH); //LED off
 server.send(200, "text/html", "LED is OFF"); //Send ADC value only to client ajax request
}

void toggle() {
  int i=0;
  int gpio = server.arg("GPIO").toInt();
  pinMode(gpio, OUTPUT);
  String onoroff = server.arg("Status");
  if(onoroff=="ON"){
  digitalWrite(gpio, HIGH);
  server.send(200,"text/plain","Turned ON");
  }
  else if(onoroff=="OFF")
  {
  digitalWrite(gpio, LOW);
  server.send(200,"text/plain","Turned OFF");
  } 
  server.send(200,"text/plain","TOGGLE");
 }


void setup(void){
  Serial.begin(115200);  
 // WiFi.begin(ssid, password);     //Connect to a WiFi router || COMMENT THIS LINE IF AP METHOD IS USED
  WiFi.softAP(ssid, password);    //ESP8266 is converted as an Access Point || COMMENT THIS LINE IF CLIENT METHOD IS USED
  Serial.println(WiFi.softAPIP()); //Prints AP's IP Address || COMMENT THIS LINE IF CLIENT METHOD IS USED
  Serial.println(""); 
  pinMode(LED,OUTPUT); 
  digitalWrite(LED,HIGH);  
  
 //Comment till "#@!~" if AP Method is used
 /*
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  } 
  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address that's assigned to your ESP
  
  //#@!~ Comment it till here if AP Method is used
  */
  
  server.on("/", handleRoot);      //Which routine to handle at root location. This is display page
//  server.on("/ledOn", handleLEDon); //as Per  <a href="ledOn">, Subroutine to be called
//  server.on("/ledOff", handleLEDoff);
  server.on("/toggle", toggle); // Uncomment this to controll LED via Thunkable / URL with random GPIO
  server.begin();                  //Start server
  Serial.println("HTTP server started");
}  
void loop(void){
  server.handleClient();          //Handle client requests
}
DHT11 - Read Temp & Humd
#include <dht.h>
dht DHT;
#define DHT11_PIN 2
void setup()
{
  Serial.begin(115200);
  Serial.println("DHT TEST PROGRAM ");
  Serial.println(DHT_LIB_VERSION);
  Serial.println();
  Serial.println("H (%),\tT (C)");
}
void loop()
{
  if(DHT.read11(DHT11_PIN)){
  Serial.print(DHT.humidity, 1);
  Serial.print(",\t");
  Serial.println(DHT.temperature, 1);
  delay(2000);
  }
  else{
Serial.println("Error Reading Sensor data");
delay(2000);
  }  
}
MQTT Example
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "";
const char* password = "";
const char* mqtt_server = "";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
char receivedChar = (char)payload[i];
Serial.print(receivedChar);
if (receivedChar == '0')
// ESP8266 Huzzah outputs are "reversed"
digitalWrite(2, HIGH);
if (receivedChar == '1')
digitalWrite(2, LOW);

}
Serial.println();
}

void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
   //  client.publish("ledstatus", "hello world");
// ... and resubscribe
client.subscribe("ledstatus");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(2,OUTPUT);
}

void loop() {

if (!client.connected()) {
reconnect();
}
client.loop();
}
ThingSpeak Upload Data
#include <DHT.h>
#include <ESP8266WiFi.h>
// replace with your channel's thingspeak API key,
String apiKey = ""; 
const char* ssid = "";
const char* password = "";
const char* server = "api.thingspeak.com";
#define DHTPIN 2 // what pin we're connected to
DHT dht(DHTPIN, DHT11,15);
WiFiClient client;

 void setup() {
  Serial.begin(115200);
  delay(10);
  dht.begin();
  WiFi.begin(ssid, password);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

 void loop() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
  Serial.println("Failed to read from DHT sensor!");
  return;
  }
if (client.connect(server,80)) { // "184.106.153.149" or api.thingspeak.com
  String postStr = apiKey;
  postStr +="&field1=";
  postStr += String(t);
  postStr +="&field2=";
  postStr += String(h);
  postStr += "\r\n\r\n";
  client.print("POST /update HTTP/1.1\n");
  client.print("Host: api.thingspeak.com\n");
  client.print("Connection: close\n");
  client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
  client.print("Content-Type: application/x-www-form-urlencoded\n");
  client.print("Content-Length: ");
  client.print(postStr.length());
  client.print("\n\n");
  client.print(postStr);
  Serial.print(postStr);
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" degrees Celcius Humidity: ");
  Serial.print(h);
  Serial.println("% send to Thingspeak");
  }
  client.stop();
  Serial.println("Waiting...");
  // thingspeak needs minimum 15 sec delay between updates
  delay(20000);
  }
  
Cayenne Controll GPIO
    
//CAYENNE Library - https://github.com/myDevicesIoT/Cayenne-MQTT-ESP
// Use this sketch to controll LED from Cayenne Dashboard | Connect LED to GPIO2 / D4

#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
// WiFi network info.
char ssid[] = "";
char wifiPassword[] = "";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "";
char password[] = "";
char clientID[] = "";

unsigned long lastMillis = 0;

void setup() {
 Serial.begin(9600);
 Cayenne.begin(username, password, clientID, ssid, wifiPassword);
  pinMode(2, OUTPUT);
  digitalWrite(2,HIGH);
}

void loop() {
 Cayenne.loop();
}

CAYENNE_IN(0)
{
  digitalWrite(2, !getValue.asInt());
} 
Data upload to Cayenne
    
//CAYENNE Library - https://github.com/myDevicesIoT/Cayenne-MQTT-ESP
//**************Send Data to Channel********************
//Connect DHT Sensor to GPIO4 & LED to GPIO2

#include <DHT.h>
#define CAYENNE_PRINT Serial
#include  <CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
// WiFi network info.
char ssid[] = "";
char wifiPassword[] = "";

#define DHTPIN 4
DHT dht(4, DHT11);
// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "";
char password[] = "";
char clientID[] = "";

unsigned long lastMillis = 0;

void setup() {
  dht.begin();
 Serial.begin(9600);
 Cayenne.begin(username, password, clientID, ssid, wifiPassword);
  pinMode(2, OUTPUT);
  digitalWrite(2,HIGH);
}

void loop() {
 Cayenne.loop();
 float temp = dht.readTemperature();
 float hum = dht.readHumidity();
 Serial.print(temp );
 Serial.print("\t");
 Serial.println(hum);
 Cayenne.virtualWrite(1,temp, TYPE_TEMPERATURE, UNIT_CELSIUS);
 Cayenne.virtualWrite(2,hum, TYPE_RELATIVE_HUMIDITY, UNIT_PERCENT);
}

CAYENNE_IN(0)
{
  digitalWrite(2, !getValue.asInt());
}
Smart Room

Download APK for Android


#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Adafruit_NeoPixel.h>
ESP8266WebServer server;
#define PIN 1 // NeoPixel(WS2812B) is connected to GPIO1
#define NUM_LEDS 3 // Number to WS2812B LEDS
#define BRIGHTNESS 180
uint8_t pin_led = 2;
char* ssid = "";
char* password = "";
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);
byte neopix_gamma[] = {
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,
  1,  1,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,
  2,  3,  3,  3,  3,  3,  3,  3,  4,  4,  4,  4,  4,  5,  5,  5,
  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  9,  9,  9, 10,
  10, 10, 11, 11, 11, 12, 12, 13, 13, 13, 14, 14, 15, 15, 16, 16,
  17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 24, 24, 25,
  25, 26, 27, 27, 28, 29, 29, 30, 31, 32, 32, 33, 34, 35, 35, 36,
  37, 38, 39, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 50,
  51, 52, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68,
  69, 70, 72, 73, 74, 75, 77, 78, 79, 81, 82, 83, 85, 86, 87, 89,
  90, 92, 93, 95, 96, 98, 99,101,102,104,105,107,109,110,112,114,
  115,117,119,120,122,124,126,127,129,131,133,135,137,138,140,142,
  144,146,148,150,152,154,156,158,160,162,164,167,169,171,173,175,
  177,180,182,184,186,189,191,193,196,198,200,203,205,208,210,213,
  215,218,220,223,225,228,231,233,236,239,241,244,247,249,252,255 };
  
void setup()
  { 
  /*pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(14, OUTPUT);
  digitalWrite(0,LOW);
  digitalWrite(1,LOW);
  digitalWrite(3,LOW);
  digitalWrite(2,LOW);
  digitalWrite(14,LOW);*/
  WiFi.mode(WIFI_AP);
  //WiFi.begin(ssid,password); // Connect to Router when AP is disabled
  WiFi.softAP(ssid, password);
  Serial.begin(115200);
  // while(WiFi.status()!=WL_CONNECTED)
  //  {
  //   Serial.print(".");
  //   delay(500);
  //  }
  Serial.println("");
  Serial.print("IP Address: ");
  Serial.println(WiFi.softAPIP());
  server.on("/",[](){server.send(200,"text/plain","Hello World!");});
  server.on("/toggle",toggle);
  server.on("/setcolor",ws2812);
  server.on("/pmw",pmw);
  server.begin();
  strip.setBrightness(BRIGHTNESS);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  }

 void loop()
  {
  server.handleClient();
  }
  void toggle()
  {
  int i=0;
  int gpio = server.arg("GPIO").toInt();
  analogWrite(gpio, 0);
  pinMode(gpio, OUTPUT);
  String onoroff = server.arg("Status");
  if(onoroff=="ON"){
  digitalWrite(gpio, HIGH);
  server.send(200,"text/plain","Turned ON");
  }
  else if(onoroff=="OFF")
  {
  digitalWrite(gpio, LOW);
  server.send(200,"text/plain","Turned OFF");
  } 
  server.send(200,"text/plain","TOGGLE");
  
if(onoroff=="1"){
  for (i=0;i<=16;i++){
  digitalWrite(i, HIGH);
  server.send(200,"text/plain","Turned ON");
  }
  }
  else if(onoroff=="0")
  {
  for (i=0;i<=16;i++){
  digitalWrite(i, LOW);
  server.send(200,"text/plain","Turned OFF");
  }
  } 
  server.send(200,"text/plain","TOGGLE"); 
  }
  void pmw()
  {
  int gpio = server.arg("GPIO").toInt();
  int pmw = server.arg("pmw").toInt();
  pinMode(gpio, OUTPUT);
  pmw = map(pmw, 0, 100, 0, 255);
  analogWrite(gpio, pmw);
  server.send(200,"text/plain","PMW"); 
  }
  void ws2812()
  {
  String pixel_num = server.arg("pixel_num");
  String r = server.arg("R");
  String g = server.arg("G");
  String b = server.arg("B");
  String rsp = "LED #"+pixel_num+" is set to: "+r+", "+g+", "+b;
  server.send(200,"text/plain",rsp);
  colorWipe(strip.Color(r.toInt(), g.toInt(), b.toInt()), 0); 
  }
  void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
  strip.setPixelColor(i, c);
  strip.show();
  delay(30);
  }
  }

Comments

Post a Comment

Popular posts from this blog

Set up for IoT Using Arduino & ESP8266

Driver Installation