Arduino Tank control via Wi-Fi. Controlling the machine via WiFi using ESP8266 NodeMCU Arduino android wifi load control

Ever thought about controlling any electronic devices using your smartphone? Agree, it would be very cool to control a robot or any other devices from your smartphone. We offer a simple lesson for beginners and dummies on how to control a smartphone using Arduino via Bluetooth. If after this lesson you want to get to know Arduino better, you can find books about it.

Step 1. What we need

Devices

Module - Bluetooth Module HC 05/06
Board - Arduino
Light Emitting Diode (LED)
Resistor - 220Ω
Android device

Software

Arduino IDE
Android Studio (actually not necessary, because you will find the Android application below)

Step 2. How it works

Usually we do this step at the end, but so that you understand what we have to achieve, look at the result at this intermediate step. We have also published a step-by-step video tutorial below.

Step 3. We begin to assemble the circuit

The circuit in our tutorial is so simple and small that we only need to make a few connections:

Arduino Pins___________Bluetooth Module Pins
RX (Pin 0)___________________________TX
TX (Pin 1)___________________________RX
5V__________________________VCC
GND_______________________GND

Connect the negative of the LED to GND on the Arduino, and the positive to pin 13 through a resistance of 220 Ohm - 1 kOhm. In general, in our figure below everything is quite clear.

Do not connect RX to RX and TX to TX Bluetooth outputs to Arduino outputs, you will not receive any data, here TX means transmit, RX means receive.

Step 4: Uploading the Program to Arduino

Now we need to write a program and upload it to our Arduino. If you don’t know how to do this yet, download books. The code below is exactly what we need to load into the Arduino.

/* Bluetooh Basic: LED ON OFF * Coder - Mayoogh Girish * Website - http://bit.do/Avishkar * Download the App: https://github.com/Mayoogh/Arduino-Bluetooth-Basic * This program lets you to control a LED on pin 13 of arduino using a bluetooth module */ char data = 0; //Variable for storing received data void setup() ( Serial.begin(9600); //Sets the baud for serial data transmission pinMode(13, OUTPUT); //Sets digital pin 13 as output pin ) void loop() ( if(Serial.available() > 0) // Send data only when you receive data: ( data = Serial.read(); //Read the incoming data and store it into variable data Serial.print(data); // Print Value inside data in Serial monitor Serial.print("\n"); //New line if(data == "1") // Checks whether value of data is equal to 1 digitalWrite(13, HIGH); // If value is 1 then LED turns ON else if(data == "0") // Checks whether value of data is equal to 0 digitalWrite(13, LOW); //If value is 0 then LED turns OFF ) )

Step 5. How the process works

The HC 05/06 module operates via a serial communication channel. The Android app sends data sequentially to the Bluetooth module when you press a specific key. The Bluetooth on the other end receives the data and sends it to the Arduino via the Bluetooth module's TX connection (Arduino RX connection).

The code loaded into the Arduino checks the received data and compares it. If a "1" is received, the LED turns on and turns off when a "0" is received. Open the serial port monitor and observe the received data.

Step 6. Application for Android devices

In this tutorial we will not touch on creating applications for Android devices. You can download the application on GitHub.

How to use the application?

After we have connected via Bluetooth, we need to download and install an application that, using a smartphone :) will control our LED from a distance. You can download the application for free on Amazon.com. We connect the smartphone to the Bluetooth module HC 05/06:

  1. Turn on the HC 05/0 module
  2. Looking for a device
  3. We connect to HC 05/06 by entering the default password “1234” or “0000” (four zeros).

After that we install the application on our smartphone. Let's open it. Select a device - select the Bluetooth module from the list (HC 05/06). After successful connection, press the ON button to turn on the LED and the OFF button to turn off the LED. Then you can click the “Disconnect” button to disconnect from the Bluetooth module.

This was a guide for dummies and beginners on how to connect a Bluetooth module with Arduino. This project can be improved and taken to a higher level for, for example, home automation through smartphone control, controlled robot and much more.

Transferring firmware, updates and other data using a soldering iron and wires is not the best solution for Arduino. However, microcontrollers for arduino wi-fi are not cheap, and they are not always needed, which is why users prefer not to use them in their projects unnecessarily.

But now another Chinese product has captured the market; you can connect your own wi-fi jammer esp8266 to an Arduino board or other system, and you will get a stable connection with a number of other advantages. So let’s figure out the arduino uno wi-fi, and whether it’s worth buying this module, as well as what a similar microcontroller on arduino wi-fi actually is.

Available Wi-Fi modules for Arduino

Nowadays, most Arduino users no longer worry about the price of such devices, although 3 years ago an Arduino wi-fi module was considered a luxury. All this thanks to the wi-fi jammer esp8266, whose manufacturers introduced a completely new product to the market, amazing in its functionality and, at the same time, being quite cheap, which made a significant contribution and created competition in this direction.

Thus, arduino wi-fi esp8266 is now considered the most affordable module on the market, like all its brothers. Thus, the price on foreign sites starts from 2 dollars, which allows you to purchase these modules in batches and not have to reflash them a thousand times, resoldering the contacts in order to maintain functionality.

At first, this Arduino wi-fi module was used mainly as an arduino wi-fi shield, since it was the cheapest option and was in no way inferior to the original one. The device is truly almost legendary, because there are no significant disadvantages for its price. There are many libraries, including user ones, and also supports work via Serial buses and the simplest AT and AT+ commands. Thanks to this, there is no need to study any semantics of the notorious C99, as is often the case with other third-party microcontrollers.

