0% found this document useful (0 votes)
23 views16 pages

PL Unit-2

Progarammi language for iot r 18 jntuh

Uploaded by

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

PL Unit-2

Progarammi language for iot r 18 jntuh

Uploaded by

syedsamad3102002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

MicroPython Features:

Key Advantages

 Runs Python: Allows you to create simple, efficient, and easy-to-understand


programs.
 Ease of Use: This is a significant advantage over other boards like the Arduino.

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.

What You Can Do with MicroPython

 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 OF MICRO PYTHON:


1. Interpreted code incurs performance penalties, affecting high-precision and high-rate
tasks.
2. Higher memory usage compared to platforms like Arduino, potentially limiting large
programs.
3. Incomplete implementation of all Python 3 library features.

4. Limited debugging tools compared to other development environments.


5. Smaller community and fewer resources compared to full Python or other
microcontroller platforms.
6. Limited support for real-time operating systems (RTOS).
7. Potential compatibility issues with certain hardware peripherals.
8. Slower execution speed for computationally intensive tasks.
9. Less mature ecosystem for advanced features like machine learning and complex data
processing.

Experimenting with Python on Your PC:


Since MicroPython is essentially a scaled-down version of Python, you can run Python on
your PC to experiment with the language. It's beneficial to load Python on your PC even if
you have a MicroPython board, as it offers a more controlled environment for testing.

Benefits of Using Python on Your PC

 Convenience: It's easier to try out code on your PC.


 Control: You can better control the testing environment.
 Efficiency: Debugging Python code on your PC can help complete much of your
project before testing it on the MicroPython board.

Limitations

 Your PC can't communicate with electronic components or hardware like


MicroPython boards.
 However, you can test basic constructs such as function calls, printing messages, and
more.

Why Use Your PC?

Using your PC to debug your Python code allows you to:

 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.

Getting Started with Python on Your PC

1. Check for Python Installation:


o Open a terminal window (command prompt).
o Type the following command: python --version
o If Python is installed, you should see something like: Python 3.6.0
o If you see a version like Python 2.7.3, check if Python 3 is also installed by
typing: python3
2. Installing Python 3:
o If Python 3 is not installed or is an older version, download the latest version
from www.python.org/downloads/.
o Always install the latest version of Python 3, as MicroPython is based on
Python 3.

Caution

 There are two versions of Python: Python 2 and Python 3.


 Since MicroPython is based on Python 3, ensure you install Python 3, not Python 2.

Installing Python 3 on Windows 10:


1. Download Python:
o Visit the official Python website: python.org/downloads/windows/.
o You will find options for 32-bit and 64-bit versions, as well as a web-based installer
and a .zip format.
o Most people should use the Windows installer. Select either the 32-bit or 64-bit
version depending on your system.

2. Choose the Installer:


o Scroll down to the section named "Latest Python 3 Release."
o Click on the appropriate installer link for your system. For example, for a 64-bit
system, download the file named python-3.6.0-amd64.exe.

3. Launch the Installer:


o Find the downloaded file in your Downloads folder.
o Double-click on the file to start the installation process.

4. Follow the Installation Steps:


o The installer will open, and you will see a series of screens to step through.
o Step 1: Agree to the license agreement.
o Step 2: Choose the destination directory where you want Python to be installed.
o Step 3: Customize installation options if needed. It’s recommended to add Python to
your PATH environment variable during the installation.

5. Complete the Installation:


o After setting your preferences, click the "Install" button to begin the installation.
o The installer will copy files and set up Python on your machine.
o Once finished, you will see a completion screen.

6. Verify the Installation:


o Open a terminal window (command prompt) by searching for "cmd" or "Command
Prompt" in the Start menu.
o Type the following command to check the Python version:

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.

Running the Python Console:


1. Open the Python Console:
o Open a terminal window (command prompt) by searching for "cmd" or
"Command Prompt" in the Start menu.
o Enter the command:

python

(or python3 or python3.6 depending on your installation).

2. Run a Simple Program:


o At the prompt (>>>), type the following code:

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.

Steps to Write and Read Data from a File

Step 1: Create a File and Write Data

1. Open a text editor and type the following code:

# Step 1: Create a file and write some data


new_file = open("log.txt", "w") # Open file in write mode
new_file.write("1,apples,2.5\n")
new_file.write("2,oranges,1\n")
new_file.write("3,peaches,3\n")
new_file.write("4,grapes,21\n")
new_file.close() # Close the file

