[go: up one dir, main page]

0% found this document useful (0 votes)
6 views19 pages

05 - Micropython With ESP32

microPython with ESP32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
6 views19 pages

05 - Micropython With ESP32

microPython with ESP32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 19
519128, 21:67 MeroPython Programming with ESP32 and ESP#266 SESOKIFY ea HOME ESP32 > MICROPYTHON PROGRAMMING WITH ESP32 AND ESP8266 2 MicroPython@ @ Programmin 4 ¥ ESP32 ESP32, ESP8266, MGROPYTHON / MARCH 10,2025 | BYEBOKIFY MicroPython Programming with ESP32 and ESP8266 Lear how to MicroPython Programming with ESP32 and ESP8266, a re-implementation of Python programming language for microcontrollers Apart from a few minor differences, programming in MicroPython is very similar to programming in Python since it shares all of Python's language capabilities. MicroPython does not by default include the whole standard library since embedded systems and microcontrollers have far more limited capabilities than our PCs. MicroPython programming is identical to Python programming if you already know how to do it. You only need to keep in mind that MicroPython is only used for restricted devices. As a result, you may expect to sae a lot of traffic on your wgbsite, Q shop Actount Search Wishtist hitps:Tebokty.commicropython-progranming-w ith-esp32-and-esp8266/2focld=W Y2xjaw MsaJNeHRUA2FbOKMABIomKETFpSmitT}eSbUt0D... 1/19 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 This article explains the Python programming language syntax basics that also apply to MicroPython, like: Mathematical operators * Relational operators * Data types + print() function * Conditional statements * While and for loops * User defined functions * Classes and objects * Modules Prerequisites We're going to use the uPyCraft IDE in this tutorial, but you may use any other program. Follow these next tutorials to install and get started with the uPyCraft IDE: * Getting Started with MicroPython on ESP32 and ESP8266 * Install uPyCraft IDE: * Install uPyCraft IDE — Windows PC Instructions * Install uPyCraft IDE — Mac OS X Instructions © Install uPyCraft IDE — Linux Ubuntu Instructions * Flash/Upload MicroPython Firmware to ESP32 and ESP8266 Mathematical Operators Micropython is capable of doing mathematical operations. The following table shows the mathematical operators that are supported: Operator Mathematical Operation + Addition o a Q shop Account Search Wishlist hitps:febokty.commicropython-progranming-wth-esp32-and-esp8266/2focld=W Y2xjaw MsaJNeHRUA2FbOKMABIcmKETFpSmitT}eSbUt0D... 2/19 519128, 21:57 MeroPython Programming with ESP32 and ESPE266 - Subtraction Multiplication Division Division, discarding the decimal point Remainder after division In the Shell, try several operations to see how they work, For example: >>> 24249-3 uy >>> 28594/2312 12.3676 >>> 214522236/7.5 2.860297e+07 >>> 23//2 1 >>> 2583 1 you import the math module, you may perform more mathematical operations like square root, trigonometric functions, logarithms, exponentiation, etc. Relational Operators By using relational operators, comparisons may be performed. These show the relation between the two values and compare the values on each side Ay 2 Q 9 shop Account Search Wisi t -ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbcld=W Y 2xjaw MsaJNeHRUA2FIDORMABICMKETFDSmIITieSbUtOb.... 3/18 519125, 21:57 MeroPython Programming with ESP32 and ESPE266 Description Not equal to Greater than Greater than or equal to Less than or equal to Try several comparisons and test the result: >>> 2 == 3 False >>> 4 ss 4 True >>> 3>2 True >>> 489808234 2223 True >>> 4.5 >= 4.5 True Assigning Values to Variables You don't need to declare the type of each variable in Python. You know that you need to declare the ‘ype of a variable when edding a new variable if youre used tegrogramming your boards using the Arduino etn Python, there is a u6Qhne Search ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbcld=W Y 2xjaw MsaJNeHRUAFIDORMABICMKETFDSmIITieSbUNOD.... 4/19 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 For values like text or numbers, variables are simply storage placeholders. The equal sign (=), with the variable name on the left and the value on the right, is used to assign a value to a variable. For example, you might simply type the following to create a variable to hold the GPIO number where an LED is connected: led_pin = 23 In the Arduino IDE, you would have something like: const int led pin = ‘As you can see, Python is much simpler than programming in C (in Arduino IDE). 6 Note: The variable names you give must be case- sensitive and cannot include spaces; thus, led_pin differs from LED_PIN or Led_Pin. Data Types Variables don't simply store whole numbers; they may also store other types of values. This is where data types come into play. A data type classification tells what operations may be done with a value and how it should be stored. The following table shows the data types we'll use most often in our projects. Description int (Int) Integer (whole number) a a Q & aebotnt seuch wahtat -ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbcld=W Y 2xjaw MsaJNeHRUAZFIDORMABIeMKETFDSmIITieSbUNOD.... S/18 519128, 21:57 MeroPython Programming with ESP32 and ESPE266 float (Float) Number with a decimal point str (String) Set of characters between quotation marks bool (Boolean) True or False Let's create variables with different data types: >>> a = 6 >>> b >>> ¢ = 'Hello World!" po> d = The first value assigned to a is an integer, which is a whole number. The b variable contains a float value, which is a number with a decimal. The third value, ‘Hello World?’ is a string, which is a series of characters. A string must be put inside single (‘Hello World!’) or double quotation (‘Hello World!") marks. Finally, d is a Boolean, which is a type that can only take either True or False The type() function may be used to check the data type of a variable. This function accepts as an argument the variable whose data type you wish to check. type (variab For example, after declaring the variables in the previous example (a, b, ¢, and d), you can check their data type. For example, if you type: >>> type (a) Itretums: o Q shop Account Search Wishlist -ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITieSbUtOD.... 6/19 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 This tells us that a is an int (integer). Experiment with the other variables, and you should get >>> type (b) >>> type (e) >>> type (d) print() Function Between the brackets, the print() function prints the message into the Shell. Debugging the code and keeping track of what's going on is very useful in our projects. For example: >>> print ('LED is on’) Comments Python comments start with the hash character (#) and go alll the way to the end of the line. A commentis useful to add “notes” to your program or to tell everyone who reads the script what the program does. Your program doesn't get any more functionality as a result of this. For example: # This is just a comment There are occasions when you should avoid adding comments to save space on the ESP memory since we apg working under constr conditions in MicroP ¢pn, shop Account Search Wishtist hitps:Tebokty.com/micropython-progranming-wth-esp32-and-esp8266/2focld=W Y2xjaw MsaJNeHRUA2FbOKMABIcmKETFpSmitT}eSbUt0b... 7/19 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 Conditional Statements You'll probably need to perform various actions based on whether a given condition is True or False to write useful programs. Conditional statements are what we're talking about. The following describes their structure: if pri>: if : elif : a) is a Boolean expression, and it can be either True or False. K itis True, the right after it is executed. The should be indented so that Python knows what statement belongs to each expression. The elif statement stands for else if and runs only if the first if condition is not True The else statement only runs if none of the other expressions are True A program may have an unlimited number of elif statements. I's not required to include another clause, but if there is one, it must come at the end. Curly brackets are used in the Arduino IDE to define code blocks. We use indentation with MicroPython. After each expression, you also need to include a colon (:). The expression does not need to be enclosed inside parentheses, unlike the Arduino IDE. 6 6 Important: Four spaces are the standard indentation in Python. To fit more code into the ft a Q shop Account Search Wishlist hitps:Tebokty.commicropython-progranming-with-esp32-and-esp8266/2focld=W Y2xjaw MsaJNeHRUA2FbOKMABIomKETFpSMitT}eSbUt0D... 8/19 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 memory of the microcontroller, the indentation in MicroPython should only be 2 spaces. While and For loops As long as a condition is satisfied, loops let you execute a piece of code multiple times, While and for loops are two different types of loops. For instance, using a while loop, you can print all the numbers between 1 and 10: number = while number <= 10: print (number) number = numb As long as the number variable's value is less than or equal to (<=) 10, the while loop's code, which is shown by the indentation, is executed, Every loop prints the current number, followed by an addition of 1. You can also print numbers from 1 to 10 using a for loop, like this: number for number in range(1, 11): print (number) ‘As long as the value of the long variable falls between the range of 1 and 11, the for loop will execute. The range() function automatically assigns the next value to the next variable until itis one lower than the final value you specify. When you wish to repeat a block of code a certain number of times, you should use a for loop. When you want to repeatedly run code until a certain condition is no longer true, use a while loop. Then, if youre lucky enough to have a job, you may be able to get away with it. o a Q shop Account Search Wishlist ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSMIITIeSbUOD.... 8/18 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 The for and while Boolean expressions should have a colon right after them, much like the conditional statements, and the expressions that will be executed should be indented. User-defined Functions You use the word def, followed by the side you wish to give the function, and a set of brackets to define a new function, Add a colon after the parentheses, then tell the function what to do. In MicroPython, the statements must be indented by two spaces. For example: etion(, , ...): return For example, a function that converts the temperature in Celsius to Fahrenheit could be the following: def celsius_to_fahrenheit (temp_c us): emp_fahrenheit = temp_celsius * (9/5) + return temp fahrenheit The celsius_to_fahrenheit() function accepts as an argument a temperature in Celsius (temp_celsius). Then, it does the calculation to convert the temperature. Finally, it retums the temperature in Fahrenheit (femp_fahrenheit) 6 Note: Functions don’t necessarily need to return something. They could just perform some work without needing to return anything. Classes and Qbjects a shop Account Search Wishlist hitps:Tebokty.com/icropython-progranming-wth-esp32-and-esp6266/2focId=W Y2xjaw MsaJNeHRUA2FbOKMABIcmKETFpSmitT}eSbU0... 10/19 925, 21:57 MeroPython Frogramming with ESP82 and ESP8268 Python is a language for object-oriented programming (OOP). Classes and objects are two crucial OOP ideas that you should comprehend Aclass is an object's blueprint. t specifies a set of characteristics (data and function) for an object. Methods are the names given to the functions found inside a class. The class keyword is used to define classes, followed by the class name. For example: 6 Note: By convention, classes’ names in Python should be CapWords. However, you can give it whatever name you want. Aclass's instances are objects. Simply put, itis a single entity made up of data and methods. Alll the functions of the object's class are accessible through it. Confused? Take a look at a simple example. We may think of the term “person’ as a class if we'd like to define several persons in a Python program using the same attributes. Using attributes like name, age, nationality, etc., we may wish to define a person. o a Q shop Account Search Wishlist -ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbcld=WY 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUNO... 11/18 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 Therefore, a class named “Person” may be created. The attributes of our class will be as follows: name, age, and country. As many attributes as you want may be added. We'll also create a method (function) that prints a summary of the person depending on its attributes: name = "" age = 0 country = "" def description(self) : print("%s is %d years old and he is from %s." %(self.name, self.age, self.country)) You can see that we define a new class by using the keyword class, followed by the name we wish to give the class. We define a number of variables that may store values within the Person class. By default, the age is 0, and the pgme and country are emgy stings. The function ((@hod) that p ins ll the yajyes ofthe variables $#@Pthe Shell is then alsAekstned Search wisi ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUNO... 12/18 t 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 The self-parameter should be an argument for all functions inside a class, along with any other arguments that may be required The self parameter refers to the actual object. itis used to get access to variables belonging to the class. To access the name variable inside the class, for example, we should use self name. We can produce as many Person objects as we desire by using the class we just built Aname, an age, and a nation will be included in the Person object. Using the description() method, we can also printits description. For example, to create a new Person object called person1: >>> personl = Person() Set the object's properties To set the name, age, and country of the person1 object. You can do it as follows: >>> personl.name >>> personl.age >>> personl.country = "USA" Calling methods Later in your code, you can use the created description() method on any Person object. To callthe description() method on the person? object: >>> personl.description() This should print the following: BokFig is 40 years oland be Ss from (B. shop Account Search Wisi t ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUN0... 13/18 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 You should now understand that you can create as many objects as you want using the same class and that you can use the available methods with all of that class's methods. petsont.descriptont) person2.deseriptiont) eae The constructor method You may use the constructor method inside your class instead of having to define a class and then set the object's properties, which can be time-consuming. As soonas a class object is created, data is started using the constructor method. Also known as the __init__ method, the constructor method is a method. The Person() class looks as follows when using the __init__ method init__(self, name, age, country): e = age self.country = country def descr on (self): print("%s is %d years old and he is from $s." self.age, self.country)) o a Q shop Account Search Wisi t ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUNO.... 14/18 925, 21:57 MeroPytnon Programming with ESP32 and ESP8266 Then, to instantiate a Person object with the same attributes we've defined earlier, we just need to do the following: >>> personl = Person("BokFive", 40, "USA") Kyou callthe description() onthe person? object, you'll get the same result >>> personl.description() BokFive is 40 years old and he is from USA. Modules You may use a set of classes and functions from a module in your code. A module is a file. it's possible to call ita library if you want to, but it’s not a must. You just need to import that class into your code to have access to the classes and functions inside that code. Use pre-made modules from the standard Python library or create your own. When it comes to MicroPython, it only comes with a small portion of the standard Python library, but it does come with a set of modules to control GPIOs, make network connections, and much more. Importing modulesilibraries is as simple as using module_name For example, to import the machine library that contains classes to control GPIOs, type the following: import machine You won't need all the classes in one module for the majority of programs. Just a single class may be what you wish to import. To import ony Pin cass from the @gchine mode, for example t shop Account Search Wisi -ntps:tlebokty.com/micropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUN0.... 15/18 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 machine import Pin machine module ur script from machine import Pin Conclusion The basics of Python that also apply to MicroPython have just been touched on in this tutorial, You'll find that MicroPython has a far more straightforward and user-friendly syntax if youre accustomed to programming electronics using the Arduino IDE. Let's just summarise a few of the key differences between your Arduino sketches and MicroPython programs: You don't use a semicolon at the end of a statement. After Boolean expressions in conditional statements and loops, you use a colon:. To define code blocks, use indentation instead of curly brackets () When creating a variable, you don’t need to define which data type it is; you don’t need to declare a variable. Indentation in MicroPython is 2 spaces. If you like MicroPython, you may also like: * Howto Flash MicroPython Firmware to ESP32 and ESP8266 * Getting Started with MicroPython on ESP32 and ESP8266 * Howto install uPyCraft IDE on a Windows PC We hope you find this tutorial useful. Thanks for reading ft a Q shop Account Search Wishlist ‘ntps:tlebokty.com/micropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUNO... 16/19 519128, 21:67 MeroPython Programming with ESP32 and ESP#266 ESP32 ESP8266. —-MicroPython Python Leave a Reply Your email address will not be published. Required fields are marked * Your Name * nail Address * Your Website Comment O Save my name, email, and website in this browser for the next time | comment. Post Comment The 1st Technology & Business Bookstore in the world o a Q shop Account Search ist ‘ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbclt=W Y 2xjaw MsaJNeHRUAZFIDORMABIeMKETFDSmIITIeSbUN0.... 17/18 519128, 21:57 MeroPython Programming with ESP32 and ESP#266 f v¥oo Need Help +2 - 01013674596 Monday ~ Friday: 9:00-20:00 Saturday: 11:00 - 15:00 contact@ebokify.com Explore Blog Sitemap About us Contact Us Sign in/Join Our Service FAQs Returns Wishlist Authors Privacy Policy Categories Ai Software Hardware Business Technology o a Q shop Account Search Wishlist -ntps:tlebokty.com/nicropython-programming-w th-esp32-and-esp8266/7fbcld=W Y 2xjaw MsaJNeHRUAZFIDORMABICMKETFDSmIITIeSbUNO.... 18/19 819128, 21:57 MeroPython Programming with ESP32 and ESPE266 Ebokify. o a Q shop Account Search Wishlist hitps:Tebokty.com/micropython-progranming-w ih-esp32-and-esp8266/2focld=W Y2xjaw MsaJNeHRUA2FbOKMABICmKETFpSMitT}eSbU0... 19/19

You might also like