Accordingly, even a beginner will figure it out in seconds, and a professional will be able to use already prepared libraries. Other advantages include:

  1. The processor is 160 MHz, but it is 32-bit, which leaves a certain imprint on performance. But it’s worth remembering that the module is still used in conjunction with Arduino boards, which themselves cut high frequencies and eat up most of the resources for unknown reasons.
  2. The manufacturer that released the esp8266 wi-fi module did not stop interesting projects, and now there is a whole line of microcontrollers of proven quality.
  3. Modern network security standards. Of course, WPA and WPA2 are no longer as secure as we would like, but their presence cannot but please us in such a cheap controller.
  4. 16 output ports, including 10-bit, allowing you to experiment with the board.

More importantly, out of the box you will find up to 4 megabytes of permanent memory, depending on the type of board, and this greatly simplifies working with large libraries and even some media files. After all, on most Arduino boards even 1 megabyte is considered an unaffordable luxury.

The characteristics of the esp8266 wi-fi are certainly encouraging, especially in comparison with its more expensive competitors, but a user who has no previous experience with these boards will have a question about how to connect it. The fact is that the module has many more pins than beginners are used to seeing, and, accordingly, they begin to panic. However, if you understand the situation, then in reality there is nothing complicated about it. It is enough to stock up on solder and a soldering iron and just read the instructions.

How to connect a Wi-Fi module to Arduino

Let's look at connecting the esp8266 esp 12e and what an esp8266 wi-fi uart bridge is. After all, it is the connection and configuration of the module that raises the most questions.


First of all, decide which version of the microcontroller you have. In the first, LEDs are built in near the pins, and in the second, which began to be produced quite recently, the signal lights are located near the antenna.

Before connecting, you should download the latest firmware, which allows you to increase the packet exchange rate to 9600 units of information per second. And we will check the connection using a usb-ttl cable and the corresponding terminal from CoolTerm.


The pins for connecting the cable described above are standard, but the power comes through a 3.3 volt pin from the Arduino. It is important to remember that the maximum current supplied by the board cannot be set above 150 mA, and esp8266 esp 07 and esp8266 witty cloud wi-fi module for arduino require 240 mA.

However, if there is no other current source, you can use the standard version from Arduino, but the power of the board will suffer. Although, if the load is not heavy, 70 mA is enough, be prepared for sudden reboots of the microcontroller at peak load times and write software accordingly so that it filters and splits files without overloading the board.


Another connection option is below. Important - the RX-TX contacts are connected with a crosshair. Since the signal levels of the ESP8266 module are 3.3V, and the Arduino is 5V, we need to use a resistive voltage divider to convert the signal level.

Registering a Wi-Fi module in Arduino

As you know, with proper experience, you can pair the esp8266 ex 12e shield with a smartphone, but for beginners, registering the esp8266 esp 12 in the Arduino system causes difficulties. In fact, it is enough to connect the module and check its functionality by issuing several standard AT commands through the debug menu.

For example, you can add blinking with a standard LED (for the connection diagram above):

#define TXD 1 // GPIO1/TXD01 void setup() ( pinMode(TXD, OUTPUT); ) void loop() ( digitalWrite(TXD, HIGH); delay(1000); digitalWrite(TXD, LOW); delay(1000) ; )

As soon as the board confirms that it sees the microcontroller in the system, you can begin full work with it. However, it is worth noting that if the Arduino board itself is used in the project only to connect this controller, this is irrational.

A USB-UART converter is sufficient, since the esp8266 does not use the “brains” of the Arduino, and its flash memory is quite enough for storing a couple of basic libraries and firmware. Accordingly, there is no point in spending extra money on an auxiliary board if you can simply solder it to the converter and further use it in the project. At the same time, by connecting an auxiliary power source and without worrying that data will stop being transmitted at the most crucial moment due to a lack of system power.

Important note! For the last circuit, we upload the sketch to the Arduino as usual, but since the ESP8266 module is connected to pins 0 and 1, programming becomes impossible. The compiler will show an error. Disconnect the wires going to the ESP8266 from pins 0 and 1, perform programming, and then return the pins to their place and press the reset button in the Arduino.

It is gaining more and more popularity, and Arduino is already taking up the initiative - adding these Wi-Fi modules to the list of supported boards.
But how to connect it to Arduino? Is it possible to somehow do without an Arduino at all? This is exactly what this article will be about today.

Looking ahead, I will say that there will be a second article, more practical, on the topic of firmware and programming the ESP8266 module in the Arduino IDE development environment. But first things first.

This video completely duplicates the material presented in the article.



At the moment, there are many varieties of this module, here are some of them:

And here is the pinout of ESP01, ESP03, ESP12:


* This picture can be viewed in good quality on off. website pighixxx.com.

Personally, I like the ESP07 version the most. At least for the fact that there is a metal screen (it protects the microcircuits from external interference, thereby ensuring more stable operation), its own ceramic antenna, and a connector for an external antenna. It turns out by connecting an external antenna to it, for example like biquadrat, then you can achieve a good range. In addition, there are quite a few input/output ports, the so-called GPIO (General Purpose Input Output ports), similar to Arduino pins.

Let's go back to our sheep Wi-Fi modules and Arduino. In this article, I will look at connecting an ESP8266 (model ESP01) to an Arduino Nano V3.

But, this information will be relevant for most ESP8266 modules and also various Arduino boards, for example the most popular Arduino UNO.

A few words about the ESP01 legs:

Vcc And GND(in the picture above these are 8 and 1) - food, per leg Vcc can be submitted, judging by the documentation, from 3 to 3.6 V, A GND- ground (minus power). I saw one person connect this module to two AA batteries (the supply voltage in this case was approximately 2.7 V) and the module was operational. But still, the developers indicated the voltage range in which the module should be guaranteed to work; if you use another one, that’s your problem.

Attention! This module is based on 3.3V logic, while Arduino is mostly 5V logic. 5 V can easily damage the ESP8266, so it needs to be powered separately from the Arduino.

