PL Unit-2
PL Unit-2
Key Advantages
Main Features
1. Interactive Interpreter:
o Read-Evaluate-Print Loop (REPL): Connect to the board via USB (or
WiFi) and type in code to execute it one line at a time. Great for prototyping
and development.
2. Python Standard Libraries:
o Extensive Support: Supports more than 80% of commonly used Python
libraries, including:
JSON parsing
Socket programming
String manipulation
File input/output
Regular expressions
3. Hardware-Level Libraries:
o Direct Hardware Access: Control hardware components such as:
Analog and digital pins
Pulse-width modulation (PWM) for controlling power to devices (e.g.,
adjusting a fan's speed)
4. Extensible:
o Custom Libraries: Advanced users can add new libraries written in C or C++
to extend MicroPython's functionality.
Control Hardware: Turn LEDs on/off, drive servos, read sensors, and display text
on LCDs.
Expand Program Features: Write and store code modules on an SD card.
Networking: Some boards support WiFi, enabling network connections.
Overall, MicroPython allows you to do just about anything you can with other
microcontroller boards, with the added benefit of using Python.
Limitations
Get much of your project working before transferring it to the MicroPython board.
Avoid common mistakes, like writing an entire solution without testing smaller parts.
Start small and test each part of the code before adding more tested parts.
Caution
python --version
o You should see output indicating the installed version of Python, such as Python
3.6.0.
o If you have both Python 2 and Python 3 installed, you may need to use:
python3 --version
7. Launching Python:
o If Python is not added to your PATH, you can use the Python console shortcut from
the Start menu to launch Python.
python
print("Hello, World!\n")
o Press Enter. You will see the message "Hello, World!" printed on the screen.
o The \n at the end is a special character that issues a carriage return, moving
the cursor to a new line.
3. Understanding the Process:
o The interpreter works by executing one line of code at a time when you press
Enter.
o Unlike running a program stored in a file, the code you enter in the console is
not saved.
4. Example - Running the Python Console on Windows:
o Open Command Prompt:
o Enter python and press Enter:
o Type print("Hello, World!\n") and press Enter:
5. Quit the Console:
o To exit the Python console, type:
quit()
o Press Enter.
6. Next Steps:
o While running a simple "Hello, World!" program is a good start, you can try
more complex examples.
o Experiment with other basic Python commands and functions in the console to
get familiar with the interpreter.
Running Python Programs with the Interpreter
Example: File Input/Output (I/O)
Suppose you need to save data to a file or read data from a file for your project. Instead of
figuring out how to do this on your MicroPython board, you can experiment with file
operations on your PC.
1. Add the following code to the same file to read and print the data:
python file_io.py
python.exe file_io.py
Expected Output
When you run the script, you should see the following output:
1 : apples : 2.5
2 : oranges : 1
3 : peaches : 3
4 : grapes : 21
Explanation
The script writes data to log.txt with commas separating the values.
It then reads the data, splits each row by commas, and prints the values with a colon and
space as separators.
This example demonstrates how easy it is to write and read data from files using Python.
Now that you’ve experimented with Python on your PC, you can explore using MicroPython
on a typical MicroPython board.
If you are using a microcontroller board like the Pyboard with MicroPython, you can connect
to it using the REPL console. Here's how to get started:
To connect to the REPL console on Windows, you need a terminal program like PuTTY.
1. Install PuTTY:
o Download PuTTY from Simon Tatham's website.
o Choose the appropriate .msi file (32- or 64-bit).
o Run the installer and follow the prompts to complete the installation.
2. Find the COM Port:
o Open the Device Manager.
o Expand the "Ports (COM & LPT)" section.
o Find the Pyboard listed as "USB Serial Device (COMn)" (where n is the port
number, e.g., COM3).
3. Open PuTTY and Connect:
o Launch PuTTY from the Start menu or search for it.
o In PuTTY, select "Serial" as the connection type.
o Enter the COM port number (e.g., COM3) and set the speed to 115200.
o Click the "Open" button to start the terminal.
print("Hello, World!")
Now you are ready to use the REPL console to interact with your MicroPython board. This
setup allows you to run and test Python code directly on the board, making it easy to develop
and debug your projects.
1. Pyboard Overview:
o The Pyboard features a micro USB connector and a micro SD card reader on
the right side.
o It includes four small LEDs and a button labeled USR, which are components
used in the examples.
2. Getting Started:
o If you have a Pyboard, you can immediately start exploring MicroPython
projects without needing additional components or internet connectivity.
o The Pyboard's built-in LEDs and button make it an excellent choice for
beginners to learn MicroPython programming.
3. Networking Limitation:
o Note that the Pyboard does not support networking out of the box, which may
limit its use for IoT projects that require internet connectivity.
o However, there are methods to connect the Pyboard to the internet, which will
be covered in more advanced sections.
4. Exploring Other Options:
o There are various MicroPython-compatible boards available besides the
Pyboard, each with unique features and capabilities.
Additional Hardware:
Basic Electronics Kit:
Breadboard:
Jumper Wires:
This kit provides everything you need to start learning and experimenting with electronics
and is priced affordably at $19.95, making it a practical choice for beginners looking to
explore MicroPython and electronics projects.
Breadboard and Jumper Wires:
A breadboard is an essential tool for anyone working with electronics. It allows you to easily
connect electrical components without soldering. The breadboard is designed with
interconnected columns that let you plug in leads of components to make a connection. This
is particularly useful for prototyping and testing circuits.
The board is split into two rows, which makes it easy to use integrated circuits (ICs) by
placing them in the center of the board. Jumper wires, or simply jumpers, are used to connect
different parts of the circuit on the breadboard to each other or to the MicroPython board..
The Adafruit Parts Pal includes a half-sized breadboard, which is one-half the length of a
standard breadboard but still provides ample space for most projects. The half-sized
breadboard fits neatly into the Parts Pal box, making it convenient to store and transport.
Additionally, depending on your MicroPython board's header pins, you might need different
jumper wires. MicroPython boards can have either male or female header pins. If your board
has male header pins, you’ll need female jumper wires, and vice versa. Adafruit offers a
variety of jumper wires to suit your needs.
By having a breadboard and the appropriate jumper wires, you'll be well-equipped to start
prototyping and experimenting with your MicroPython projects.
EXAMPLE 1: Blink the Blue LED
In this example, we'll write code to blink the blue LED on a Pyboard. The board has four
LEDs: red, green, yellow (orange), and blue.
Let's write code to make the blue LED blink on and off every 250 milliseconds, so it flashes
quickly.
Explanation:
1. Comments: Lines starting with # are comments and are ignored by MicroPython.
They help explain what the code does.
2. Import the Library: import pyb imports the Pyboard hardware library.
3. Initialize the LED: led = pyb.LED(4) initializes the blue LED (LED 4).
4. Ensure LED is Off: led.off() ensures the LED is off initially.
5. Loop: The for loop runs 20 times. Inside the loop:
o led.on() turns the LED on.
o pyb.delay(250) waits for 250 milliseconds.
o led.off() turns the LED off.
o pyb.delay(250) waits for another 250 milliseconds.
6. Final Steps: After the loop, led.off() ensures the LED is off, and print("Done!")
prints a completion message.
1. Enter the code line by line into the REPL console. Skip the lines starting with #.
2. For the for loop, type the indented lines carefully.
3. After the second pyb.delay(250) call, press Enter on a blank line to end the
indentation block.
4. Observe the blue LED blinking on the Pyboard.
Note:
On macOS and Linux, you might be able to copy and paste the code into the REPL
console. This may not work on all platforms or terminal programs.
To rerun the code or if you make a mistake, close the PuTTY window, eject the USB
drive, and press the reset button (marked RST) on the board to reinitialize the REPL
console.
Step-by-Step Explanation
This line imports the Pyboard library, which provides access to the board's hardware
features.
Before starting the main loop, we ensure that all LEDs are turned off. This helps to
clear any previous states and ensures that our program starts with a clean slate.
We'll use a while loop to turn each LED on and off in sequence. A counting variable
i will keep track of which LED to light up.
Complete Code
Here’s the complete code for blinking the LEDs sequentially (Listing 2-4):
i = 1 # LED counter
When you run the code, the LEDs will blink in sequence: red, green, yellow (orange), and
blue. This sequence will continue indefinitely until you reset the board. Remember to eject
the drive first to prevent data corruption.
Additional Notes
For Loop vs. While Loop: The for loop is used to iterate over a sequence (in this case, the
LEDs) a specific number of times. The while loop runs as long as the condition is true, which
in this example, creates an infinite loop.
Delays: The pyb.delay() function pauses the program for the specified number of
milliseconds. Adjusting these values can change the speed of the LED blinking.
Resetting the Board: If you need to stop the program, you can reset the Pyboard by pressing
the reset button. Always remember to eject the USB drive safely before doing so.
Step-by-Step Explanation
import pyb: This imports the Pyboard library, allowing access to the board's hardware
features.
led = pyb.LED(2): This line creates an instance of the green LED (LED number 2) and
assigns it to the variable led.
led.off(): This ensures that the LED is off when the program starts.
def flash_led():
for i in range(0, 25):
led.on()
pyb.delay(100)
led.off()
pyb.delay(100)
button = pyb.Switch(): This creates an instance of the user button (marked "USR" on
the Pyboard) and assigns it to the variable button.
button.callback(flash_led): This registers the flash_led function as a callback,
which means flash_led will be executed whenever the button is pressed.
print("Ready for testing!"): This prints a message indicating that the setup is
complete and the code is ready for testing.
Complete Code
Additional Notes
Interrupts and Callbacks: Interrupts allow your program to respond immediately to certain
events (like a button press) without constantly checking for those events. A callback function
is a function that is automatically executed in response to an interrupt.
Eject the Drive: Before unplugging or resetting your Pyboard, make sure to eject the USB
drive from your computer to prevent data corruption.