Code
#include
const char* ssid = “Phamson”; const char* password = “phamtheson”; WiFiServer server(80); void setup() { Serial.begin(115200); //Default Baud Rate for NodeMCU delay(10); pinMode(2, OUTPUT); // Connect Relay to NodeMCU’s D4 Pin digitalWrite(2, 0); // 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.println(WiFi.localIP()); } 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); } String req = client.readStringUntil(‘\r’); Serial.println(req); client.flush(); int val; if (req.indexOf(“/gpio/0”) != -1) val = 0; else if (req.indexOf(“/gpio/1”) != -1) val = 1; else { Serial.println(“invalid request”); client.stop(); return; } // Set GPIO2 according to the request digitalWrite(2, val); client.flush(); String s = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n
\r\n
\r\nGPIO is now “; s += (val)?”high”:”low”; s += ”
“; }
I want to send temperature sensor data whenever a button named get temperature is pressed on app it should display the current temperature value. I am able to see new client request whenever I click the button and also Arduino serial print but it does not appear on the app text box… Please help
Welcome,
Most of the devices does not have the temperature sensor. See the documentation.
A sensor component that can measure the ambient (external) temperature. Most Android devices do not have this sensor.
They’re using an Arduino Temperature Sensor
Oh, I thought it is an Android sensor
This may help you:
Thanks @NishyanthKumarbut i m using Wifi instead of bluetooth … Here is the sample blocks which i want to use please ignore the cross marks as this is just an example. What i want to do is there is a button on my app which is getTemp when i press that button it sends new client request to esp8266 and whatever output in the form of text i get on serial monitor of arduino should get updated on the text box (temp) located just above the button.ill also provide sample arduino code here i have given constant temp example but it is a variable in my case and its changing
#include
const char* ssid = “JioFi2_C4FFC1”;const char* password = “######”;WiFiServer server(80);
void setup() {Serial.begin(38400);
Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(100); //500 Serial.print("."); } Serial.println(""); Serial.println("Wifi Connected"); Serial.println("Server started "); Serial.println(WiFi.localIP());
server.begin();
}void loop() {string temp=38*cWiFiClient client = server.available();if (!client){return;}Serial.println(“new client”);while(!client.available()){delay(1);}String req = client.readStringUntil(‘\r’);Serial.println(req);
if (req.indexOf("/getTemp")!=-1) { client.println(temp); Serial.println(temp); } String web = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; client.print(web); client.flush();
Ah, sorry. Didn’t see that.I’m not the best at Arduino (I don’t know C++), but @Juan_Antonio and @NissanCedric are the go-to people to ask in its terms inside of this Community.
Check
Thanks @Juan_AntonioI have already gone through these two links but the problem with in my case is that I want to receive the text that obtained on serial monitor of Arduino but these 2 examples will send data from to esp device do I need to make any change in Arduino code or in app blocks to receive text from esp device to app using wifi.. … Please help
Here many examples with ESP32
Check your phone to see if its web browser can reach that 192.168… address.
You may need to switch from your cell service’s net access to local WiFi access to get there.
thanks for your support @Juan_Antonio I tried your example of analog read from potentiometer… but in my case it displays “Error1101: unable to connect to specific URL http://192.168.1.184/temp”i made the same program as like yours but to get temperature data in form of stringthe only difference here is :this is from your code-if (req.indexOf(“consulta”) != -1){valor = analogRead(Ent_Anilogica);valor_map = map(valor, 0, 4095, 0, 330);Serial.println(valor);}
this is from my code-if (req.indexOf(“/getTemp”)!=-1){client.println(temp);Serial.println(temp);}
I can’t understand why its not working please help.
@Sneha_JangidTry
if(req.indexOf(“getTemp”)!=-1)
@Juan_Antonio did but same error
@ABG checked but not working
#include
const char* ssid = “XXXXXXX”;const char* password = “XXXXXXXXXXXX”;
String temperature = “34”;
WiFiServer server(80);
void setup() {Serial.begin(115200);
// Conecta a la red wifi.Serial.println();Serial.print(“Conectando con “);Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {delay(500);Serial.print(“.”);}Serial.println(“Conectado con WiFi.”);
// Inicio del Servidor web.server.begin();Serial.println(“Servidor web iniciado.”);
// Esta es la IPSerial.print(“Esta es la IP para conectar: “);Serial.print(“http://”);Serial.print(WiFi.localIP());}
void loop() {// Consulta si se ha conectado algún cliente.WiFiClient client = server.available();if (!client) {return;}
Serial.print(“Nuevo cliente: “);Serial.println(client.remoteIP());
// Espera hasta que el cliente envíe datos.while(!client.available()){ delay(1); }
/////////////////////////////////////////////////////// Lee la información enviada por el cliente.String req = client.readStringUntil(‘\r’);Serial.println(req);
// Realiza la petición del cliente.if (req.indexOf(“consulta”) != -1){temperature = String(random(1,100));Serial.println(temperature);delay(10);}
//////////////////////////////////////////////// Página WEB. ////////////////////////////client.println(“HTTP/1.1 200 OK”);client.println(“Content-Type: text/html”);client.println(“”); // Importante.
client.println(temperature);
Serial.print(“Cliente desconectado: “);Serial.println(client.remoteIP());// client.flush();}
Here with a potentiometer:http://kio4.com/arduino/347B_esp8266_AI2_Potenciometro.htm
@Sneha_Jangid did it work ?
In this project, you’re going to build an Android app using the MIT App Inventor software that allows you to control the ESP8266 GPIOs.
First, watch the video demonstration
To learn more about the ESP8266 use the following tutorials as a reference:
- Getting started with the ESP8266
- ESP8266 web server with NodeMCU
- Flashing NodeMCU firmware
- ESP8266 troubleshooting guide
If you like the ESP and you want to do more projects you can download my eBook Home Automation using ESP8266 here.
Let’s get started!
Parts List
Here’s the hardware that you need to complete this project:
- 1x ESP8266 -read Best ESP8266 Wi-Fi Developmento Boards
- 1x FTDI programmer
- 2x LEDs
- 2x 220Ω Resistors
- 1x Breadboard
- 1x Android Phone – example OnePlus 5 (read review)
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Downloading ESPlorer IDE
I recommend using the ESPlorer IDE which is a program created by 4refr0nt to send commands to your ESP8266.
Follow these instructions to download and install ESPlorer IDE:
- Click here to download ESPlorer
- Unzip that folder
- Go to the main folder
- Run “ESPlorer.jar” file
- Open the ESPlorer IDE
Creating the Android App with MIT App Inventor
MIT App Inventor is a drag-and-drop software that allows you to create a basic, but fully functional Android app within an hour or less.
Here’s how to edit the ESP8266 Controller app:
- Click here to download the .aia file
- Unzip the folder
- Go to MIT App Inventor
- Click the “Create Apps” button on the top right corner
- Go to the “Projects” tab and select “Import project (.aia)”
After importing the .aia file, you’ll be able to edit the app and see how the app was built.
Designer
The designer tab is where you can edit how the app looks. Feel free to change the text, change the colors, add buttons or add more features.
Blocks
The blocks section is where you can add what each button does and add logic to your app.
After finishing editing the app you can click the “Build” app tab and install the .apk file in your Android. I personally recommend that you first upload the app provided below to ensure that everything works as expected (later you can edit the app).
Step 8: Smartphone Configuration
First of all, you need to download the application on your phone from AppStore or Google Play. Application is free of charge.
Install and start the application. Right after you start it, a window will appear, where all the settings from cloud.supla.org must be entered. Save the settings and the relay connected to the ESP can be operated via your Smartphone.
Participated in the Digital Life 101 Challenge
Open the Google Play store or Apple App store on your phone or tablet, or use the buttons below to open the corresponding page:
After downloading, step through the instructions to install the Companion app on your device. You need to install the MIT App Inventor Companion app only once, and then you can leave it on your phone or tablet for whenever you use App Inventor. Note: There are some differences between the Android and iOS versions. Please review this page for more details.
Alternatively, you can scan the following QR codes to get either the iOS or Android app:
For iOS, scan this code to go to the Companion app on the Apple App Store.
For Android, scan this code to download the Android .APK file for the Companion app directly to your device. (Using an .APK file requires sideloading the app on your device and updating the app manually in the future.)
App Inventor will automatically show you the app you are building, but only if your computer (running App Inventor) and your device (running the Companion) are connected to the same Wi-Fi network. See a more detailed explanation of this here.
Go to App Inventor and open a project (or create a new one — use Project > Start New Project and give your project a name).
Then Choose “Connect” and “AI Companion” from the top menu in your browser:
A dialog with a QR code will appear on your PC screen. On your device, launch the MIT App Companion app just as you would do any app. Then click the “Scan QR code” button on the Companion, and scan the code in the App Inventor window:
Within a few seconds, you should see the app you are building on your device. It will update as you make changes to your design and blocks, a feature called “live testing.”
If you have trouble scanning the QR code or your device does not have a scanner, type the code shown on the computer into the Companion’s text area on your device exactly as shown. The code is directly below where the screen on your PC shows “Your code is” and consists of six characters. Type the six characters and choose the orange “Connect with code.” Do not type an Enter or carriage return: type just the six characters followed by pressing the orange button.
If your app does not appear on your device, the most likely problems are:
This is what my database looks like. I want to create a button where whenever I click it, it fetches the data from the Firebase and displays it on the same screen as a table or as a list. I’ve tried and I’m stuck, I’m just new to MIT app. Thank you very much.
users >
users1> id: “34535”
name : “Alice”
time: “Saturday, June 17, 2023 15:58:40”
users2> id: “5675675675”
name : “Tina”
time: “Saturday, June 17, 2023 15:58:40”
users3> id: “78658856”
name : “Luis”
time: “Saturday, June 18, 2023 10:30:10”
This is what my database looks like. I want to create a button where whenever I click it, it fetches the data from the Firebase and displays it on the same screen as a table or as a list. I’ve tried and I’m stuck, I’m just new to MIT app. Thank you very much.
users >
users1> id: “34535”
name : “Alice”
time: “Saturday, June 17, 2023 15:58:40”
users2> id: “5675675675”
name : “Tina”
time: “Saturday, June 17, 2023 15:58:40”
users3> id: “78658856”
name : “Luis”
time: “Saturday, June 18, 2023 10:30:10”
Hey guys, I need to create an app by app inventor. It should be able to receive strings from Arduino via ESP8266.
I need an app inventor extension of the WiFi module.
I have seen so many module of Bluetooth or wifi module that can only send messages to Arduino.
So I need an extension that can receive data from Arduino via WiFi module.
Any idea? Thank you very much!
My extension works with TCP/IP. I can’t tell if it works with your WIFI card.
If you are going to connect to the Arduino from time to time, and use your phone for other tasks as well, then I think it’s better to let the Arduino be the server and your phone be a client. Then use polling as suggested before. This will be easier to implement.
Dear @Junrong_Huang,
I’m struggling since a couple of days with a problem similar to yours.
Behind the scene: => I wanted to make something like a home automation/antitheft system on my own.
I have then bought 3 NODEMCU8266 and some PIR sensors (Arduino compatibles).
The aim is to have a PAD (or phone) with an AI2 application to behave as the “controller” of the various NODEMCU’s in a totally local WiFi network, without any router (therefore no remote control via WEB).
.I’ve then decided to have a structure like:
1 NODEMCU (#1) acting as a soft Access Point in Server configuration. It acquires the PIR and drives two relays (when it receives the command by each of the other two NODEMCU’s).
2 NODEMCU’s (#2 and #3) acting as Stations (STA) in Client configuration, Every 5 seconds they send a relay ON/OFF request to the AP, just to see whether they are alive and connected.
1 PAD (Lenovo M8 Android 9) in Client configuration, acting as User Interface or Controller. It can send a relay ON/OFF command by hitting on two buttons (of the PAD screen). On the screen are also shown the HTML strings as they come from the AP. No extensions used, just blocks.
With my configuration, in which the PAD (phone) is a client, I found that the “easy” way to receive messages from the server, is to set a periodical clock (i.e. 250 ms) on the PAD, so the PAD can ask the server if there are any news (like it was sent unsolicited by the server: see [(@rkl099) Rolf’s answer].
In other words, by means of a 250 ms clock, the PAD (phone) asks the server to respond with some updates. If the server has some news to transmit to the client, it sends this new information, else, it sends the string “nothing to say”. As soon as the string is received by the PAD, the app parses it, and decides consequently (i.e. “nothing to say” = no actions ).
The .aia and the .ino files that you find attached are really far from being “ready to use” but, anyway, they are working in my configuration, as described above and I guess they can be a good base that you can elaborate to get your needs Auto_Home_04 _1.aia (103.0 KB) ESP_8266_base.ino (8.1 KB)
EDIT: removed yesterday’s Client .ino. Replaced with a commented one:
I know you are at the experimental stage but it is best to not have any unused cables near the Arduino and no cables should be near the module other than the ones connected to it. ESP-01S ESP8266 Module should work just fine, make sure it’s in good condition -check for hairline cracks with a magnifying glass and test the cabling for continuity. Need to be sure you start with a good base
Taking It Further
This is a basic example that shows you how easy it is to integrate an Android app with the ESP8266. You can take this example and modify it.
You could add multiple screens to the app, so you can other ESPs or add buttons to control more GPIOs.
Do you have any questions? Leave a comment down below!
Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.
Hello friends,
1.- Send message and view it on an LCD screen.
1.- You write a message in TexBox1 and it is sent by WiFi to ESP8266, that message is shown on the LCD screen.2.- If you write on5, off5, on6, off6, LEDs 5 or 6 turn on/off.
``` // Juan A. Villalpando. // KIO4.COM // Send a message // from App Inventor #include
const char* ssid = "Name_Net_WiFi"; const char* password = "Password_WiFi"; // Static IP. IPAddress local_IP(192, 168, 1, 12); IPAddress gateway(192, 168, 1, 1); IPAddress subnet(255, 255, 255, 0); #define LED5 D5 // LED in pin 5 #define LED6 D6 // LED in pin 6 #includeint columns = 16; int rows = 2; LiquidCrystal_I2C lcd(0x27, columns, rows); // LiquidCrystal_I2C lcd(0x3F, columns, rows); WiFiServer server(80); void setup() { Serial.begin(115200); pinMode(LED5, OUTPUT); pinMode(LED6, OUTPUT); lcd.init(); lcd.backlight(); // Set Static IP. WiFi.config(local_IP, gateway, subnet); // Connection to WiFi Serial.println(); Serial.print("Connecting with "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println("Connected with WiFi."); // Start WebServer. server.begin(); Serial.println("WebServer started."); // This is IP of WebServer Serial.print("IP of WebServer: "); Serial.print("http://"); Serial.print(WiFi.localIP()); } void loop() { // Check if a client has connected. WiFiClient client = server.available(); if (!client) { return; } Serial.print("New client: "); Serial.println(client.remoteIP()); // Wait for the client to send data. while(!client.available()){ delay(1); } ///////////////////////////////////////////////////// // Read information of client. String req = client.readStringUntil('\r'); Serial.println(req); req.replace("+", " "); // Spaces without + req.replace(" HTTP/1.1", ""); // this delete HTTP/1.1 req.replace("GET /", ""); // this delete GET / lcd.clear(); // Borra pantalla. lcd.setCursor(0, 0); // Start cursor lcd.print("Mensaje"); lcd.setCursor(0,1); // Next row. lcd.print(req); // Make the customer's request. if (req.indexOf("on5") != -1) {digitalWrite(LED5, HIGH);} if (req.indexOf("off5") != -1){digitalWrite(LED5, LOW);} if (req.indexOf("on6") != -1) {digitalWrite(LED6, HIGH);} if (req.indexOf("off6") != -1){digitalWrite(LED6, LOW);} ////////////////////////////////////////////// // Página WEB. //////////////////////////// client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // Important. Serial.print("Client disconnected: "); Serial.println(client.remoteIP()); client.flush(); client.stop(); } ```
-
In this code I use static IP.
-
Utilizo:
Regards,http://kio4.com/arduino/345_esp8266_AI2_LCD.htm
With NodeMcu:https://groups.google.com/forum/#!searchin/mitappinventortest/esp8266$20sends$20message|sort:date/mitappinventortest/t9DJ8U0KE6Y/18orp_xgBwAJ
I saw several projects that integrate APP Inventor with Arduino,
unfortunately I only found projects where data from arduino sensors
are replicated on the mobile screen or actuators are turned on or off.
Would anyone know of an example where the mobile APP can pass a value
to an Arduino variable?
For example, turning on a lamp if the level of the photoresistor is
less than x, and the value of x is can be changed on the application
screen (typing the value or using a slider, etc.)
If you would like to have full control over ESP, send and read data. Also be able to control ESP remotely, e.g. from work, read about the MQTT protocol. There is a nice MQTT extension for appinvwntor and lots of libraries for arduino. There are also many free mqtt brokers (servers) available. You can also create your own server, e.g. using the android application. This way you can also control esp from e.g. the google assistant.
Here is English translated Wifi Led control project, But I am still trying to write correct code for Nodemcu
Also I will have to findout How to upload LEDWifi_ESP_BIJ_1Aia Project file here for community
In this project, you’re going to build an Android app using the MIT App Inventor software that allows you to control the ESP8266 GPIOs.
Taking It Further
This is a basic example that shows you how easy it is to integrate an Android app with the ESP8266. You can take this example and modify it.
You could add multiple screens to the app, so you can other ESPs or add buttons to control more GPIOs.
Do you have any questions? Leave a comment down below!
Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.
First, watch the video demonstration
To learn more about the ESP8266 use the following tutorials as a reference:
- Getting started with the ESP8266
- ESP8266 web server with NodeMCU
- Flashing NodeMCU firmware
- ESP8266 troubleshooting guide
If you like the ESP and you want to do more projects you can download my eBook Home Automation using ESP8266 here.
Let’s get started!
Uploading Code
You should see a window similar to the preceding Figure, follow these instructions to upload a Lua file:
- Connect your FTDI programmer to your computer
- Select your FTDI programmer port
- Press Open/Close
- Select NodeMCU+MicroPtyhon tab
- Create a new file called init.lua
- Press Save to ESP
Everything that you need to worry about or change is highlighted in red box.
Downloading ESPlorer IDE
I recommend using the ESPlorer IDE which is a program created by 4refr0nt to send commands to your ESP8266.
Follow these instructions to download and install ESPlorer IDE:
- Click here to download ESPlorer
- Unzip that folder
- Go to the main folder
- Run “ESPlorer.jar” file
- Open the ESPlorer IDE
Step 7: ESP Configuration
Before any steps are taken you need to subscribe to the OpenSource service project called SUPLA at https://cloud.supla.org/account/create .
You need to read location settings and password as well as server address after you log on cloud.supla.org.
Now, we can start the proper ESP configuration.
- Turn the power supply on.
- RGB diode should flash in blue indicating the module is in configuration mode. If the diode flash in red, you need to press and hold for at least 5 sec. the second switch (the furthest to the powering unit). Such action should put the unit in the configuration mode manually, and the diode should start flashing blue automatically.
- You need to connect to SUPLA-ESP8266 WiFi network from any computer with WiFi card.
- Go to http://192.168.4.1 and enter access data of your home WiFi having Internet access, password and location identifier obtained from cloud.supla.org into the form.Click „Save”.
- Turn the power off and on back again or press switch No. 2 (the furthest to the powering unit).
* Module does not display password, which does not mean they are not saved.
**Properly saved data will be confirmed with the “Data Saved” alert.
***LAST STATE: defines status of the most recent svr1.supla.org. server connection. If the entered location data was incorrect, you can return to the configuration to read the last alert.
RDG diode will indicate module status, after restart:
- Red light – No WiFi connection or IP address from DHCP has not been obtained
- Blue light – steady burn: WiFi connection has been obtained. IP address has been obtained, but no connection to server (svr1.supla.org) has been set.
- Green light – Server connection has been set. Unit is ready to work. It is worth pointing out that the relay can also be operated manually when pressing switch No. 2.
Code
Upload the following code into your ESP8266 using the preceding software. Your file should be named “init.lua“.
Don’t forget to add your network name (SSID) and password to the script below.
-- Rui Santos -- Complete project details at https://randomnerdtutorials.com wifi.setmode(wifi.STATION) wifi.sta.config("YOUR_NETWORK_NAME","YOUR_NETWORK_PASSWORD") print(wifi.sta.getip()) led1 = 3 led2 = 4 gpio.mode(led1, gpio.OUTPUT) gpio.mode(led2, gpio.OUTPUT) srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(client,request) local buf = ""; buf = buf.."HTTP/1.1 200 OK\n\n" local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); end local _GET = {} if (vars ~= nil)then for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do _GET[k] = v end end if(_GET.pin == "ON1")then gpio.write(led1, gpio.HIGH); elseif(_GET.pin == "OFF1")then gpio.write(led1, gpio.LOW); elseif(_GET.pin == "ON2")then gpio.write(led2, gpio.HIGH); elseif(_GET.pin == "OFF2")then gpio.write(led2, gpio.LOW); end client:send(buf); client:close(); collectgarbage(); end) end)
Step 6: Software for the Microcontroller
Software for the microcontroller. Appropriate firmware is required in order to have the microcontroller working. In this case, we will use firmware to be downloaded from GITHUB: https://github.com/SUPLA/ESP8266/tree/master/socket-firmware
NOTICE! Some versions of the ESP8266-12 have the 4th and 5th GPIO ports inverted. If this is the case, you need to use firmware which will be compatible. Such a solution is available at: https://github.com/SUPLA/ESP8266/tree/master/socket-firmware-gpio54
Firmware must be writted in the following flash memory area:
eagle.flash.bin——–>0x00000
eagle.irom0text.bin—->0x40000
You must use appropriate software to have firmware loaded onto the microcontroller. I have used „NODEMCU FIRMWARE PROGRAMMER” https://github.com/nodemcu/nodemcu-flasher
32bit Version: https://github.com/nodemcu/nodemcu-flasher/tree/master/Win32/Release
64bit Version: https://github.com/nodemcu/nodemcu-flasher/tree/master/Win64/Release
You must select proper serial port where the USB-Serial converter has been plugged in and enter the other settings which can be seen on the screenshots.
If the ESP module is connected via the USB-Serial converter to the computer, and all the above steps have been performed, we can upload the software.
– Provide 12V power supply. – Press and hold the micro-switch connected to the GPIO0 port (the nearest to the powering unit), and turn the power on – keep pressing the micro-switch the whole time. – Release the micro-switch when power is on.
The RGB diode should now gently flash three colors.
We can now load firmware. Using NODEMCU click „Flash” and wait until progress bar reaches 100% for each of the two files.
NOTICE! ESP8266 module is very interference-sensitive. When it is connected to breadboard temporarily, firmware load may not be successful at the first time. Therefore, sometimes the attempt must be made few times. If the firmware was loaded successfully, we can disconnect power supply and remove the USB-Serial converter and move to the next step.
NOTICE! ESP will not start, if the converter remains on the breadboard not connected to a powered-up computer.
Schematics (3.3V FTDI Programmer)
The schematics for this project are very straight forward. You only need to establish a serial communication between your FTDI programmer and your ESP8266. You can buy one FTDI programmer on eBay.
Wiring:
- RX -> TX
- TX -> RX
- CH_PD -> 3.3V
- VCC -> 3.3V
- GND -> GND
Tạo App Android bằng MIT APP INVENTOR
Để có thể tạo một App Android bằng MIT app inventor chúng truy cập vào link để tạo dự án nhé: http://appinventor.mit.edu
Bước đầu tiên các bạn Click vào Projects chọn “Start new project” để tạo một dự án mới.
Tiếp theo chúng ta cần đặt tên cho dự án.
Ở bên tay trái màn mình các bạn, chúng ta Click vào Button dùng để bật tắt thiết bị. Ở đây mình sẽ chọn 2 nút và đặt là “ON” và “OFF”.
Để có thể chỉnh sửa các thông số của Button các bạn Click vào và nó sẽ xổ ra các trường thông tin. Ở đây các bạn có thể đặt lại tên cho Button ở phần Text …
Tiếp theo, các bạn chọn mục Connectivity và cho Web và kéo thả vào Viewer nhé.
Sau khi đã cấu hình cho các Button và Web ta chọn vào Block để chuyển qua lập trình kéo thả Block.
Click vào “Button 1” chọn phần mà mình đã khoanh đỏ và kéo chúng vào vùng lập trình.
Tiếp tục, ta chọn “Web1” và kéo Block đã được đánh dấu. Ở phần này chúng ta sẽ cấu hình địa chỉ IP Web.
Chọn mục “Text” kéo block được khoanh đỏ vào vùng lập trình.
Tiếp theo ở mục Web1 chọn Block “Call Web.Get”.
Để biết được địa chỉ IP của NodeMCU ESP8266 ta cần nạp Code và bật Monitor lên xem nhé. Code mình để cuối bài viết các bạn tải về và
thực hiện nhé. Ở đây địa chỉ IP của mình là: 192.168.88.106
- http://192.168.88.106/gpio/1
- http://192.168.88.106/gpio/0
Các bạn kéo thả các Block lại với nhau giống như trên màn hình nhé.
Để có thể tải dự án về điện thoại, các bạn vào mục Build chọn App (project QR code for apk).
Quét mã QR code xuất hiện trên màn hình. Và các bạn tiến hành cài đặt App vào điện thoại nhé.
Như vậy là đã xong các bạn có thể điều khiển bật tắt thiết bị trên App điện thoại rồi.
Introduction: ESP8266 and Relay Control Using Smartphone
This instruction describes ESP8266 microcontroller start-up to control by smartphone a relay connected to the ESP. In a separate instruction I will try to present a similar case, but instead of the ESP8266 microcontroller we will use Raspberry PI version B+.
Here we go then
What will we need?
- A smartphone, Android (3.1.x Version or higher) or iPhone iOS 6.1 (or higher).
- An ESP8266 module version 512KB flash (or higher). This article will cover the ESP8266-12 version.
- A USB-Serial converter to program ESP. I have used the “FT232RL FTDI 3.3V 5.5V USB to TTL Serial Adapter”.
- PCB adapter for ESP.
- 3.3/5V powering unit. I have used the YwRobot module.
- A relay module. For this article I have used version I had close at hand i.e. YwRobot 4 relay.
- 12V charger.
- Two (2) LED diodes, one of which must be RGB.
- Two (2) micro-switches
- One (1) transistor. I have used BC547.
- Three (3) 100R resistors.
- Two (2) 10K resistors.
- One (1) breadboard.
- Connecting wiring.
- Piece of a thin wire.
Do not forget to connect the ESP module TXD pin to the USB-Serial converter RXD pin, and the ESP module RXD pin to the USB-Serial converter TXD pin. “IN1” must be connected to the relay module.
Let’s start…
Attachments
Parts List
Here’s the hardware that you need to complete this project:
- 1x ESP8266 -read Best ESP8266 Wi-Fi Developmento Boards
- 1x FTDI programmer
- 2x LEDs
- 2x 220Ω Resistors
- 1x Breadboard
- 1x Android Phone – example OnePlus 5 (read review)
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Code
Upload the following code into your ESP8266 using the preceding software. Your file should be named “init.lua“.
Don’t forget to add your network name (SSID) and password to the script below.
-- Rui Santos -- Complete project details at https://randomnerdtutorials.com wifi.setmode(wifi.STATION) wifi.sta.config("YOUR_NETWORK_NAME","YOUR_NETWORK_PASSWORD") print(wifi.sta.getip()) led1 = 3 led2 = 4 gpio.mode(led1, gpio.OUTPUT) gpio.mode(led2, gpio.OUTPUT) srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(client,request) local buf = ""; buf = buf.."HTTP/1.1 200 OK\n\n" local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); end local _GET = {} if (vars ~= nil)then for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do _GET[k] = v end end if(_GET.pin == "ON1")then gpio.write(led1, gpio.HIGH); elseif(_GET.pin == "OFF1")then gpio.write(led1, gpio.LOW); elseif(_GET.pin == "ON2")then gpio.write(led2, gpio.HIGH); elseif(_GET.pin == "OFF2")then gpio.write(led2, gpio.LOW); end client:send(buf); client:close(); collectgarbage(); end) end)
Installing the Android App
Follow these instructions to install the default app that I’ve created:
- Click here to download the .apk file
- Unzip the folder
- Move the .apk file to your Android phone
- Run the .apk file to install the app
Here’s how the ESP8266 Controller app looks when you to open it.
It’s very easy to configure. Click the button “Set IP Address” on the bottom of the screen and type your IP address (in my case 192.168.1.95).
You’re all set!
Now you can turn the GPIOs high and low with your smartphone. Go to the top of this page to see a video demonstration of this project.
Schematics (3.3V FTDI Programmer)
The schematics for this project are very straight forward. You only need to establish a serial communication between your FTDI programmer and your ESP8266. You can buy one FTDI programmer on eBay.
Wiring:
- RX -> TX
- TX -> RX
- CH_PD -> 3.3V
- VCC -> 3.3V
- GND -> GND
Sơ đồ đấu nối
Các linh kiện cần thiết cho dự án
Tên linh kiện | Số lượng | Shopee |
NodeMCU ESP8266 | Mua ngay | |
Dây cắm (Cái – Cái) | Mua ngay | |
Module Relay 5V | Mua ngay |
Uploading Code
You should see a window similar to the preceding Figure, follow these instructions to upload a Lua file:
- Connect your FTDI programmer to your computer
- Select your FTDI programmer port
- Press Open/Close
- Select NodeMCU+MicroPtyhon tab
- Create a new file called init.lua
- Press Save to ESP
Everything that you need to worry about or change is highlighted in red box.
Installing the Android App
Follow these instructions to install the default app that I’ve created:
- Click here to download the .apk file
- Unzip the folder
- Move the .apk file to your Android phone
- Run the .apk file to install the app
Here’s how the ESP8266 Controller app looks when you to open it.
It’s very easy to configure. Click the button “Set IP Address” on the bottom of the screen and type your IP address (in my case 192.168.1.95).
You’re all set!
Now you can turn the GPIOs high and low with your smartphone. Go to the top of this page to see a video demonstration of this project.
/***********
Juan A. Villalpando
KIO4.COM
25/11/22
Version del módulo 9.2.4
Velocidad 9600
Carga el programa. Ve al Serial Monitor.
Escribe en un navegador 192.168.1.5
Pulsa los botones para encender o apagar el LED13 del Arduino.
***********/
#include
#define DEBUG true
SoftwareSerial esp8266(3,2);
// El TX del módulo al terminal 3 del Arduino.
// El RX del módulo al terminal 2 del Arduino.
void setup()
{
pinMode(13,OUTPUT);
Serial.begin(9600);
esp8266.begin(9600); // Importante la velocidad del módulo.
sendData(“AT+RST\r\n”,2000,DEBUG); // Borra la configuración que tenía el módulo
sendData(“AT+CWJAP=\”Nombre_de_tu_WiFi\”,\”Clave_de_tu_WiFi\”\r\n”, 2000, DEBUG);
delay(5000); // Espera un poco que conecte con el Router.
sendData(“AT+CWMODE=3\r\n”,1000,DEBUG); // Modo de cliente y servidor.
sendData(“AT+CIFSR\r\n”,1000,DEBUG); // En el Serial Monitor aparece la IP de cliente y servidor.
sendData(“AT+CIPMUX=1\r\n”,1000,DEBUG); // Multiples conexiones.
sendData(“AT+CIPSERVER=1,80\r\n”,1000,DEBUG); // El Puerto web es el 80
}
void loop(){
if(esp8266.available()) // Consulta si el módulo está enviando algún mensaje
{
if(esp8266.find(“+IPD,”))
{
delay(500);
int connectionId = esp8266.read()-48;
// Aquí las construcción de la PAGINA WEB.
String webpage = “HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n\r\n”;
webpage += ”
KIO4.COM
“;
webpage += ”
“;
webpage += ”
\r\n\r\n”;
String cipSend = “AT+CIPSEND=”;
cipSend += connectionId;
cipSend += “,”;
cipSend +=webpage.length();
cipSend +=”\r\n”;
sendData(cipSend,500,DEBUG);
sendData(webpage,500,DEBUG);
// Lee el pin 13
int pin13 = digitalRead(13);
// Retorno de la lectura.
String retorno = “HTTP/1.1 200 OK\r\n Content-Type: text/html\r\n\r\n\r\n”;
if (pin13 == 1) {retorno += ” ON – Encendido”;}
if (pin13 == 0) {retorno += ” OFF – Apagado”;}
// ResponseCode App Inventor
cipSend = “AT+CIPSEND=”;
cipSend += connectionId;
cipSend += “,”;
cipSend += retorno.length();
cipSend +=”\r\n”;
sendData(cipSend,500,DEBUG);
sendData(retorno,500,DEBUG);
// Cierra la conexión
String closeCommand = “AT+CIPCLOSE=”;
closeCommand+=connectionId;
closeCommand+=”\r\n”;
sendData(closeCommand,500,DEBUG);
}
}
}
// Función para Enviar datos al Servidor.
String sendData(String command, const int timeout, boolean debug){
String response = “”;
esp8266.print(command); // Envía la información de command al servidor
long int time = millis();
while( (time+timeout) > millis())
{
while(esp8266.available())
{
// A response van los datos que regresan al servidor.
char c = esp8266.read(); // Va leyendo caracter a caracter.
response+=c;
// Consulta si en la información que regresa al servidor
// viene “GET /enci” o “GET /apag”
// Encenderá o apagará el LED13 del Arduino
if(response.indexOf(“GET /enci”) >0){
// Serial.print(“enciende”);
digitalWrite(13,HIGH);
}
if(response.indexOf(“GET /apag”) >0){
//Serial.print(“apaga”);
digitalWrite(13,LOW);
}
}
}
if(debug)
{
Serial.print(response);
}
return response;
}
// http://kio4.com/arduino/57modulowifi_2.htm
// Juan A. Villalpando
#include
SoftwareSerial esp8266(3,2);
// El TX del módulo al terminal 3 del Arduino.
// El RX del módulo al terminal 2 del Arduino.
int random_1 = 10;
int random_2 = 50;
String random_out = “0,0”;
String input_data = “”;
String fin = “”;
void setup(){
randomSeed(analogRead(A0));
Serial.begin(9600);
esp8266.begin(9600);
sendData(“AT+RST\r\n”,2000); // Borra la configuración que tenía el módulo
sendData(“AT+CWJAP=\”Nombre_de_tu_WiFi\”,\”Clave_de_tu_WiFi\”\r\n”, 2000);
delay(10000); // Espera un poco que conecte con el Router.
sendData(“AT+CWMODE=1\r\n”,1000); // Modo de cliente del Router.
sendData(“AT+CIFSR\r\n”,1000); // En el Serial Monitor aparece la IP del Servidor Web.
sendData(“AT+CIPMUX=1\r\n”,1000); // Multiples conexiones.
sendData(“AT+CIPSERVER=1,80\r\n”,1000); // Crea Servidor Web, puerto 80
}
void loop(){
if(esp8266.available()){
while(esp8266.available()){
char c = esp8266.read();
input_data += c;
if(input_data.indexOf(“genera”) > 0){
random_1 = random(10,50);
random_2 = random(50,99);
random_out = (String) random_1 + “,” + (String) random_2;
input_data = “”;
fin = “finalizado”;
}
}
}
// Return responseContent
if(fin == “finalizado”){
String header = “HTTP/1.1 200 OK\r\n Content-Type: text/html; \r\n”;
header += “Content-Length: “;
header += random_out.length();
header += “\r\nConnection: close\r\n\r\n”;
header += random_out;
sendData(“AT+CIPSEND=” + String(0) + “,” + header.length() + “\r\n”, 500);
sendData(header,1000);
// sendData (“AT+CIPCLOSE=” + String(0) + “\r\n”, 1000);
fin = “”;
}
}
// Envia datos al servidor y recibe la respuesta de los AT.
String sendData(String command, const int timeout){
String response = “”;
esp8266.print(command); // Envía la información de command al servidor
long int time = millis();
while( (time+timeout) > millis()){
while(esp8266.available()){
// A response van los datos que regresan al servidor.
char c = esp8266.read(); // Va leyendo caracter a caracter.
response+=c;
}
}
Serial.print(response);
return response; // Devuelve la respuesta del AT
}
It took me a while to figure out how the web server “knew” to work off IP address 192.168.1.9, but then I saw it in the COM24 log as the result of the AT+CIFSR command, and I imagine you read that output to get the IP address hard coded into the AI2 app.
Now we are going to carry out the previous example but we will create an Access Point (SoftAP – Soft Access Point), that is, the module will create a network independent from the Router, it will not be connected to the Router.
The code will create a network called ESP_81411C and the Web Server will have as IP: 192.168.4.1
For this we will change these lines…
void setup(){
randomSeed(analogRead(A0));
Serial.begin(9600);
esp8266.begin(9600);
sendData(“AT+RST\r\n”,2000); // Borra la configuración que tenía el módulo
// sendData(“AT+CWJAP=\”Nombre_de_tu_WiFi\”,\”Clave_de_tu_WiFi\”\r\n”, 2000);
// delay(10000); // Espera un poco que conecte con el Router.
sendData(“AT+CWMODE=2\r\n”,1000); // NOW IS A SOFT ACCESS POINT, MODE = 2
sendData(“AT+CIFSR\r\n”,1000); // En el Serial Monitor aparece la IP del Servidor Web. (192.168.4.1)
sendData(“AT+CIPMUX=1\r\n”,1000); // Multiples conexiones.
sendData(“AT+CIPSERVER=1,80\r\n”,1000); // Crea Servidor Web, puerto 80
}
We must change the IP in the code…
It is also convenient to install the application, since we are going to change the network and the MIT Companion will be in the Router’s network.
Once the application is installed, we go to the WiFi configuration and establish the ESP_81411C network
It is not necessary to put a Password since in this default configuration it does not have it.
If we wanted to change the name of the network and put a password on it, we would put this line:
3.- Remove the Serial Monitor, in case you have it open.
4.- We load this sketch in the IDE and upload it…
It is convenient from time to time to remove the power from the ESP8266 and put it back if it does not load well.
Summary
/*
* This sketch demonstrates how to set up a simple HTTP-like server.
* The server will set a GPIO pin depending on the request
* http://server_ip/gpio/0 will set the GPIO2 low,
* http://server_ip/gpio/1 will set the GPIO2 high
* server_ip is the IP address of the ESP8266 module, will be
* printed to Serial when the module is connected.
*/
#include
const char* ssid = “nombredemirouter”;
const char* password = “contraseñadelrouter”;
// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);
void setup() {
Serial.begin(9600);
delay(1500);
// prepare GPIO2
pinMode(2, OUTPUT);
digitalWrite(2, 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.println(WiFi.localIP());
}
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 req = client.readStringUntil(‘\r’);
Serial.println(req);
client.flush();
// Match the request
int val;
if (req.indexOf(“/gpio/0”) != -1)
val = 0;
else if (req.indexOf(“/gpio/1”) != -1)
val = 1;
else {
Serial.println(“invalid request”);
client.stop();
return;
}
// Set GPIO2 according to the request
digitalWrite(2, val);
client.flush();
// Prepare the response
String s = “HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n
\r\n
\r\nGPIO is now “;
s += (val)?”high”:”low”;
s += ”
\n”;
// Send the response to the client
client.print(s);
delay(1);
Serial.println(“Client disonnected”);
// The client will actually be disconnected
// when the function returns and ‘client’ object is detroyed
}
5.- When there is upload, remove the GPIO 0 to GND cable and open the Serial Monitor. Restart.
6.- Once the sketch is loaded we can remove the Arduino, connect an LED to the GPIO2 and feed the module with 3.3V
If you don’t have a 3.3V power supply, you can use the Arduino to power the module, note that you don’t need RX or TX.
Điều khiển thiết bị bằng MIT App Inventor sử dụng NodeMCU ESP8266
Trong nội dung bài viết hôm nay mình sẽ giới thiệu với các bạn một chủ đề mới cách có thể tạo một App Android trên MIT App Inventor một cách nhanh chóng mà không cần phải biết về lập trình nhiều.
Bài viết sẽ hướng dẫn các bạn cách tạo một App đơn giản và điều khiển các thiết bị trong gia đình thông qua NodeMCU ESP8266. Để có thể nắm rõ hơn các bạn có thể tìm đọc các bài viết liên quan đến dự án.
Creating the Android App with MIT App Inventor
MIT App Inventor is a drag-and-drop software that allows you to create a basic, but fully functional Android app within an hour or less.
Here’s how to edit the ESP8266 Controller app:
- Click here to download the .aia file
- Unzip the folder
- Go to MIT App Inventor
- Click the “Create Apps” button on the top right corner
- Go to the “Projects” tab and select “Import project (.aia)”
After importing the .aia file, you’ll be able to edit the app and see how the app was built.
Designer
The designer tab is where you can edit how the app looks. Feel free to change the text, change the colors, add buttons or add more features.
Blocks
The blocks section is where you can add what each button does and add logic to your app.
After finishing editing the app you can click the “Build” app tab and install the .apk file in your Android. I personally recommend that you first upload the app provided below to ensure that everything works as expected (later you can edit the app).
Keywords searched by users: esp8266 mit app inventor 2
Categories: Khám phá 39 Esp8266 Mit App Inventor 2
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/