- My Arduino has a leg where it says 3.3 V, why not use it?

You'll probably think. The fact is that the ESP8266 is quite a power-hungry module, and in peaks it can consume currents of up to 200 mA, and almost no Arduino is capable of delivering such a current by default, with the exception of Arduino Due, in which the current along the 3.3 V line can reach 800 mA, which is plenty, in other cases I advise you to use an additional 3.3 V stabilizer, for example AMS1117 3.3 V. There are a lot of them both in China and here.

Leg RST 6 - is intended for hardware to reboot the module, by briefly applying a low logical level to it, the module will reboot. Although I neglected this in the video, I still advise you “press” this leg with a 10 kOhm resistor to the power supply positive, in order to achieve better stability in the operation of the module, otherwise I would reboot at the slightest interference.

Leg CP_PD 4 (or in another way EN) - serves, again, to “hardwire” the module into energy-saving mode, in which it consumes very little current. Well again - It wouldn’t hurt to “press” this leg with a 10 kOhm resistor to the positive Pitalova In the video, I stupidly short-circuited this leg to Vcc, because I didn’t have such a resistor at hand.

Legs RXD0 7 TXD0 2 - hardware UART, which is used for flashing, but no one prohibits using these ports as GPIO (GPIO3 and GPIO1, respectively). For some reason, GPIO3 is not marked in the picture, but it is in the datasheet:

By the way, to the leg TXD0 2 the “Connect” LED is connected, and it lights up when the logic level on GPIO1 is low, or when the module sends something via UART.

GPIO0 5 - can not only be an I/O port, but also put the module into programming mode. This is done by connecting this port to a low logical level (“pressing” it to GND) and supplying power to the module. In the video I do this with a regular button. After flashing, do not forget to pull out the jumper/press the button (it is not necessary to hold the button during flashing; when turned on, the module goes into programming mode and remains in it until rebooted).

GPIO2 3 - input/output port.

And one more important point, each GPIO of the Wi-Fi module can safely deliver current up to 6mA, so as not to burn it, be sure to place resistors in series with the input/output ports on... Remember Ohm's law R = U/I = 3.3V / 0.006 A = 550 Ohm, that is, at 560 Ohm. Or neglect it, and then wonder why it doesn't work.

In ESP01, all GPIOs support PWM, so to our four GPIOs, that is, GPIO0-3, you can connect a motor driver, ala L293 / L298, and steer two motors, for example boats, or make RGB Wi-Fi whatever. Yes, yes, this module has a lot of things on board, and for simple projects the Arduino violinist is not needed, only for flashing. And if you use ESP07, then in general the ports are almost the same as those of Uno, which makes it possible to confidently do without an Arduino. True, there is one unpleasant moment, the ESP01 has no analog ports at all, and the ESP07 has only one, called ADC. This of course makes working with analog sensors more difficult. In this case, an Arduino analog multiplexer will help.

Everything seems to be explained by pinout, and here is the diagram for connecting the ESP8266 to the Arduino Nano:

Do you see the jumper on the RST and GND pins on the Arduino Nano? This is necessary so that the Arduino does not interfere with the firmware of the module; in the case of connecting the ESP8266 using Arduino, this is a prerequisite.

Also, if you connect to Arduino, the RX of the module must go to the RX of the arduino, TX - TX. This is because the converter chip is already connected to the Arduino pins in a cross pattern.

Also important is a resistive divider consisting of 1 kOhm and 2 kOhm resistors (can be made from two 1 kOhm resistors by connecting them in series) along the RX line of the module. Because Arduino is 5 V logic and the module is 3.3. This turns out to be a primitive level converter. It must be there, because the legs of the RXD TXD module are not tolerant to 5 V.

Well, you can do without an Arduino altogether by connecting the ESP8266 via a regular USB-UART converter. In the case of connecting to Arduino, we, in fact, use a standard usb and uart interface converter, bypassing the brains. So why spend extra money if you can do without an Arduino at all? Only in this case, we connect the RXD of the module to the TXD of the converter, TXD - RXD.

If you are too lazy to bother with connections, fiddling with resistors and stabilizers, there are ready-made NodeMcu solutions:

Everything is much simpler here: plug the cable into the computer, install the drivers and program, just don’t forget to use the jumper/button on GPIO0 to switch the module to firmware mode.

Well, that’s probably all with the theory, the article turned out to be quite long, and I will publish the practical part, ala firmware and programming of the module, a little later.

In the process of studying and designing increasingly complex projects, the time comes when the need and desire arises to learn how to work with such a common type of communication as WiFi. Since this type of communication can allow you to comfortably create a single network for your smart home devices and control them, for example, from a mobile phone, tablet or computer, that is, in other words, create a real smart home that will cost you tens of times less than buy ready-made solutions in the store. The use of WiFi, of course, is not limited to this and there are so many examples of using this type of communication that there is no point in listing them, and if you have landed on this page, it means that you already need to use WiFi for some reason, you just need to figure out how to work with it correctly .

We will figure it out based on the cheapest and most popular WiFi module ESP8266-01. You can buy the ESP8266-01 WiFi module on our website.

One of the main advantages of such a module is the presence of memory and its own microcontroller on the board, which allows it to work independently by loading the sketch directly into the module itself.

There are actually quite a lot of modifications of the ESP8266 WiFi module and we will not list them here; once you learn how to work with one, you can easily start working with others. I would like to immediately note that working with WiFi may seem like a rather difficult task, and if you have few completed projects in your luggage, it is better to give up WiFi communication for now and use radio communications in your projects, working with which is much easier to understand. Entire communities and thematic forums are created for working with WiFi modules, which once again proves how difficult it is for most people to immediately understand this type of communication, and after re-reading all the information, most people simply give up. Most likely, I won’t be able to include all the important information within the framework of this article alone, and there’s no point in doing so, otherwise there will be another mess. I will try to follow the path of a strict sequence of the most important points, so that you can begin to understand the principle of operation of this type of communication and then simply develop your own skills in this direction.