2. Save the file as file_io.py.

Step 2: Read Data from the File

1. Add the following code to the same file to read and print the data:

# Step 2: Open the file and read data


old_file = open("log.txt", "r") # Open file in read mode

# Use a loop to read all rows in the file


for row in old_file.readlines():
columns = row.strip("\n").split(",") # Split row by commas
print(" : ".join(columns)) # Print the row with colon separator

old_file.close() # Close the file

Running the Script

1. Open a terminal window (command prompt).


2. Navigate to the directory where you saved file_io.py.
3. Run the script using the following command:

python file_io.py

o On Windows, you may need to use:

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.

The Run, Evaluate, Print Loop (REPL Console)


Connecting to the 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:

Step 1: Connect the Board

1. Connect the Board to Your Computer:


o Use a USB to micro USB cable.
o The USB cable provides power and connectivity for the console.
o Wait for the board to boot (it may take 1-2 minutes the first time).
2. Browse the Drive:
o Once the board is connected, you can view the files on the board using your
computer's file explorer.
o For example, on Windows 10, you should see the USB drive mount
automatically.
o Notice there are two files with a .py file extension: boot.py, which is executed
on boot (hence the name); and main.py, which you can replace with your own
program if you want to use the board independently.
o There are also additional files such as the README.txt that contains some
instructions to using the board.
o The pybcdc.inf, which is a device driver installer for Windows.

Step 2: Install and Use PuTTY (Windows)

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.

Step 3: Use the REPL Console

1. Interact with the REPL Console:


o Once the terminal opens, you will see the REPL console.
o You can type Python commands directly and see the results immediately.
2. Example: Print a Message:
o At the prompt (>>>), type the following command:

print("Hello, World!")

Press Enter to see the output.


o
3. Change Terminal Colors (Optional):
o If you don't like the default color scheme, you can change it by selecting
"Colours" in PuTTY's settings.

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.

Off and Running with MicroPython:


To get started with MicroPython, especially if you have a Pyboard, follow these steps to
begin experimenting with simple 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:

 Contains common electronic components like resistors, capacitors, LEDs, diodes,


transistors, and sensors.
 Essential for learning and experimenting with circuits and electronic projects.
 Allows you to understand fundamental principles such as voltage, current, and
resistance.

 Breadboard:

 Used for prototyping circuits without soldering.


 Provides a platform to easily connect and disconnect components and wires.
 Ideal for testing and iterating on circuit designs quickly.

 Jumper Wires:

 Essential for making connections between components on a breadboard.


 Available in different lengths and colors for organizing and managing connections.
 Facilitates easy and flexible experimentation with circuit layouts.

Basic Electronics Kit:


Both Adafruit and Sparkfun offer basic electronics kits that include common components like LEDs,
switches, buttons, resistors, etc. The Adafruit Parts Pal, in particular, is packaged in a convenient
plastic case and contains a wide range of components essential for hobby-level electronics projects.

 Prototyping tools: Includes a half-size breadboard and jumper wires in various


lengths.
 LEDs: Green, red, and RGB LEDs for lighting and visual projects.
 Capacitors: Ceramic and electrolytic capacitors for storing electrical charge.
 Resistors: Various resistors in different values for controlling current flow.
 Diodes: Includes signal diodes and rectifier diodes for current direction control.
 Transistors: NPN and PNP transistors for amplification and switching applications.
 Voltage Regulators: Linear voltage regulators for stabilizing voltage levels.
 Other Components: Includes sensors (photocell, thermistor, vibration sensor),
potentiometers, piezo buzzer, switches (tactile and slide), and header strips.

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.

Here's the complete code (Listing 2-3):

import pyb # Import the Pyboard library

led = pyb.LED(4) # Get the blue LED instance (4 = Blue)


led.off() # Make sure the LED is off first

for i in range(0, 20): # Run the loop 20 times


led.on() # Turn LED on
pyb.delay(250) # Wait for 250 milliseconds
led.off() # Turn LED off
pyb.delay(250) # Wait for 250 milliseconds

led.off() # Turn the LED off at the end


print("Done!") # Print a message

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.

Running the Code:

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.

Example 2: Sequential LED Blinking:


