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> ");
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 RoomDownload APK for Android
Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our.
ReplyDeleteSoftware Testing Services
Independent Software Testing Services
Functional Testing Services
QA Automation Testing Services
eCommerce Testing Services
Performance Testing Services
Security Testing Services
API Testing Company
Regression Testing Services
Mobile App Testing Services
Thank you so much for this nice information. Hope so many people will get aware of this and useful as well. And please keep update like this.
ReplyDeleteServerless Data Warehouse
Benefits of Agile Testing
Top Node.js Frameworks
Ai in banking
Data Migration Tools
Big Data Companies
Penetration Testing Companies
Software Testing Companies