So, let's get started and first look at the WiFi module pins ESP8266-01.

VCC- module power supply from 3V to 3.6V

GND- Earth.

RST- Reset output responsible for rebooting the module.

CH_PD- "chip power-down" when power is supplied to it, the module's operation is activated.

TX- data transfer (UART interface)

RX- data reception (UART interface)

GPIO0

GPIO2- general purpose I/O port

The GPIO0 and GPIO2 pins are exactly the same digital pins that we work with on Arduino boards for interconnecting with various sensors, and they are used in the case of implementing independent operation on the internal WiFi microcontroller of the ESP8266-01 module.

To reliably power the ESP8266-01 module, use an external stabilized 3.3V power supply and it is better not to try to take power from your Arduino board, as the module consumes current up to 215mA and this may end badly for your debug board. Where to get a stabilized 3.3V power supply I hope is not a problem for you, otherwise it’s clearly too early for you to deal with this module. For example, I like to use this 3.3V and 5.0V YWRobot power module to quickly assemble circuits on breadboards, which allows you to quickly get a stabilized voltage of 3.3V or 5V on the corresponding power paths of the breadboard.

Connecting the plus (+) from our 3.3V power supply to pin VCC module ESP8266-01, and minus (-) bring the power supply to the output GND. In this state, the red LED on the module will turn on, signaling us that the power is connected correctly. In order for the module to be activated, it is also necessary to connect the plus (+) power supply with output CH_PD module ESP8266-01 and it is advisable to do this directly through a 10 kOhm resistor. Now, when we turn on the power, the red LED on the module should light up and the blue LED should blink quickly a couple of times. If this is what happens to you, then everything is fine, you have connected everything correctly and your module is working. Otherwise, check the connection again, or replace the module, as it is most likely not working.

Go ahead. To work with the ESP8266 WiFi module, we need a USB-UART adapter. There are different adapters, for example: FT232RL, CP2102, PL2303. But we will assume that you do not have such adapters, and we will use an Arduino board as a USB-UART adapter. I will use an Arduino NANO board for this, but you can use any other one at your disposal. The connection on any board is identical. We make the connection according to the following diagram.

Let's look at what we've done here. Please immediately note that we have connected the pins on the Arduino board with a jumper RST And GND. This manipulation disables the microcontroller and allows us to make a real USB-UART adapter out of our Arduino board.

Since we power the ESP8266-01 WiFi module from a separate external power supply, remember that we must always connect the ground of all power supplies in our projects. Therefore we connect the output GND Arduino boards with ground (-) our external 3.3V power supply designed to power the ESP8266-01 module.

Conclusion TX connect your Arduino board to the pin TX ESP8266-01 module. This line will transmit data from the WiFi module to the Arduino board. Anyone familiar with the UART interface may wonder: “But how can this be? Everywhere they taught that TX must connect to RX. TX transmits information, and RX receives.” And you will be right. That's right, TX is always connected to RX, but in the case when we make a UART adapter from Arduino, we need to connect the devices directly. Consider this the exception to the rule.

Line RX We also connect your Arduino board directly to the line RX ESP8266-01 module. This line will transmit information from the Arduino board to the WiFi module board. But we make this connection through a so-called voltage divider, consisting of two resistors with nominal values ​​of 1 kOhm and 2 kOhm. We need to reduce the voltage on this line using two resistors (voltage divider), since the Arduino board transmits a logical signal with a voltage of 5V, and the WiFi module operates with a voltage of 3.3V. To convert the logic signal, we could use a special logic level converter board, which would of course be more correct, but again, let’s assume that you don’t have one, and we had to take a simpler route and do it using a voltage divider.

We have now connected everything necessary for further work, but we still have 3 more pins not used ( GPIO0, GPIO2 And RST) on WiFi module ESP8266-01. For stable operation of the WiFi module, we need to pull these remaining unused pins to positive (+) module power lines through 10 kOhm resistors.

This will save us from various interferences (interference) and make the module’s operation stable. It's better to do it right away. Otherwise, don’t be surprised that your module is constantly overloaded, produces incomprehensible information, or does not want to work at all. Using pull-up resistors on unused pins of a microcontroller should be a rule of thumb if you want stable operation in your projects.

And again we check the functionality of the ESP8266-01 WiFi module. Turn on the power and see that the red LED lights up and the blue LED blinks a couple of times. If everything happens like this, then great, let's move on. Otherwise, we check the correctness of the connections, as well as the quality of all contacts. It may just be a trivial situation when you double-checked everything ten times and made sure that everything was connected correctly, but when you turn on the module, you see that the blue LED does not behave adequately, is constantly on, constantly blinking, or does not respond to anything at all. This may be due to poor contact on some line. For example, when assembling a circuit on a breadboard, one of the resistors does not sit tightly in its place and this causes interference. Check the quality of connections. The module is very sensitive. Don't neglect this. This is a common reason for unstable operation.

In general, we are done with the connection. Now we need to prepare the Arduino IDE program to work with the ESP8266-01 WiFi module. To do this, we need to download and install in the Arduino IDE the necessary archive with libraries, examples and ESP boards, which will subsequently allow us to upload sketches directly to the microcontroller of the ESP8266-01 module, change the firmware, etc. For the purposes of this article, we most likely will not need these settings, but it seems to me that after we have figured out how to connect the module, the procedure will be correct if we immediately download everything necessary to work with the Arduino IDE. Everything here is simple in principle.

Launch the program Arduino IDE and go to the menu "File" - "Settings"