In this example, we'll write code to blink the LEDs on the Pyboard in sequence using a while
loop. The LEDs will turn on and off one at a time, demonstrating more complexity than the
previous example.

Step-by-Step Explanation

1. Import the Pyboard library:

import pyb # Import the Pyboard library

This line imports the Pyboard library, which provides access to the board's hardware
features.

2. Turn Off All LEDs:

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.

for j in range(1, 5): # Loop through LEDs 1 to 4


led = pyb.LED(j) # Get the LED
led.off() # Turn the LED off
o for j in range(1, 5):: This loop iterates through the LEDs numbered 1 to 4.
o led = pyb.LED(j): This line gets the LED corresponding to the current value of j
and assigns it to the variable led.
o led.off(): This turns off the LED.

3. Sequential Blinking with While Loop:

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.

i = 1 # Initialize the LED counter

while True: # Loop forever


led = pyb.LED(i) # Get the next LED
led.on() # Turn LED on
pyb.delay(500) # Wait for 1/2 second
led.off() # Turn LED off
pyb.delay(500) # Wait for 1/2 second
i = i + 1 # Increment the LED counter
if i > 4: # If counter exceeds 4, reset to 1
i = 1

o i = 1: This initializes the LED counter to 1.


o while True:: This starts an infinite loop, which will run continuously.
o led = pyb.LED(i): This gets the LED corresponding to the current value of i and
assigns it to the variable led.
o led.on(): This turns on the LED.
o pyb.delay(500): This waits for 500 milliseconds (1/2 second).
o led.off(): This turns off the LED.
o pyb.delay(500): This waits for another 500 milliseconds.
o i = i + 1: This increments the LED counter.
o if i > 4:: If the counter exceeds 4 (since we only have 4 LEDs), it resets to 1.
o i = 1: This resets the counter to 1 if it exceeds 4.

Complete Code

Here’s the complete code for blinking the LEDs sequentially (Listing 2-4):

import pyb # Import the Pyboard library

for j in range(1, 5): # Turn off all of the LEDs


led = pyb.LED(j) # Get the LED
led.off() # Turn the LED off

i = 1 # LED counter

while True: # Loop forever


led = pyb.LED(i) # Get next LED
led.on() # Turn LED on
pyb.delay(500) # Wait for 1/2 second
led.off() # Turn LED off
pyb.delay(500) # Wait for 1/2 second
i = i + 1 # Increment the LED counter
if i > 4: # If > 4, start over at 1
i = 1
Running the Code

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.

Example 3: Using the Button and Interrupts:


This example demonstrates how to use the button on the Pyboard and set up an interrupt,
which triggers a function when the button is pressed.

Step-by-Step Explanation

1. Import the Pyboard library and set up the green LED:

import pyb # Import the Pyboard library


led = pyb.LED(2) # Get the green LED (2 = green)
led.off() # Ensure the LED is off

 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.

2. Define a function to flash the LED:

def flash_led():
for i in range(0, 25):
led.on()
pyb.delay(100)
led.off()
pyb.delay(100)

 def flash_led():: This defines a new function named flash_led.


 for i in range(0, 25):: This loop runs 25 times.
 led.on(): This turns the LED on.
 pyb.delay(100): This waits for 100 milliseconds.
 led.off(): This turns the LED off.
 pyb.delay(100): This waits for another 100 milliseconds.

This function makes the LED flash quickly 25 times.

3. Set up the button and register the callback:

button = pyb.Switch() # Get the button (switch)


button.callback(flash_led) # Register the callback function

 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.

4. Print a ready message:

print("Ready for testing!")

 print("Ready for testing!"): This prints a message indicating that the setup is
complete and the code is ready for testing.

Complete Code

Here’s the complete code for this example:

import pyb # Import the Pyboard library

led = pyb.LED(2) # Get the green LED (2 = green)


led.off() # Ensure the LED is off

def flash_led(): # Define the callback function


for i in range(0, 25):
led.on()
pyb.delay(100)
led.off()
pyb.delay(100)

button = pyb.Switch() # Get the button (switch)


button.callback(flash_led) # Register the callback function

print("Ready for testing!") # Indicate readiness

Running the Code

1. Enter the code into the REPL console line by line.


2. After seeing the message "Ready for testing!" in the REPL console, press the button marked
"USR" on the Pyboard.
3. Each time the button is pressed, the green LED will flash quickly 25 times.

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.

You might also like