Getting Started with ESP32 Wireless Networking in C | Wirelessly Enable Any Project with ESP32

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
wirelessly enabling your latest project has never been easier for 10 us dollars the esp32 by expressive puts the power of wi-fi and bluetooth directly into your hands what is up guys welcome back to another low level learning tutorial in today's video i'll be showing you all how to put the power of esp32 into your hands and set up the wi-fi and tcp controller on the device and by the end of this video you'll know how to connect your esp32 to a wireless network and send and receive data over tcp for your latest iot project the esp32 while powerful is arguably very difficult to program and while there is extensive documentation in its api the start to finish flow of how to enable the wi-fi interface create a socket connect to a remote server etc is not entirely straightforward now there is the cop-out option of using the simplified arduino interface for the esp32 which extracts away all the detail and optimization of how the device works but we don't do that here so in today's video we're writing this in c to do this you first need to have the esp32 idf installed if you don't already have that set up feel free to check out my previous video on the esp32 i'll put a card right here for that video and a link in the description now let's get to the code normally in my videos when i'm programming with you guys i actually run through and code in front of you line by line explain what my thought process is when i'm doing that programming in this video i'm not going to do that primarily because there is so much code to go through and i think a video writer's type in front of you would not be very exciting so instead i'm going to walk through this code that i've already written that connects to a wireless network connects to a host gets some information from that host and then does something with it and kind of explain to you how that works now the code enters at this function called app main if you remember from our previous esp32 tutorial the app main is the entry point to free rtos where it creates the main task where the user is able to insert their code so here we have app main where our code runs there's a bunch of boilerplate stuff here it's not very interesting or important this is actually stolen from a previous example where we initialize the nvs or the non-volatile storage in flash that is where we're going to eventually store our wi-fi config and we need this to be initialized before we can do that every time we boot up the device in our code here we check to see if there are any free pages left in the flash and if there aren't we completely erase the flash and then re-initialize it to give us room and then make sure that there were no errors in doing that once we've initialized the flash we can do our connect wi-fi function and obviously we check to see if that fails after it gets ran and up here is the connect wi-fi function where the meat and potatoes of this tutorial is right so the wi-fi function does what it says in this comment connects to the wi-fi and return the result did we or did we not successfully connect and we tracked that in a status variable here i broke the code up into major events where things are happening in these star comments and then beneath the star comments are the double slash comments where singular events are happening right so this is like the big summary and these are the little parts within each function you see this esp error check all that's doing is checking that the return value of the esp api call is zero and if it's not zero it throws an abort and then it tells us why it broke so here we just initialized the entire network interface driver of the esp32 no parameters required for that that's very default stuff the big thing that happens here and kind of a theme of this tutorial is we create what's called the default event loop so the esp32 is designed to be written via event driven programming where there's actually an infinite loop happening in the esp32 and it checks to see if different events have occurred in the esp32 and then once an event has occurred it checks through a list of callback functions that we set up and if we have a callback function registered with a certain event then it calls that function and allows us to take action and we'll explain how that works down here a little bit but we create that default event loop so that it begins checking for events in the background now within the network interface driver for the esp32 we create what's called a default wi-fi station it basically just says hey we're going to do wi-fi and get ready then we just create a default wi-fi config this config structure will eventually have your ssid that you're connecting to the password for that ssid the type of authentication you're doing so wpa versus wpa2 versus wep etc so by default we create a default one so there's no ssid no password this just allows us to get the wi-fi interface moving and you know start programming events against it we are going to create an event group so what an event group does is it allows us to check the output of an event that gets called and see if our event was successful or not so again i'll go into this in more detail in the event handler itself just know that this is where the output of the event is going to live and this is a global variable it actually lives up here in the top of the code right so this is our event group where all the status information gets held for the event okay so the big meat and potatoes and what was kind of confusing for me but it took me a minute to figure out but i've actually got it pretty down pat is the esp event handler instance register so in esp32 like i said there's a giant loop running and it's checking for different things that are happening and seeing hey does the user have an event handler registered for this event if the answer is yes it will call this function so i set up two event handlers for us to do an action on the first is if i see a wi-fi event and if it's any wi-fi event type so normally you specify the wi-fi base event and then i could say wi-fi station connect or wi-fi station disconnect as kind of a filter to say what i do and do not call this function for but in this case i use the esp event any id global catch-all which says if i literally see any wi-fi event i want to call this function and do something and then this null don't worry about that and here we just say this is the instance id of our event handler and we use that later to eventually close our event handler and unregister us from that event loop and then same thing down here i instantiate another event handler for an ip event that says hey if my station if me if i got an ip i want to run this function so basically we set up one for wi-fi events and then one for a very particular ip event and we'll show you why that matters here in a second so we set up the config of our wi-fi controller and this is where you normally put your your ssid sid for me and i'll do my password right which is like you know super secure password i'm not actually going to use my real stuff because i don't want you internet gremlins to come hunt me down but you have ssid and your password and you put your authentication mode right so for us it's going to be authentication uh wpa2 psk pre-shared key and you can just put these as defaults these are the capable and required these are just pretty boilerplate so eventually we set the mode of the wi-fi to be a station and then we set the config of our station to be our new config so this one that has now our ssid and our password and then we say wi-fi start this is where the magic happens and the event loop for the wi-fi controller kicks off so two things are gonna happen once we do this we're gonna see a station initialization complete and this function here is going to block until our wi-fi event group remember this is where our status bits are stored for our events are going to reflect either a wi-fi success or a wi-fi failure and we will wait as long as we have to and this port max delay is i believe one second so we'll wait for this to happen and one of these has to be true either a wi-fi success or a wi-fi failure so we can go up and check out the actual event loops that are going to get ran and explain to you how they allow us to connect to the wi-fi so we set up the wi-fi event handler here and we say if the event base is wi-fi which to get here it has to be and if the event id is a wi-fi event station start meaning the station has just turned on right we just said esp wi-fi init will tell the user hey we're connecting to the access point and we say esp wi-fi connect and that's it this will connect to the wi-fi what we need to be able to handle is if there is a failure or a disconnection in the station connection so then we say if the event is a wi-fi event but it's also a wi-fi event station disconnected type here we track the number of failures we've already had with this s retry number and say okay cool no big deal we disconnected but we're going to try to reconnect and then every time we try to reconnect and we increment the number of failures we've had if we get to the point where the failures have exceeded some max failures value which is here we call it 10 we say hey guys i i can't connect to the wi-fi so i set in the wi-fi event group status handler that we have had a wi-fi failure otherwise if we get through this point where we had the event and we successfully connect eventually we'll connect and we'll get a dhcp lease from the dhcp server right from the wi-fi network and this event will trigger if the event base is ip event which again it has to be to get here and we have an ip event the station got an ip meaning we have successfully retrieved an ip from the network we will say that we can you know log the ip address here and we'll put into our event group status tracker that we've had a wi-fi success so station has started we connect to the wi-fi there are no failures this event gets triggered and then we set the wi-fi success bit in our event group if both of those things happen we will have a wi-fi success or a wi-fi failure in our event groups so this will stop blocking at this point once it stops blocking we can then retrieve the bits using this function and say okay if the bits retrieved are a success cool we successfully connected to the ap otherwise if the bits and failure are true we successfully fit or we failed to connect to the ap and then if somehow we get bits that are other than these two we've had some unexpected event there's a memory of corruption we gotta get out of there so this is all failure so based on these outputs we set the status of our function to either success or failure and then before we return we unregister ourselves as event handlers right once we've gotten past this point we now have an ip address and we are connected we no longer want these callback functions to proc off those events so we pull the handlers out of that loop by unregistering them from free rtos and then we event group delete we delete that status container for our event loop and we return the status so once we return we are now back in app main if we have successfully connected we get a wi-fi success if that is not the case we say hey we failed to connect we failed 10 times we're just going to end it we can't do anything about that and we return but once we've successfully gotten out of there now we have an ip address we're nice and happy we can talk to other servers on the network we can now use this to connect via a socket to other servers and get data right have them remotely control us or we can remotely control them or something like that so we will do connect to tcp server to connect to another server and then pull back data and then do something with it right you know perform some action via the the input that the user has given us so in our function not tcp server at this point what's cool about expressive is that all of the code most of the code is posix compliant right so if you've done any kind of standard c network programming this is very similar to you right and all we're going to do here is connect to the server and return the result so here we connect to the tcp server by creating you know standard posix compliance structures a sock adder in we say the sock adder in family is af inet there's a little exclamation point delete that we see the sock adder in uh sin adder the you know the server address is some hard-coded ip address that i can show you guys later and then the port is some hard-coded port right very straightforward c programming stuff so once we've gotten away from the esp32 wi-fi driver interface we can just do very basic you know programming at pretty much the the linux composix compliant level we connect to the server which is specified by this ip address and this port if we don't connect successfully then we say that we fail then we take some action we close the socket we leave if we did connect successfully we zero out some read buffer and then we read from that socket over the network and we printed the screen and if we wanted to we could say if you know stir compare of read buffer and hello is true then we esp log i we did it right something like that pretty something something silly cool you take some action based on user input the whole purpose of this you can use this to make your project behave in whatever way you want it to right but this is just getting the network stack off the ground so i'll show you guys it in action um i've got it set up here i have my raspberry pi ready to roll here this is that host you saw in the connect script where the ip address is listening here first we're going to idf.pop build i'm not going to do that because i've already actually you know built the code then we're going to flash the board i'm not going to do that because i've already actually built the code but then we are going to idf.pi monitor by monitoring the code we can actually talk to the usb port here see here we have connected to the server you can pull back up the uh cam link can we see we have a connection from the device i will type in some code hello there darling the device has now gotten that data from our server remotely over the network and we can do whatever we want with this we can have this be commands from the user we can have the esp32 send and update over the network about maybe it's you know the network information the temperature outside you can have this thing move motors around and do whatever you want um anyway guys that's all i got i hope this was informative i hope you learned something if you did do me a favor hit like hit subscribe and i'll see you guys next week as we dive deeper into esp32 peripherals i'll see you guys then [Music]
Info
Channel: Low Level Learning
Views: 55,560
Rating: undefined out of 5
Keywords: esp32 wifi, esp32, esp32 idf, iot development framework, freertos, raspberry pi, pico, rpi, microcontroller, arduino, maker, craft, hobby, electronics, wires, temperature, safety, project, board, electric, leds, led, thonny, python, micropython, os, ide, onewire, ds18b20, circuitpython, review, launch, measure, probe, rp2040, specs, specifications, how to, guide, programming, Pico emulation, retro games raspberry pi pico, etaprime, eta prime, raspberry pi pico, arm cortex m0+, low cost
Id: _dRrarmQiAM
Channel Id: undefined
Length: 14min 47sec (887 seconds)
Published: Tue Jan 04 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.