In the window that appears, in the top field we write “esp8266”. As a result, we will only have the required firmware in the window. When you click on the firmware, a button will appear "Installation". Click on the button "Installation" and wait until everything is installed. The archive is quite large, about 150 megabytes, so you'll have to wait.

After installation is complete. We reboot the Arduino IDE and see how new ESP boards have appeared in the “Tools” - “Boards” menu. That's all. We are done with setting up the Arduino IDE. We don’t need these settings for now, but in future work we won’t be able to do without them.

We have everything connected and prepared, now we can begin to understand the controls. In fact, now we will continue to check and configure the module using AT commands, and there is no way to do without it. WiFi modules are implemented in such a way that all communication with them occurs using so-called AT commands, which are hardwired into the module’s firmware. We will not list all AT commands here, there are quite a lot of them and if you want to study everything carefully, you can easily find them on the Internet. And now we will use only the most necessary to get started.

And so, we connect our Arduino board via a USB cable to the computer. And an external power source that powers WiFi module ESP8266-01 No need to turn it on yet. We launch the Arduino IDE program, select our Arduino board from the “Tools” menu, in my case it is Arduino NANO, and you select yours. Also, do not forget to select the port to which our Arduino is connected. I hope you understand all this and know how to do it.

Open port monitoring "Tools" - "Port Monitor". Selecting the port speed 74880 (at this speed the module starts) and select “NL & CR” in the list on the left

Now we connect an external power source that powers our WiFi module. After which you should see approximately the following information in the port monitor.

Here we see some information on our WiFi module (speed, amount of memory on board, etc.). The information received may differ depending on the firmware version of the WiFi module. Let's not focus on this. Something else is important. Below we see a set of meaningless characters, this means that the port speed (74880 baud) that we set is only suitable for the initial loading of the module in order to see this information normally, but this speed is not suitable for normal communication with the WiFi module.

To select the correct port speed, we will simply change the port speed and send symbols to the port (the field at the top and the send button) AT until we get an answer OK. If you try to send characters right now AT to the port at a speed of 74880, you will receive another one or two meaningless characters in response.

Try immediately setting the speed to 115200 baud and sending the AT command. Most often, modules are flashed at this speed.

This is the picture you should see in your port monitor. If you still receive an incomprehensible set of characters in response, lower the speed and resend AT commands until the answer comes back OK. If you tried all the speeds and did not get the correct answer, then you are out of luck and the module is flashed with firmware at a non-standard speed. Then all that remains is to reflash the module with normal firmware, but this is a topic for a separate article.

I hope that everything is fine and you have selected the correct speed. By the way, if you try to turn off and turn on the WiFi module again after you have selected the correct speed, then instead of the same initial information that was correctly displayed at a speed of 74880 baud, you will, on the contrary, see a jumbled set of characters, but at the end you will see the word “ready” ". But we have the opportunity to view this initial information in normal form at the correct speed; to do this, we need to programmatically reboot the module using the AT command AT+RST.

To find out the firmware version of your ESP8266-01 WiFi module, you need to send a command to the port monitor AT+GMR and in response you will receive approximately the following information:

The ESP8266-01 WiFi module can operate in both access point and client modes. To allow the module to operate in all modes at once, send the command to the port monitor AT+CWMODE=3 and in response you should receive OK.

Team AT+CWLAP will allow you to view all WiFi access points that your module currently sees. My module, for example, currently sees only three WiFi access points in its coverage area. The answer should be something like this:

For example, we know the password for the third access point and to connect to it we execute the command AT+CWJAP="name","password", in my case this command looks like AT+CWJAP="dsl_unlim_512_home","11111111", to which we get a successful response:

The command parameters are written to the flash memory of the ESP8266-01 WiFi module, and if we turn off the module and turn it on again, it will automatically connect to this access point. Look, by chance, do not allow a space in the command, otherwise you will receive an answer ERROR. Please note that in the latest firmware versions it is recommended to use the command AT+CWJAP_CUR, that is, the command will look like AT+CWJAP_CUR="name","password". If suddenly we forgot which access point our module is connected to, we need to send a command AT+CWJAP? or AT+CWJAP_CUR? and in response we will receive the access point to which the WiFi module is currently connected.

With connection and initial setup WiFi module ESP8266-01 we figured it out. The module works and is ready for the implementation of your further projects. It is simply not possible to analyze all possible examples of working with this module within the framework of one article, and we will deal with this in the following articles. And for those who are not very familiar with programming, but really want to quickly start managing their projects using WiFi, I recommend introducing them to the RemoteXY WiFi project designer. This site will help you easily create a control interface for your mobile phone or tablet and use it to control your device to which you connect a WiFi module.

In this article, you will learn how to create a system that can turn DC loads on and off using a mobile app. You will also learn how to perform this task instantly or using timers preset to turn loads on and off.

Project overview

You can implement this system where you need to turn on a DC load for a specific time. Our Android application will help you with this, without requiring a hardware interface, keyboard or LCD display.

Accessories

ESP8266 Development Board Assembly

The ESP8266 is a low-cost SoC with an integrated microcontroller and a full TCP/IP protocol stack, meaning it can directly access your Wi-Fi network.

Since this chip has its own microcontroller, you can put your application code on it, or you can simply use the module as a Wi-Fi transceiver, which is what we are going to do in this project. It would be more efficient to use this module as both a transceiver and a controller, but for training purposes we will interact with the module using an Arduino.

The ESP8266 chip comes in different modules. We will use the ESP-01 module. Of course, you can use any other module.

Firstly, you should know that the module operates at 3.3V and the high logic level voltage from Arduino must be the same to avoid damaging our module. This requires a voltage level converter between the Arduino board (which runs at 5V) and the module. The good news is that the converter will only need a pin to send to the Arduino, since the receive pin typically recognizes 3.3V logic signals from the ESP8266.

