Welcome to the ESP8266 Mongoose-OS Module on WiFi. In this module, we will explore how to configure and utilize WiFi connectivity on the ESP8266 microcontroller using Mongoose-OS firmware.
The ESP8266 is a powerful microcontroller with built-in WiFi capability, making it a popular choice for IoT (Internet of Things) projects. Mongoose-OS is an open-source firmware for microcontrollers that provides a development environment for building IoT applications.
In this module, we will cover topics such as configuring WiFi settings, connecting to WiFi networks, handling WiFi events, and utilizing WiFi functionalities in IoT applications. Whether you’re a beginner or an experienced developer, this module will provide you with the knowledge and skills to effectively use WiFi on the ESP8266 with Mongoose OS.
Let’s dive into the world of WiFi connectivity with the ESP8266 and Mongoose-OS!
By default when flashing the firmware after ESP8266 WiFi configured as a AP mode in the WiFI AP SSID name of Mongoose_????? here ???? is the chip id and password is Mongoose .
FAQ
How to Set ESP8266 to AP mode?
How to Set ESP8266 as Hotpots?
Steps to follow
Go to the Device files tab in a web browser using the mos tool. (IP address http://127.0.0.1:1992/#files )
Change the ap credential or set the credential in the conf0.json file. (Refer Below Image)
Code Example
Enable AP Mode : “enable”: true, .
Disable AP Mode : “enable”: false, .
You can hide ESP8266 AP mode list using “hidden”: false, (Not shown WiFi available list).
Here’s an example code snippet to connect an ESP8266 to a WiFi router using Mongoose OS:
load('api_config.js'); // Load the Mongoose OS configuration API
load('api_net.js'); // Load the Mongoose OS network API
// Configure WiFi settings
let ssid = 'YourWiFiSSID'; // Replace 'YourWiFiSSID' with your WiFi network SSID
let password = 'YourWiFiPassword'; // Replace 'YourWiFiPassword' with your WiFi network password
// Connect to WiFi
Net.connect({
ssid: ssid,
pass: password,
auth: Net.AUTH_WPA2_PSK // Use WPA2 authentication (change if necessary)
});
// Event handler for WiFi connection status change
Net.setStatusEventHandler(function(ev, arg) {
if (ev === Net.STATUS_DISCONNECTED) {
print('WiFi disconnected');
} else if (ev === Net.STATUS_CONNECTING) {
print('WiFi connecting...');
} else if (ev === Net.STATUS_CONNECTED) {
print('WiFi connected');
}
});
Replace 'YourWiFiSSID' with the SSID of your WiFi network and 'YourWiFiPassword' with the password of your WiFi network. This code will attempt to connect the ESP8266 to the specified WiFi network using the provided credentials. It also includes event handlers to print status messages when the WiFi connection status changes.
Starting with C programming offers great opportunities! Let’s kick things off with a brief overview of the basics to get you started:
Remember, mastering programming requires time and practice, so don’t get discouraged if you face difficulties along the way. Keep coding and experimenting, and you’ll improve over time!
Setup your environment: You need a compiler to write and run C programs. Popular choices include GCC (GNU Compiler Collection), Clang, and Visual Studio for Windows. Install one based on your operating system.
Choose a text editor or IDE: You can write C code in any text editor, but using an Integrated Development Environment (IDE) can make your life easier. Some popular options include Visual Studio Code, Atom, Sublime Text, and Eclipse.
Learn the basics: Familiarize yourself with basic C syntax, such as variables, data types, operators, loops (like for and while loops), conditional statements (if-else), functions, arrays, and pointers. These are the building blocks of any C program.
Compile and run: Save your program with a “.c” extension (e.g., hello.c). Open a terminal or command prompt, navigate to the directory containing your program, and compile it using the compiler you installed. For GCC, the command would be: gcc hello.c -o hello This command compiles your code into an executable named “hello”. Then, run the executable: ./hello You should see “Hello, World!” printed to the screen.
Practice: Once you’ve got the basics down, practice writing more complex programs. Try solving small programming challenges or work on projects that interest you.
Learn from resources: There are plenty of online resources, tutorials, and books available to help you learn C programming. Websites like GeeksforGeeks, Tutorialspoint, and the C programming subreddit can be valuable learning resources.
Debugging: Learn how to debug your programs when something goes wrong. Understanding concepts like breakpoints, stepping through code, and reading error messages will be immensely helpful.
Explore more advanced topics: Once you’re comfortable with the basics, you can delve into more advanced topics like memory management, file handling, data structures, and algorithms.
Write your first program
A classic first program is the “Hello, World!” program. It simply prints “Hello, World!” to the screen. Here’s how you can write it:
#include <stdio.h>
int main() {
printf("Arun E, World!\n");
return 0;
}
Join a community
Participating in online forums or joining a local programming group can provide support, encouragement, and opportunities to learn from others.
Constants
(Two types : Primary, Secondary)
When the program execution time constants should not change their value (A constant is an entity that doesn’t change)
Constant Type
Constant Sub Type
Type
Type
Description
Example
Primary Constant
Numeric Constant (Three Type)
Integer
Decimal
Decimal constants are 0 to 9 numbers
86 , 94 , -133
Primary Constant
Numeric Constant (Three Type)
Integer
Octal
Octal constants are 0 to 7 numbers. First number should be ‘0‘
0137 , -0567 , 034
Primary Constant
Numeric Constant (Three Type)
Integer
Hexadecimal
Hexadecimal constants are 0 to 9 and A to F. First number should be start with ‘0x’ or ‘0X’
0X73A , 0x89FA
Primary Constant
Real or floating point Constant (Two types)
Fractional form
Fractional form
dot points are consider as fractional forms
-0.567 , .64 , 24.0
Primary Constant
Real or floating point Constant (Two types)
Exponential form
Exponential form
Rules: May use mantissa and exponent symbols Should not use .dot point in exponent Should have at-least one digit in exponent
0.2571e-5, mantissa – 0.2571, exponent – -5
Primary Constant
Character Constant
Character Constant
Character Constant
Character constant are come with two single quotes (‘)
Blank space, Horizontal tab, Carriage return, New line , Form feed.
Reserved Keywords
C89 Reserved Keywords
According to C89 standards c has 32 reserved keywords
auto
do
goto
signed
unsigned
break
double
if
sizeof
void
case
else
int
static
volatile
char
enum
long
struct
while
const
extern
register
switch
continue
float
return
typedef
default
for
short
union
Enum:
Enumeration (or enum) represents a user-defined data type in C. It primarily assigns names to integral constants, making programs easier to read and maintain
-- or ++ are can’t be done on enum value.
C99 Reserved Keywords
According to C99, C has 5 more reserved keywords
_Bool
_Complex
_Imaginary
inline
restrict
C11 Reserved Keywords,
According to C11, C has 7 more reserved keywords
_Alignas
_Alignof
_Atomic
_Generic
_Noreturn
_Static_assert
_Thread_local
Identifiers
Rules
Should not use keyword as a identifier.
First letter should be English word.
May use Uppercase and Lowercase letters.
Can use _ underscore as a first letter of Identifier.
Identifiers are case sensitive(below both identifiers are not same)
Example
Valid Identifiers: Sum, basic_pay, a1, Ab, ab.
Invalid Identifiers: 8a – First letter should not be numbers, auto – auto is a keyword
Variables
When the program execution time variable may be change their value.(A variable is an entity that does change),
Example: Sum , average , basic_pay , basic-pay , A0 etc (valid variables)
Generally variables are store in different storage class types : automatic, static , extern , register
Declaring a variable
Rules
should be declared data type of variable.
data types name should be declared data type’s
if declare multiple variables in a single data type, separate each by, operator
Every declaration should end with;semicolon
Syntax
datatype variable_1, variable_2, …..variable_n ;
Example-1:int a, b , c; //here a,b, c are integer variables
Example-2:float salary; //here salary is a floating type variable.
Use of variable declaration
Compiler can allocate a memory when we declared data type variable
Variable Initializing
Syntax: datatype variable_name = initial value;
Example: int sum = 1;
Assigning Value to Variable
Assigning Operator = equal is used to assign value to variable in
Syntax for value : Variable_name = value; Ex: x = 20;
Syntax for another variable:variable_name = variable; Ex: y = x;
Syntax for expressions:variable_name = expression; Ex: z = x+y;
Exercise
Q : Which of the following is not a valid variable name in C? A. 1 a @ B. a 1 2 C. a b 123 D. a b c 123
Answer: Option A (Explanation: First character must be alphabet).
You cannot print (automagically) the type of a variable in C. Variables and their types are only known at compile time.
At runtime, there is no variables (only locations & values) and almost no types:
Data types
Data types in any of the language means that what are the various type of data the variables can have in that particular language.
Whenever a variable is declared it becomes necessary to define data type that what will be the type of data that variable can hold.
basic datatype: char , int , float and double.
type modifier (Qualifier) : short , long , signed and unsigned
Rules : Every variable should have any one of the following data type
Types
bit Size
Byte Size
Range
char (or) signed char
8
1
127 to 127
unsigned char
8
1
0 to 255
int (or) signed int
16
2
-32,767 to 32,767
unsigned int
16
2
0 to 65,535
short int (or) signed short int
8
1
-127 to 127
unsigned short int
8
1
0 to 255
long int (or) signed long int
32
4
-2,147,483,647 to 2,147,483,647
unsigned long int
32
4
0 to 4,294,967,295
float
32
4
3.4E-38 to 3.4E+38
double
64
8
1.7E-308 to 1.7E+308
long double
80
10
3.4E-4932 to 1.1E+4932
unsigned sort
16
2
The various general types of data are:
General type
General Sub type
Data Type
Number type data
Integer Type
int
Number type data
Float type (Three Types)
Float
Number type data
Float type (Three Types)
double
Number type data
Float type (Three Types)
long double
Character type data
char
String type data
Boolean type data
bool
C Programming Structure
Pr-processor Commands
Type definition
Function prototype – Declare function type and variable passed to functions
Variable – We must have a main function in every c programs
//pre processor command
#include <stdio.h>
//variable type definition ("a" is a variable and integer type)
int a;
//Function prototype ("Func" is a integer type function name with arguments "a", "b" is a variables integer type)
int Func(int b, int c);
//main function integer type
int main()
{
//"E" Local variable integer type
int E;
C statements;
}
Note : All the programs are run in gnu gcc of linux.
Escape sequence
Escape sequence is a character constant or string constants, its a non graphical character or printable.
Escape sequence
Example
\a – alarm character
\b – back space
\f – form feed
\n – new line
\r – carriage return
Carriage return is known as cartridge return and often shortened to CR, <CR> or return.
It is a control character or mechanism used to reset a device position to the beginning of a line of text.
It is closed associate with the line feed and newline concepts.
\t – horizontal tab
\v – vertical tab
\\ – back slash
\? – question mark
\’ – single quote
\” – double quote
\000 – character representation
\xbh – character representation
\0 – nul character
Difference between ‘/0’ and ‘\0’ in C programming?‘\0’ – Null terminator in array.
Header files (Two types)
Predefined Header files
Syntax : #include<file_name> (Stored in Specified directories).
If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path.
User defined Header files
Syntax : #include “file_name” (Stored in Locally saved programs).
If a header file is included with in “ “ , then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.
Command Statements
/* Commands */ – Commands in paragraph
// commands – command in single line
Format specifier
Specifier
Description
%i
Can be used to input integer in all the supported format.
File management in the C programming language involves operations related to reading from and writing to files. Here are some key concepts and functions for file management in C:
Storage classes in C determine a variable’s scope, visibility, lifetime, and storage location. They include auto, extern, static, and register. The default initial value varies based on the storage class. Scope defines variable visibility, while lifetime dictates its persistence in memory.
Scope: The extent to which different parts of a program have access to the variable, determining its visibility.
Lifetime refers to the duration for which the variable persists in memory, encompassing the allocation and deallocation of its storage. The scope also influences a variable’s lifetime.
variable types(Global variable)
Variable Type
Lifetime
Scope
Global Variable
Only destroyed when the program terminates
Only the program
Local Variable
Allocated memory when entering the function, destroyed when leaving
A variable declared inside a function without any specified storage class is termed an auto variable.
Only usable within functions.
Created and destroyed automatically upon function call and exit, respectively.
Compiler assigns them garbage values by default.
The stack memory stores local variables.
By default, every local variable in a function is of auto storage class.
Example:
void f() {
int i; // auto variable
auto int j; // auto variable
}
Global variable
A variable declared outside any function is a global variable.
Any function in the program can change its value.
initializing
int – 0
char – \0
float – 0
double -0
pointer – null
Register Keyword
The “register” keyword specifies that local variables are stored in a register for rapid access, particularly for counters. These variables offer quicker access than normal ones, but only a limited number can be placed in registers. While the compiler sees “register” as a suggestion, it ultimately decides. Typically, compilers optimize and determine variable allocation.
Register Note 1:
Attempting to access the address of a register variable results in a compile error. For instance:
int main() {
register int i = 10;
int *a = &i; // Compile error
printf("%d", *a);
getchar();
return 0;
}
Register Note 2:
You can use the register keyword with pointer variables. Below is a valid example:
int main() {
int i = 10;
register int *a = &i;
printf("%d", *a); // Output: 10
getchar();
return 0;
}
Resistor Note 3:
Register is a storage class, and C prohibits multiple storage class specifiers for a variable. Therefore, you cannot use register with static.
int main() {
int i = 10;
register static int *a = &i; // Error
printf("%d", *a);
getchar();
return 0;
}
Register Note 4:
There’s no limit to the number of register variables in a C program. However, the compiler may choose to allocate some variables to registers and others not.
static keyword
static means its take only single or same memory.
static is initialized only once and remains into existence till the end of program
static assigned 0 (zero) as default value by the compiler.
A static local variables retains its value between the function call and the default value is 0.
If a global variable is static then its visibility is limited to the same source code.
Static variables stored in Heap(Not in Stack memory)
The following function will print 1 2 3 if called thrice.
Example
void f() { static int i; ++i; printf(“%d “,i); }
In “static int a[20];”, variable “a” is declared as an integer type and static. When a variable is declared as static, it is automatically initialized to the value ‘0’ (zero).
What is a static function?
A function prefixed with the static keyword is called a static function.
You would make a function static if it should only be called within the same source code or be visible to other functions in the same file.
static has different meanings in in different contexts.
When specified on a function declaration, it makes the function local to the file.
When specified with a variable inside a function, it allows the vairable to retain its value between calls to the function
storage class specifier
typedef – typedef is the storage class specifier.
It does not reserve the storage.
It is used to alias the existing type. Also used to simplify the complex declaration of the type.
The widget will appear 5 seconds after the page finishes loading. if you want to change this delay, change the number 1000 to a greater or lessor number in this post .delay(5000)
By default, the like box only shows up the first time the user visit your page. if you world like the pfacebooj box to popup every time the page loads, then remove this line of ocde $.cookie(‘popup_facebook_box’, ‘yes’, { path: ‘/’, expires: 7 });
If you want to display only when visit your homepage, go to “Template”->Edit HTML->Serch by (CTRL+F) </body> then paste the facebook popup widget right abovethe body tag make sure to include the conditional tag below <b:if cond=’data:page.type == “index”‘>ADD THE FACEBOOK WIDGET CODE HERE </b:if> –>Save
ZigBee is a low-power, low-data-rate wireless communication embedded protocol based on the IEEE 802.15.4 standard. It is commonly used for creating networks of low-power devices in applications such as home automation, industrial control, and smart energy management.
ZigBee is designed to be simple, cost-effective, and reliable, making it ideal for use in battery-powered devices that need to communicate over short distances. It uses a mesh networking topology, allowing devices to communicate with each other directly or through intermediate nodes in the network.
ZigBee supports a range of applications including lighting control, HVAC control, security systems, and remote monitoring. It provides robust security features to ensure the confidentiality and integrity of data exchanged between devices.
Overall, ZigBee is a popular choice for building wireless sensor networks and other low-power, low-data-rate communication systems.
Low power consumption: ZigBee is designed for low-power devices, making it ideal for battery-powered devices that need to operate for long periods without frequent battery replacements.
Low data rate: ZigBee is optimized for applications that do not require high data transfer speeds, making it suitable for applications such as home automation and industrial control.
Robust mesh networking: ZigBee’s mesh networking topology allows for reliable communication even in challenging environments with obstacles and interference.
Cost-effective: ZigBee is a cost-effective solution for building wireless sensor networks and other low-power communication systems.
Security features: ZigBee provides strong security features to protect data communication between devices, ensuring confidentiality and integrity.
Disadvantages of ZigBee:
Limited data rate: ZigBee’s low data rate may not be suitable for applications that require high-speed data transfer, such as video streaming or large file downloads.
Limited range: ZigBee’s range is typically limited to a few tens of meters, which may not be sufficient for applications that require long-range communication.
Interference: ZigBee operates in the crowded 2.4 GHz frequency band, which can be prone to interference from other wireless devices operating in the same frequency range.
Scalability: While ZigBee supports scalable networks, managing large networks with hundreds or thousands of devices can be challenging.
Compatibility: ZigBee devices may not be compatible with devices using other wireless communication protocols, limiting interoperability in mixed-device environments.
This tutorial “ESP8266 NodeMCU HTTP Module” will discuss. The ESP8266 NodeMCU module is a popular microcontroller board based on the ESP8266 Wi-Fi chip. It’s widely used for IoT (Internet of Things) projects due to its low cost, built-in Wi-Fi capabilities, and ease of programming. One common use case of the ESP8266 NodeMCU is handling HTTP requests and responses, allowing it to communicate with web servers, APIs, and other devices over the internet.
HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the World Wide Web. With the ESP8266 NodeMCU, you can leverage HTTP to send and receive data, control devices remotely, and interact with cloud services.
In this example, we’ll explore how to configure the ESP8266 NodeMCU to connect to a Wi-Fi network, monitor Wi-Fi events, and perform HTTP operations such as sending POST requests to a web server. Additionally, we’ll set up a GPIO pin to trigger an action when its state changes, showcasing how the ESP8266 NodeMCU can interact with external devices.
Execute a custom HTTP request for any HTTP method.
http.delete()
Executes a HTTP DELETE request. Note that concurrent requests are not supported.
Syntax : http.delete(url, headers, body, callback
Parameters
url The URL to fetch, including the http:// or https:// prefix
headers Optional additional headers to append, including \r\n; may be nil
body The body to post; must already be encoded in the appropriate format, but may be empty
callback The callback function to be invoked when the response has been received or an error occurred; it is invoked with the arguments status_code, body and headers. In case of an error status_code is set to -1.
Returns : nil
HTTP Get Example
Read your thing-speak text file from the below code for ESP8266 NodeMCU Module HTTP.
station_cfg={}
station_cfg.ssid="ArunEworld" -- Enter SSID here
station_cfg.pwd="8300026060INDIA" --Enter password here
server_link = "http://iot.aruneworld.com/httt-get.txt" -- set server URL
wifi.setmode(wifi.STATION) -- set wi-fi mode to station
wifi.sta.config(station_cfg)-- set ssid&pwd to config
wifi.sta.connect() -- connect to router
--Wifi Eent Monitoring file
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, function(T)
print("\n\tSTA - CONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..
T.BSSID.."\n\tChannel: "..T.channel)
end)
wifi.eventmon.register(wifi.eventmon.STA_DISCONNECTED, function(T)
print("\n\tSTA - DISCONNECTED".."\n\tSSID: "..T.SSID.."\n\tBSSID: "..
T.BSSID.."\n\treason: "..T.reason)
tmr.stop(0)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, function(T)
print("\n\tSTA - GOT IP".."\n\tStation IP: "..T.IP.."\n\tSubnet mask: "..
T.netmask.."\n\tGateway IP: "..T.gateway)
tmr.start(0)
end)
function GetFromArunEworld()-- callback function for get data
http.get(server_link,'',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
end
-- call get function after each 5 second
tmr.alarm(1, 5000, 1, function() GetFromArunEworld() end)
Code Explanation
This code sets up a NodeMCU or similar device to connect to a Wi-Fi network, monitor Wi-Fi events, and periodically fetch data from a server over HTTP. It’s a good example of IoT device interaction with both Wi-Fi and web servers.
station_cfg={}
station_cfg.ssid="ArunEworld" -- Enter SSID here
station_cfg.pwd="8300026060INDIA" -- Enter password here
Here, a Lua table named station_cfg is defined, which contains the SSID and password for connecting to the Wi-Fi network.
server_link = "http://iot.aruneworld.com/httt-get.txt" -- set server URL
This line sets the URL of the server from which data will be fetched. It seems to be a text file containing data.
wifi.setmode(wifi.STATION) -- set Wi-Fi mode to station
wifi.sta.config(station_cfg)-- set SSID and password to config
wifi.sta.connect() -- connect to router
These lines configure the Wi-Fi module to operate in station mode, set the Wi-Fi station configuration to the values provided in station_cfg, and then initiate a connection to the specified router.
These functions register event handlers for various Wi-Fi events like connection, disconnection, and obtaining an IP address. When any of these events occur, the code prints a message containing relevant information. Additionally, it starts or stops the timer depending on the event.
function GetFromArunEworld()-- callback function for fetching data
http.get(server_link,'',
function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
end
This function GetFromArunEworld() is defined as a callback function to fetch data from the specified server. It makes an HTTP GET request to server_link and prints the response code and data.
-- call the fetch function every 5 seconds
tmr.alarm(1, 5000, 1, function() GetFromArunEworld() end)
Finally, a timer is set up to call the GetFromArunEworld() function every 5 seconds to fetch data from the server.
HTTP Post Example
Post Data to thinkspeak website
Code
station_cfg={}
station_cfg.ssid="ssid" -- Enter SSID here
station_cfg.pwd="password" -- Enter password here
server = "http://api.thingspeak.com/update" -- set server URL
count = 0 -- set initial count to 0
wifi.setmode(wifi.STATION) -- set wi-fi mode to station
wifi.sta.config(station_cfg) -- set ssid&pwd to config
wifi.sta.connect() -- connect to router
function PostToThingSpeak()
-- callback function for post data
local string = "api_key=1EYZIS5OCRJSKZHG&field1="..count
http.post(server, '', string, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
count = count + 1 -- increment count after each successful post
end
end)
end
-- call post function after each 20 seconds for ThingSpeak server update
tmr.alarm(1, 20000, tmr.ALARM_AUTO, function() PostToThingSpeak() end)
Code Explanation
This script connects to the specified Wi-Fi network, sends data to a ThingSpeak channel at regular intervals, and increments the count each time data is successfully posted.
station_cfg={}
station_cfg.ssid="ssid" -- Enter SSID here
station_cfg.pwd="password" -- Enter password here
These lines define a Lua table station_cfg with keys ssid and pwd, representing the SSID and password of the Wi-Fi network you want to connect to.
server = "http://api.thingspeak.com/update" -- set server URL
This line sets the URL of the ThingSpeak server where you’ll send the data.
count = 0 -- set initial count to 0
Initializes a variable count to keep track of the number of data posts.
wifi.setmode(wifi.STATION) -- set Wi-Fi mode to station
wifi.sta.config(station_cfg) -- set ssid&pwd to config
wifi.sta.connect() -- connect to router
These lines configure the Wi-Fi module to work in station mode, set the Wi-Fi station configuration, and connect to the router using the provided SSID and password.
function PostToThingSpeak()
-- callback function for posting data
local string = "api_key=1EYZIS5OCRJSKZHG&field1="..count
http.post(server, '', string, function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
count = count + 1 -- increment count after each successful post
end
end)
end
Defines a function PostToThingSpeak() to send data to ThingSpeak.
Constructs a string containing the API key and the current value of the count variable.
Sends an HTTP POST request to the ThingSpeak server with the constructed string.
Prints the response code and data received.
Increments the count after each successful post.
-- call post function every 20 seconds for ThingSpeak server update
tmr.alarm(1, 20000, tmr.ALARM_AUTO, function() PostToThingSpeak() end)
Sets up a timer to call the PostToThingSpeak() function every 20 seconds automatically.
This code sets up a NodeMCU or similar device to connect to a Wi-Fi network, monitor various Wi-Fi events, and perform an action when a specific GPIO pin state changes. Let’s break it down:
Overall, this script configures the Wi-Fi connection, sets up event handlers for various Wi-Fi events, defines a function to send data via HTTP POST, and sets up a GPIO pin to trigger an action when its state changes.
It registers a callback function to handle the event when the device disconnects from the Wi-Fi network. (Similar registration for other Wi-Fi events like authentication mode change, obtaining IP address, DHCP timeout, station/AP connection/disconnection, etc.)
HTTP Post Functionality:
local function D_Send()
tmr.wdclr()
http.post('https://aruneworld.com.com/post', 'Content-Type: text/plain\r\n', 'Hum=23&temp=24', function(code, data)
if (code < 0) then
print("HTTP request failed")
else
print(code, data)
end
end)
end
Defines a function D_Send() to perform an HTTP POST request to a server when called. In this case, it posts humidity and temperature data.
GPIO Pin Interrupt Setup:
local function pin1cb(level)
D_Send()
end
gpio.trig(3,"down", pin1cb) --gpio-0 pin
Defines a callback function pin1cb to be triggered when the GPIO pin 3 (GPIO 0) goes from high to low.
Registers this callback function with gpio.trig() to handle the GPIO interrupt.
These various applications for sending data, especially in IoT projects. Below are some scenarios and use cases where sending data using an HTTP POST request can be beneficial. In this article will discuss about “ESP8266 Arduino-core Tutorial – HTTP Post Data to Web Page”.
Web Sever (Shared, Linux, Windows or Own Server like with any hosting providers: Amazon, GoDaddy, GlobeHost, BlueHost, HostingRaja and etc)
Cpanel Login Access and update index file contend
Cpanel index.php code for web Server
Note I tested its code is working well.
<?php
$age= $name = $TimeStamp = "";
$Hum= $Temp = "";
$timezone = new DateTimeZone("Asia/Kolkata" );
$date = new DateTime();
$date->setTimezone($timezone );
echo $date->format('Ymd-H:i:s');
$TimeStamp = $date;
if( $_REQUEST["Hum"] || $_REQUEST["Temp"] )
{
echo " The Humidity is: ". $_REQUEST['Hum']. "%<br />";
echo " The Temperature is: ". $_REQUEST['Temp']. " Celcius<br />";
$Hum= $_REQUEST["Hum"];
$Temp = $_REQUEST["Temp"];
$myfile = fopen("arun.txt", "a") or die("Unable to open file!");
fwrite($myfile, "TimeStamp : ".$date->format('Ymd-H:i:s')."\t | Hum : ".$Hum."\t | Temp : ".$Temp. " |\n");
fclose($myfile);
}
if( $_GET["name"] || $_GET["age"] ) {
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.". "<br />";
$age= $_GET["age"];
$name = $_GET["name"];
$myfile = fopen("arun.txt", "a") or die("Unable to open file!");
fwrite($myfile, "TimeStamp : ".$date->format('Ymd-H:i:s')."\t | Name : ".$name."\t | Age : ".$age. " |\n");
fclose($myfile);
exit();
}
$myfile = fopen("arun.txt", "r") or die("Unable to open file!");
echo "<table border='1' align ='center' >";
while(!feof($myfile)) {
echo "<tr><td border='1' align ='center' >";
echo fgets($myfile) . "<br>";
echo "</td></tr>";
}
echo "</table>";
fclose($myfile);
?>
ESP8266 Arduino-Core Code for HTTP Post Data
//www.Aruneworld.com/embedded/esp8266/esp8266-arduino-core/
const char* hostGet = "iot.aruneworld.com/ESP8266/NodeMCU/HTTP-Post/";
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
const char* ssid="ArunEworld";
const char*password="8300026060INDIA";
WiFiClient client;
void postData() {
WiFiClient clientGet;
const int httpGetPort = 80;
//the path and file to send the data to:
String urlGet = "/index.php";
// We now create and add parameters:
String src = "12345";
String typ = "6789";
String nam = "temp";
String vint = "92";
urlGet += "?Hum=" + src + "&Temp=" + typ ;
Serial.print(">>> Connecting to host: ");
Serial.println(hostGet);
if (!clientGet.connect(hostGet, httpGetPort)) {
Serial.print("Connection failed: ");
Serial.print(hostGet);
} else {
clientGet.println("GET " + urlGet + " HTTP/1.1");
clientGet.print("Host: ");
clientGet.println(hostGet);
clientGet.println("User-Agent: ESP8266/1.0");
clientGet.println("Connection: close\r\n\r\n");
unsigned long timeoutP = millis();
while (clientGet.available() == 0) {
if (millis() - timeoutP > 10000) {
Serial.print(">>> Client Timeout: ");
Serial.println(hostGet);
clientGet.stop();
return;
}
}
//just checks the 1st line of the server response. Could be expanded if needed.
while(clientGet.available()){
String retLine = clientGet.readStringUntil('\r');
Serial.println(retLine);
break;
}
} //end client connection if else
Serial.print(">>> Closing host: ");
Serial.println(hostGet);
clientGet.stop();
}
void setup() {
Serial.begin(115200); // Starts the serial communication
WiFi.begin(ssid, password); //begin WiFi connection
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println("ArunEworld");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
postData();
delay(30000);
}
Make sure to replace the placeholders:
your-ssid and your-password with your WiFi credentials.
your-server-address with the address of your server.
/your-api-endpoint with the specific endpoint on your server that handles the incoming POST requests.
Applications and Uses
Purpose
Example and use Case
Data Logging
Use Case: Collecting sensor data from IoT devices and sending it to a web server for logging.
Example: Temperature and humidity readings from a sensor sent periodically to a server for historical tracking.
Remote Control
Use Case: Controlling devices remotely through a web interface.
Example: Sending commands to turn on/off lights, appliances, or actuators.
Sensor Data Transmission
Use Case: Transmitting real-time sensor data to a central server.
Example: Accelerometer data from a wearable device sent to a cloud server for analysis.
Form Submissions
Use Case: Submitting form data from a device to a web server.
Example: User input from a device form (e.g., a weather station) sent to a server for processing.
User Authentication
Use Case: Authenticating users and transmitting login credentials securely.
Example: Transmitting username and password securely to a server for authentication.
Integration with APIs
Use Case: Interacting with third-party APIs or services.
Example: Sending data to a cloud service API for weather information or other integrations.
Alerts and Notifications
Use Case: Sending alerts or notifications from a device to a central server.
Example: Sending an alert when a predefined threshold is exceeded (e.g., temperature too high).
Configuration Updates
Use Case: Updating device configurations remotely.
Example: Sending configuration parameters to a device, allowing dynamic adjustments.
Data Synchronization
Use Case: Synchronizing data between devices and servers.
Example: Uploading data collected offline on a device to a central server when connectivity is restored.
Command and Control Systems
Use Case: Building command and control systems for industrial or automation applications.
Example: Controlling and monitoring devices in a manufacturing plant through a central server.
Security aspects & Encryption
When implementing HTTP POST requests in your application, consider security aspects such as using HTTPS for encrypted communication and implementing proper authentication mechanisms to protect sensitive data. Always follow best practices for secure communication, especially when transmitting data over the internet.
FAQ
if you have the following Questions and most of the repeated and same-meaning questions, then the Above article should help you
How send data to web page using ESP8266?
How to HTTP Post Data to Web Page using ESP8266 via Arduino-core Tutorial –
ESP8266 send data to website?
Send ESP8266 Data to Your Webpage – no AT Commands
Arduino-Esp8266-Post-Data-to-Website
ESP8266: HTTP POST Requests
Posting and getting data from ESP on Apache WebServer
How to Send Data from Arduino to Webpage using WiFi?
How to send data to a server using ESP8266 with Arduino?
if you have questions like How set GPIO pin as input in ESP8266? then refer the below contents
Required
ESP8266 Any module or NodeMCU Development Kit(Any Version)
ESPlorer
Wires (Optional)
Note : if your using ESP8266 module only you need to know basic connection diagram of ESP8266
Code
-- set pin index 1 to GPIO mode, and set the pin to high.
pin=3 --gpio-0
gpio.mode(pin, gpio.INPUT)
while true do
print("GPIO Read PIN Status : "..gpio.read(pin))
end
GPIO pin set as output
Set GPIO pin as output using gpio.mode() function.
--www.aruneworld.com/embedded/esp8266/esp8266-nodecmu
button_pin=3 --GPIO-0
gpio.mode(button_pin, gpio.INPUT)
while true do
print("GPIO Read PIN Status : "..gpio.read(button_pin))
tmr.delay(1000000)
end
NodeMCU Flasher tool is flashing the NodeMCU Firmware to ESP8266 Easily. This tool is developed by NodeMCU. Flashing firmware to an ESP8266-based NodeMCU board involves updating the firmware on the microcontroller to enable it to execute the desired code. Here’s a step-by-step guide on how to flash firmware to an ESP8266 NodeMCU using the ESP8266Flasher tool. Please note that you’ll need a USB-to-Serial converter or USB-based development board for this process.
The ESP8266 NodeMCU is a versatile and affordable microcontroller board that has gained immense popularity in the maker community due to its built-in Wi-Fi capabilities and low cost. One of the key advantages of the NodeMCU is its flexibility, allowing developers to customize and build firmware tailored to their specific project requirements.
In this guide, we will walk through the process of building firmware for the ESP8266 NodeMCU. Whether you’re a beginner looking to get started with microcontroller programming or an experienced developer aiming to create advanced IoT applications, this tutorial will provide you with the necessary steps to compile and upload firmware to your NodeMCU board.
We’ll cover essential topics such as setting up the development environment, configuring the firmware, compiling the code, and uploading it to the NodeMCU. By the end of this tutorial, you’ll have the skills and knowledge to harness the full potential of your ESP8266 NodeMCU board by creating custom firmware tailored to your project’s needs. Let’s dive in!
Step-2: Two times enter your e-mail address (You will get a status about building the firmware)
Step 3: Select branch to build from (Recommended choose master always)
Step-4: Select modules to include( More than 40+ NodeMCU Lua Modules are available, Select depends upon your application development)
Step-5: Miscellaneous options (Recommended for beginner : Don’t select any option )
Step-6: Click the Start Your Build button
Step-7: Open your email ID (What you gave before)
Step 8: you will get an email about firmware building started and finished notification. In the finished Notification mail, you can download float and integer type NodeMCU .bin firmware file.
If you have many custom NodeMCU firmware, but the firmware name does not contain the details of info about what the NodeMCU module libraries are present. This article explains ESP8266 NodeMCU – How to know firmware information?, if ESPlorer works fine means ESP8266 returns the firmware details, some times ESPlorer IDE does not auto-detect the firmware details. so you should note that your custom NodeMCU firmware details yourself. This post will help to firmware details list easily by using small code.
The NodeMCU firmware is designed to work with the Lua scripting language. Lua is a lightweight and powerful scripting language that is well-suited for embedded systems.
The firmware is often used in conjunction with the NodeMCU development kit, which includes the ESP8266 WiFi module and a USB-to-Serial converter. The kit simplifies the development process and makes it easy to upload Lua scripts to the ESP8266
Three Different IDE’s are available from NodeMCU ESP8266 Platform
ESPlorer
Lua Loader
ESP8266 Web File Manager
ESP-IDF
This ESP8266 NodeMCU IDE tutorial Only discussed ESPlorer, You can use this ESPlorer tool as a UART Terminal Application. You can send and receive the data in terminal windows like Putty, DockLight
The ESP32 WiFi and Bluetooth chip is the generation of Espressif products.
It has a dual-core 32-bit MCU, which integrates WiFi HT40 and Bluetooth/BLE 4.2 technology inside.
It is equipped with a high-performance dual-core Tensilica LX6 MCU.
One core handles high-speed connection and the other for standalone application development.
The dual-core MCU has a 240 MHz frequency and a computing power of 600 DMIPS.
In addition, it supports Wi-Fi HT40, Classic Bluetooth/BLE 4.2, and more GPIO resources.
ESP32 chip integrates a wealth of hardware peripherals, including Capacitive touch sensors, Hall sensors, low noise sensor amplifiers, SD card interfaces, Ethernet interfaces, High-speed SDIO / SPI, UART, I2S, and I2C, etc. Lets ESP32 get the Start
Arduino is an electronic prototyping platform. It is an Open-source and users to create interactive electronic objects. Arduino is an open-source hardware and software company, project and user community that designs and manufactures single-board microcontrollers and microcontroller kits for building digital devices. It supports various CPUs like Atmel AVR (8-bit), ARM Cortex-M0+ (32-bit), ARM Cortex-M3 (32-bit), and Intel Quark (x86) (32-bit).
You must be logged in to post a comment.