One of the simplest ways to perform this conversion is a circuit from Sparkfun. You can order a ready-made module.

Level converter 5V → 3.3V

The figure below shows the pinout of our module on the ESP8266:

ConclusionPurpose
UTXDData transfer via UART
URXDReceiving data via UART. The output it connects to should be 3.3V.
CH_PDTurn off: low input turns the chip off, high input turns it on; For normal operation of the module, it is necessary to connect it to the power line.
GPIO0When loading: the level must be high to enter normal loading mode; a low level enters special boot modes.
GPIO2On boot: a low level causes the bootloader to enter flash boot mode; a high level causes normal boot mode.
RSTReset; active level - low.
GNDEarth.
VCCPower/3.3V.

I used the LM317, a configurable linear voltage regulator with an output current of up to 1.5A, to provide the module with a suitable 3.3V power supply.

Note: Do not use the 3.3V pin from the Arduino, as the 3.3V voltage regulator on the Arduino board cannot provide the amount of current required by the module, especially during peak power consumption during transmission.

I used BS170 (instead of BSS138) for the logic level converter; both work well.

Now you can connect your module to your computer using a USB-TTL converter and test it.

Relay Breadboard Assembly

To control the relay, I used a BC337 bipolar NPN transistor with a 1 kOhm resistor on the base. To protect against coil reverse voltage I used a 1n4007 diode.

I decided to connect the normally closed (NC) contact of the relay to ground.

Arduino code

Now we are faced with a problem. The ESP8266 uses UART as an interface for AT commands, while the Arduino Uno (which uses the Atmega328) only has one UART port. This port is already connected to the USB-TTL bridge, as well as pins 0 and 1.

As a solution, you can use an emulator for the UART port on another Arduino digital pin using the AltSoftSerial or SoftwareSerial libraries. This will allow you to still have a hardware UART port for debugging and printing messages to the console, and a software port for communicating with the module.

Many people (including myself) report problems with the software serial port at high baud rates - like the ones we'll be using with the esp8266, 115200 bps. I can say that 50% of the data received from the module will be damaged if you use a software UART, and of the data transferred from the Arduino to the module, almost 100% will be correct. I got these results after monitoring the signals on the RX and TX lines.

As a solution, I added some define directives to the code to make it easier for you to choose between hardware and software UART ports. Keep in mind that you cannot use the same port for debugging and communicating with the module, so you need to choose between them.

//uncomment Serial.*** if you want to use a hardware serial port (pins 0,1) to communicate with the ESP //uncomment esp8266.*** if you want to use a software serial port (pins 2,3) to communicate with the ESP #define esp8266_Available() Serial.available() //esp8266.available() #define esp8266_Find(ARG) Serial.find(ARG) //esp8266.find(ARG) #define esp8266_Read() Serial.read() //esp8266 .read() #define esp8266_Write(ARG1,ARG2) Serial.write(ARG1,ARG2) //esp8266.write(ARG1,ARG2) #define esp8266_Print(ARG) Serial.print(ARG) //esp8266.print(ARG)

In the source you will find part of the code that installs the module with your router:

SendCommand("AT+RST\r\n", 2000, DEBUG); // restart the module sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as an access point sendCommand("AT+CWJAP=\"tur\",\"341983#tur\"\r\n", 3000, DEBUG); //**** CHANGE SSID and PASSWORD ACCORDING TO YOUR NETWORK ******// delay(10000); sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get the IP address sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections sendCommand("AT+CIPSERVER=1,1337\r\n", 1000, DEBUG); // enable server on port 1337

The sketch loop waits for commands that should come through the Wi-Fi connection. The following commands are currently supported:

  • ‘con’ to get pin status, logic high or low;
  • ‘on=’ enable the corresponding output;
  • ‘of=’ turn off the corresponding output;
  • ‘Tm=n/fS’ set the timer to turn on (n) or turn off (f) the corresponding output.

All commands have a confirmation response.

Notes:

  • some parts of the sketch are based on ;
  • if you are using modules with an old SDK, you may have the same errors as me. The only solution in this case is to update your firmware to the latest version. See for help updating the module firmware on the ESP8266. I updated the firmware from version 1.3 to 1.5.4.

Full program code:

#include #define DEBUG 0 // if you are using a hardware serial port to communicate with the ESP, change the value to 0 #define ESPBaudRate 115200 #define HWSBaudRate 115200 #define OUTPUT1 11 #define OUTPUT2 12 #define OUTPUT3 13 //uncomment Serial.*** , if you want to use a hardware serial port (pins 0,1) to communicate with the ESP //uncomment esp8266.*** if you want to use a software serial port (pins 2,3) to communicate with the ESP #define esp8266_Available() Serial.available( ) //esp8266.available() #define esp8266_Find(ARG) Serial.find(ARG) //esp8266.find(ARG) #define esp8266_Read() Serial.read() //esp8266.read() #define esp8266_Write(ARG1 ,ARG2) Serial.write(ARG1,ARG2) //esp8266.write(ARG1,ARG2) #define esp8266_Print(ARG) Serial.print(ARG) //esp8266.print(ARG) // Makes the Arduino RX line pin 2, and the TX line of the Arduino is pin 3. // This means that you need to connect the TX line from the ESP to pin 2 of the Arduino, // and the RX line from the ESP to pin 3 of the Arduino. SoftwareSerial esp8266(2, 3); /*************/ byte OUTPUTstate; byte OUTPUTTMRIsSet ; byte OUTPUTTMRState ; long OUTPUTTimer; /************/ /***Commands**/ String GETSTATE = "con"; // Request string from the mobile application to find out the status of each output String SETON = "on="; // Request string from the mobile application to enable output String SETOFF = "of="; // Request string from the mobile application to turn off the output String TIMER = "tm="; // Request line from the mobile application to set the exit timer /**************/ void setup() ( Serial.begin(HWSBaudRate); // Serial port for sending messages from Arduino to computer esp8266.begin(ESPBaudRate); // Software serial port for sending messages from Arduino to ESP8266 pinMode(OUTPUT1, OUTPUT); digitalWrite(OUTPUT1, LOW); pinMode(OUTPUT2, OUTPUT); digitalWrite(OUTPUT2, LOW); pinMode( OUTPUT3, OUTPUT); digitalWrite(OUTPUT3, LOW); // restart the module sendCommand("AT+RST\r\n", 2000, DEBUG); // configure as an access point sendCommand("AT+CWMODE=1\r\ n", 1000, DEBUG); //**** CHANGE SSID and PASSWORD ACCORDING TO YOUR NETWORK ******// sendCommand("AT+CWJAP=\"tur\",\"341983#tur\ "\r\n", 3000, DEBUG); delay(10000); // get an IP address sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // configure for multiple connections sendCommand("AT+ CIPMUX=1\r\n", 1000, DEBUG); // enable the server on port 1337 sendCommand("AT+CIPSERVER=1,1337\r\n", 1000, DEBUG); if (DEBUG == true) Serial.println("Server Ready"); ) void loop() ( if (esp8266_Available()) // check if esp sent a message ( if (esp8266_Find("+IPD,")) ( // wait until the serial buffer is full (read all serial data) delay(1000 ); // get the connection id so we can disconnect int connectionId = esp8266_Read() - 48; // subtract 48 because the read() function returns // a decimal value in ASCII, and 0 (the first decimal number) starts with 48 String closeCommand = "AT+CIPCLOSE="; // creating a command to close the connection closeCommand += connectionId; // add the connection id closeCommand += "\r\n"; esp8266_Find("? "); // This character defines the beginning of the command in the body of our message String InStream; InStream = (char) esp8266_Read(); InStream += (char) esp8266_Read(); InStream += (char) esp8266_Read(); if (DEBUG == true) Serial.println(InStream); if (InStream.equals(GETSTATE)) ( // response to the command Status=<состояние_выхода_1><состояние_выхода_2><состояние_выхода_3>String response = "Status="; response += OUTPUTstate; response += OUTPUTstate; response += OUTPUTstate; sendHTTPResponse(connectionId, response); sendCommand(closeCommand, 1000, DEBUG); // close the connection ) else if (InStream.equals(SETON)) ( int pinNumber = (esp8266_Read() - 48); // get the first digit, i.e., if the pin is 13, then the 1st digit is equal to 1 int secondNumber = (esp8266_Read() - 48); if (secondNumber >= 0 && secondNumber<= 9) { pinNumber *= 10; pinNumber += secondNumber; // получить вторую цифру, т.е., если вывод 13, то 2-ая цифра равна 3, // и добавить ее к первой цифре } if (pinNumber == OUTPUT1) OUTPUTstate = 1; else if (pinNumber == OUTPUT2) OUTPUTstate = 1; else if (pinNumber == OUTPUT3) OUTPUTstate = 1; digitalWrite(pinNumber, 1); String response = "Confg="; // Отклик на команду Confg=<номер_вывода>response += pinNumber; sendHTTPResponse(connectionId, response); sendCommand(closeCommand, 1000, DEBUG); // close the connection ) else if (InStream.equals(SETOFF)) ( int pinNumber = (esp8266_Read() - 48); // get the first digit, i.e., if the pin is 13, then the 1st digit is equal to 1 int secondNumber = (esp8266_Read() - 48); if (secondNumber >= 0 && secondNumber<= 9) { pinNumber *= 10; pinNumber += secondNumber; // получить вторую цифру, т.е., если вывод 13, то 2-ая цифра равна 3, // и добавить ее к первой цифре } if (pinNumber == OUTPUT1) OUTPUTstate = 0; else if (pinNumber == OUTPUT2) OUTPUTstate = 0; else if (pinNumber == OUTPUT3) OUTPUTstate = 0; digitalWrite(pinNumber, 0); // изменить состояние вывода String response = "Confg="; // Отклик на команду Confg=<номер_вывода>response += pinNumber; sendHTTPResponse(connectionId, response); sendCommand(closeCommand, 1000, DEBUG); // close the connection ) else if (InStream.equals(TIMER)) ( int pinNumber = (esp8266_Read() - 48); // get the first digit, i.e., if the pin is 13, then the 1st digit is equal to 1 int secondNumber = (esp8266_Read() - 48); if (secondNumber >= 0 && secondNumber<= 9) { pinNumber *= 10; pinNumber += secondNumber; // получить вторую цифру, т.е., если вывод 13, то 2-ая цифра равна 3, // и добавить ее к первой цифре } if (esp8266_Read() == "n") { if (DEBUG == true) Serial.println("on"); if (pinNumber == OUTPUT1) OUTPUTTMRState = 1; else if (pinNumber == OUTPUT2) OUTPUTTMRState = 1; else if (pinNumber == OUTPUT3) OUTPUTTMRState = 1; } else { if (DEBUG == true) Serial.println("off"); if (pinNumber == OUTPUT1) OUTPUTTMRState = 0; else if (pinNumber == OUTPUT2) OUTPUTTMRState = 0; else if (pinNumber == OUTPUT3) OUTPUTTMRState = 0; } int j = 0; byte Atime; // Таймер может настроен на максимальное значение в 1 сутки // поэтому программа может принять 5 цифр, так как 1 сутки равны 86400 секундам long Time; // Прочитать секунды, значение имеет переменное количество цифр, поэтому читать, пока не получим "s", // что является символом завершения в теле моего сообщения от мобильного телефона while (1) { Time = esp8266_Read(); if (Time == "s") break; Atime[j] = Time - 48 ; j++; } switch (j) // секунды... { case 1: // одна цифра Time = Atime; break; case 2: // две цифры Time = Atime * 10 + Atime; break; case 3: // три цифры Time = Atime * 100 + Atime * 10 + Atime; break; case 4: // четыре цифры Time = Atime * 1000 + Atime * 100 + Atime * 10 + Atime; break; case 5: // пять цифр Time = Atime * 10000 + Atime * 1000 + Atime * 100 + Atime * 10 + Atime[j]; break; } if (DEBUG == true) { Serial.println("Timer:"); Serial.println(Time); } Time = Time * 1000 + millis(); if (DEBUG == true) { Serial.println("Pin:"); Serial.println(pinNumber); } if (pinNumber == OUTPUT1) { OUTPUTTMRIsSet = 1; OUTPUTTimer = Time; } else if (pinNumber == OUTPUT2) { OUTPUTTMRIsSet = 1; OUTPUTTimer = Time; } else if (pinNumber == OUTPUT3) { OUTPUTTMRIsSet = 1; OUTPUTTimer = Time; } String response = "tConfg="; // Отклик на команду tConfg=<номер_вывода>response += pinNumber; sendHTTPResponse(connectionId, response); sendCommand(closeCommand, 1000, DEBUG); // close the connection ) else // an unsupported command was received ( String response = "ERROR"; sendHTTPResponse(connectionId, response); sendCommand(closeCommand, 1000, DEBUG); // close the connection ) ) ) /*****Check timer for each output******/ if (OUTPUTTMRIsSet != 0 && (OUTPUTTimer< millis())) { digitalWrite(OUTPUT1, OUTPUTTMRState); OUTPUTstate = OUTPUTTMRState; OUTPUTTMRIsSet = 0; } if (OUTPUTTMRIsSet != 0 && (OUTPUTTimer < millis())) { digitalWrite(OUTPUT2, OUTPUTTMRState); OUTPUTstate = OUTPUTTMRState; OUTPUTTMRIsSet = 0; } if (OUTPUTTMRIsSet != 0 && (OUTPUTTimer < millis())) { digitalWrite(OUTPUT3, OUTPUTTMRState); OUTPUTstate = OUTPUTTMRState; OUTPUTTMRIsSet = 0; } /***************************************/ } /* Name: sendData Description: Функция, используемая для отправки данных на ESP8266. Params: command - данные/команда для отправки; timeout - время ожидания отклика; debug - печатать в консоль?(true = да, false = нет) Returns: Отклик от esp8266 (если есть отклик) */ String sendData(String command, const int timeout, boolean debug) { String response = ""; int dataSize = command.length(); char data; command.toCharArray(data, dataSize); esp8266_Write(data, dataSize); // передача символов на esp8266 if (debug) { Serial.println("\r\n====== HTTP Response From Arduino ======"); Serial.write(data, dataSize); Serial.println("\r\n========================================"); } long int time = millis(); while ((time + timeout) >millis()) ( while (esp8266_Available()) ( // esp has data, so print it to the console char c = esp8266_Read(); // read the next character. response += c; ) ) if (debug) ( Serial .print(response); ) return response; ) /* Name: sendHTTPResponse Description: A function that sends an HTTP 200, HTML UTF-8 response */ void sendHTTPResponse(int connectionId, String content) ( // create an HTTP response String httpResponse; String httpHeader; // HTTP header httpHeader = " HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n"; httpHeader += "Content-Length: "; httpHeader += content.length(); httpHeader += " \r\n"; httpHeader += "Connection: close\r\n\r\n"; httpResponse = httpHeader + content + " "; // There is a bug in the code: the last character in "content" is not sent, so I added an extra space sendCIPData(connectionId, httpResponse); ) /* Name: sendCIPDATA Description: sends the CIPSEND= command ,<данные>*/ void sendCIPData(int connectionId, String data) ( String cipSend = "AT+CIPSEND="; cipSend += connectionId; cipSend += ","; cipSend += data.length(); cipSend += "\r\ n"; sendCommand(cipSend, 1000, DEBUG); sendData(data, 1000, DEBUG); ) /* Name: sendCommand Description: Function used to send data to the ESP8266. Params: command - data/command to send; timeout - response waiting time; debug - print to the console?(true = yes, false = no) Returns: Response from esp8266 (if there is a response) */ String sendCommand(String command, const int timeout, boolean debug) ( String response = ""; esp8266_Print(command ); // passing characters to esp8266 long int time = millis(); while ((time + timeout) > millis()) ( while (esp8266_Available()) ( // esp has data, so print it to the console char c = esp8266_Read(); // read the next character. response += c; ) ) if (debug) ( Serial.print(response); ) return response; )

Android application

To control all the above hardware components, we will use a simple Android application. This application will allow us to turn the output on or off directly or after a certain period of time.

Note: The application requires Android 4.0 (IceCreamSandwich) or higher.

  • First of all, you must know the IP address of your module. If you used a software serial port, the IP address will be printed in the console. If you used a hardware serial port, then you must use a cable to monitor the data on the RX and TX lines to see the IP address. You also need to know the port number that was specified in the Arduino sketch. After that, click "connect" to get the status of all three outputs. You need to make sure that your Wi-Fi router is turned on and you are connected to the local network.
  • Now click on any switch you want to turn on/off. Whenever you want, you can click "refresh" to refresh the status of all outputs.
  • In the "Timers" tab, you can set any of these three outputs to turn on/off after a certain period of time (from 0 to 24 hours).
  • After any action, you will receive a confirmation message indicating whether the command completed successfully or some error occurred.

Demo video

That's all! I hope the article was useful. Leave comments!