• For Loops in MicroPython on Raspberry Pi Pico

    For loops are one of the most commonly used loops in programming, including MicroPython on Raspberry Pi Pico. They allow you to repeat a set of instructions a specific number of times, making your code more efficient and concise.

    In MicroPython, a for loop is used to iterate over a sequence of values, such as a list, tuple, or string. The general syntax for a for loop in MicroPython is as follows:

    for variable in sequence:
        # Code to execute for each item in the sequence
    

    Here, variable is a temporary variable that takes on the value of each item in the sequence. The code block under the for statement is executed for each item in the sequence, with variable taking on the value of each item in turn.

    For example, let’s say we have a list of numbers and we want to print each number in the list:

    numbers = [1, 2, 3, 4, 5]
    
    for num in numbers:
        print(num)
    

    In this code, num takes on the value of each item in the numbers list, and the print statement outputs each number in turn.

    In addition to lists, for loops can also be used with other sequences such as tuples and strings. For example:

    name = "John"
    
    for char in name:
        print(char)
    

    This code outputs each character in the string name, one character per line.

    You can also use the built-in range() function with for loops in MicroPython. The range() function returns a sequence of numbers starting from 0 (by default) and incrementing by 1, up to a specified number. For example:

    for i in range(5):
        print(i)
    

    This code outputs the numbers 0 through 4, one number per line.

    You can also specify a starting value and a step size for the range() function. For example:

    for i in range(1, 10, 2):
        print(i)
    

    This code outputs the odd numbers from 1 to 9, one number per line.

  • While Loops in MicroPython on Raspberry Pi Pico

    While loops in MicroPython on Raspberry Pi Pico are used to execute a block of code repeatedly as long as a certain condition is true. The general syntax for a while loop is:

    while condition:
        # code to execute
    

    The condition is checked at the beginning of each iteration. If the condition is true, the code inside the loop is executed. Once the code has been executed, the condition is checked again, and the loop continues until the condition is false.

    Here’s an example of a simple while loop:

    i = 0
    while i < 5:
        print(i)
        i += 1
    

    In this example, the loop will continue to execute as long as i is less than 5. Inside the loop, the current value of i is printed, and i is incremented by 1. The loop will continue until i reaches 5, at which point the condition i < 5 will be false, and the loop will terminate.

    It’s important to make sure that the condition in a while loop will eventually become false, otherwise the loop will continue to execute indefinitely, which is known as an infinite loop. An infinite loop can cause your program to hang or crash, so it’s important to make sure that your loop will eventually terminate.

    Here’s an example of an infinite loop:

    i = 0
    while i < 5:
        print(i)
    

    In this example, the condition i < 5 will always be true, since i is never incremented. This will cause the loop to continue to execute indefinitely, which is not what we want.

    While loops can be useful for a variety of tasks, such as reading data from sensors, controlling motors, or performing other repetitive tasks. By using while loops, you can make your code more efficient and easier to read.

  • Introduction to Loops in MicroPython on Raspberry Pi Pico

    Loops are an essential part of any programming language, including MicroPython on Raspberry Pi Pico. They allow you to execute a block of code repeatedly, saving you time and effort. In this article, we’ve introduced you to the two types of loops in MicroPython: for loops and while loops.

    What are Loops?
    A loop is a programming construct that allows you to execute a block of code repeatedly until a specific condition is met. There are two types of loops in MicroPython: for loops and while loops.

    For Loops
    A for loop is used when you want to execute a block of code a fixed number of times. The syntax of a for loop in MicroPython is as follows:

    for variable in sequence:
        # Code to execute

    The variable is assigned to each element of the sequence in turn, and the code inside the loop is executed. Here’s an example:

    for i in range(5):
        print(i)

    This code will print the numbers from 0 to 4.

    While Loops
    A while loop is used when you want to execute a block of code repeatedly until a specific condition is met. The syntax of a while loop in MicroPython is as follows:

    while condition:
        # Code to execute

    The code inside the loop will be executed repeatedly until the condition becomes false. Here’s an example:

    i = 0
    while i < 5:
        print(i)
        i += 1

    The code first initializes the value of i to 0. Then it enters the while loop and checks if the value of i is less than 5. Since i is initially 0, the condition is true and the loop begins.

    The loop prints the current value of i using the print() function and then increments the value of i by 1 using the += operator. This process repeats until the value of i is no longer less than 5, at which point the loop ends and the program continues with the rest of the code.

    When you run this code in a MicroPython environment such as Thonny IDE, the output will be:

    0 1 2 3 4

    This is because the loop executes five times, with the value of i being printed on each iteration.

  • Conditional Statements in MicroPython on Raspberry Pi Pico

    Conditional statements in MicroPython on Raspberry Pi Pico are used to make decisions based on certain conditions. They allow us to execute a block of code only if a certain condition is true, or to execute a different block of code if the condition is false.

    In MicroPython, we use the if, elif, and else keywords to create conditional statements. The general syntax for an if statement is:

    if condition:
        # Code to execute if condition is True
    

    If the condition is true, then the code inside the block is executed. If the condition is false, then the code inside the block is skipped.

    Here’s an example of an if statement:

    temperature = 25
    
    if temperature > 30:
        print("It's hot outside!")
    

    In this example, the condition temperature > 30 is false, so the code inside the block is not executed.

    We can also use the else keyword to specify what code should be executed if the condition is false:

    temperature = 25
    
    if temperature > 30:
        print("It's hot outside!")
    else:
        print("It's not that hot outside.")
    

    In this case, since the condition is false, the code inside the else block is executed, and the output would be “It’s not that hot outside.”

    We can also use the elif keyword to check multiple conditions:

    temperature = 25
    
    if temperature > 30:
        print("It's hot outside!")
    elif temperature > 20:
        print("It's warm outside.")
    else:
        print("It's not that hot outside.")
    

    In this example, the first condition is false, so the elif condition is checked. Since temperature > 20 is true, the code inside the elif block is executed, and the output would be “It’s warm outside.”

    Conditional statements can also be nested inside each other, to create more complex logic. For example:

    x = 5
    y = 10
    
    if x > 0:
        if y > 0:
            print("Both x and y are positive.")
        else:
            print("x is positive but y is not.")
    else:
        if y > 0:
            print("y is positive but x is not.")
        else:
            print("Both x and y are negative.")
    

    In this example, the output would be “Both x and y are positive.” since both x and y are greater than 0.

    elif statements can be nested in Python and MicroPython on Raspberry Pi Pico. You can use them to create more complex conditions that depend on multiple variables or factors.

    Here’s an example of nested elif statements in MicroPython on Raspberry Pi Pico:

    x = 5
    y = 10
    
    if x > y:
        print("x is greater than y")
    elif x < y:
        print("x is less than y")
        if x < 0:
            print("x is negative")
        elif x == 0:
            print("x is zero")
        else:
            print("x is positive")
    else:
        print("x is equal to y")

    In this example, if x is less than y, the program checks whether x is negative, zero, or positive using nested elif statements. If x is greater than y, the program prints a message saying so. And if x is equal to y, the program prints a message saying that as well.

    Note that when you nest elif statements, you must make sure that the indentation is correct to avoid syntax errors.

  • Variables and Data Types in MicroPython on Raspberry Pi Pico

    Variables and data types are fundamental concepts in programming. In MicroPython, just like in any programming language, variables are used to store data values and data types define the kind of data that can be stored.

    In this tutorial, we will explore variables and data types in MicroPython on Raspberry Pi Pico.

    Variables in MicroPython

    Variables in MicroPython are used to store data values such as numbers, strings, and boolean values. A variable is simply a named reference to a value.

    To create a variable, you simply assign a value to a name using the equals sign (=). For example:

    x = 5

    In this case, the variable x is assigned the value of 5.

    You can also assign values to multiple variables at once, like this:

    x, y, z = 5, "Hello", True
    

    This assigns the value of 5 to the variable x, the string “Hello” to the variable y, and the boolean value True to the variable z.

    Further Explanation

    x, y, z = 5, “Hello”, True is a way of assigning values to multiple variables at once in Python. In this case, the values 5, “Hello”, and True are assigned to the variables x, y, and z respectively.

    This syntax is known as “tuple unpacking”. The values on the right-hand side of the equals sign are packed into a tuple, which is then unpacked and assigned to the variables on the left-hand side.

    Essentially, it’s the same as writing:

    my_tuple = (5, "Hello", True)
    x = my_tuple[0]
    y = my_tuple[1]
    z = my_tuple[2]

    But using tuple unpacking is a more concise and readable way to assign values to multiple variables at once.

    Data Types in MicroPython

    MicroPython has several built-in data types that define the kind of data that can be stored in a variable. These include:

    • Integer: whole numbers, such as 5 or -3.
    • Float: decimal numbers, such as 3.14 or -2.5.
    • String: a sequence of characters, such as “Hello” or “123”.
    • Boolean: a value that is either True or False.
    • List: a collection of values, such as [1, 2, 3] or [“apple”, “banana”, “orange”].
    • Tuple: a collection of values, like a list, but cannot be modified once created, such as (1, 2, 3) or (“apple”, “banana”, “orange”).
    • Dictionary: a collection of key-value pairs, such as {“name”: “John”, “age”: 30}.

    To determine the data type of a variable, you can use the type() function, like this:

    This will output <class ‘int’>, indicating that x is an integer.

    x = 5
    print(type(x))  # Output: <class 'int'>
    
  • How to Read internal temperature sensor of Raspberry Pi Pico using Thonny IDE

    The internal temperature sensor of RP2040 is read using micropython. The Thonny IDE is used in Windows environment.

    The temperature sensor is connected to Channel number 4 of the ADC.

    But since this is a rather small implementation using Thonny IDE, it does most of the interfacing related code in the background.

    Code

    import machine
    import time
    
    """
    Function Name: Read internal temperature sensor
    Description: This function reads the internal temperature sensor of RP2040 chip.
                 The temperature sensor measures the Vbe voltage of a biased bipolar diode,
                 connected to the fifth ADC channel (AINSEL=4).
    """
    def read_internal_temperature_sensor():
        tsi = machine.ADC(machine.ADC.CORE_TEMP)
        temp = tsi.read_u16() * (3.3 / (65535))
        temp = 27 - (temp - 0.706)/0.001721
        return temp
    
    while True:
        #reads the temprature and prints it
        print("Temperature: ", read_internal_temperature_sensor())
        #Create a dealy of 1 second
        time.sleep(1)
    
  • How to setup Raspberry Pi Pico using Thonny IDE on windows and Blink onboard LED

    First you have to install micropython on your raspberry pi pico board.
    Follow the steps shown in the video.

    To blink the onboard LED you can follow these steps:

    1. Connect your Raspberry Pi Pico to your Windows computer using a micro USB cable.
    2. Open Thonny IDE on your Windows computer.
    3. Click on the “File” menu and select “New”.
    4. In the new window, enter the following code:
    import machine
    import time
    
    led_onboard = machine.Pin(25, machine.Pin.OUT)
    
    while True:
        led_onboard.toggle()
        time.sleep(1)
    1. Save the file with a meaningful name and the “.py” extension.
    2. Click on the “Run” menu and select “Run current script” or press the “F5” key.
    3. Thonny IDE will run the code and the onboard LED of Raspberry Pi Pico will start blinking at a frequency of 1 second.

    That’s it! You have successfully blinked the onboard LED of Raspberry Pi Pico using Thonny IDE on Windows.

  • Diodes

    • Diodes are electronic devices that conduct in one direction. Ideally, they have to block the conduction of current in the reverse direction, but in reality, there is always a small leakage current present.
    • Due to the presence of impurities in the diode, it gets hot when a large amount of current is passed through.
    • There are diodes for various applications which focus on a special property of the diode.
      • For example:
        • Zener Diode – Works in reverse bias condition. Provide excellent voltage regulation.
        • Schottky Diode – Has low forward voltage drop and high switching speed. Suitable for high-frequency applications and power supply circuits.
        • Silicon Controlled Rectifier (SCR) – Can handle high current and voltage levels. Used for power switching and motor control applications.
        • Light Emitting Diode (LED) – Emits light when forward biased. Used for lighting and display applications.
        • Tunnel Diode – Exhibits negative resistance. Used in microwave oscillators, amplifiers, and detectors.
        • Avalanche Diode – Can withstand high reverse voltage and exhibits avalanche breakdown. Used for overvoltage protection and voltage regulation.
        • Photodiode – Generates a current when exposed to light. Used in optical communication and sensing applications.
        • These are just a few examples, and there are many more types of diodes available for various applications.

    The following properties should be looked at in a datasheet. There may be additional details but these are the minimum.

    • VF is the voltage drop across the diode when it is conducting current in the forward direction. For example, a silicon diode may have a VF of around 0.7V.
    • IF is the maximum current that the diode can handle without being damaged. For example, a diode rated for 1A can handle a maximum current of 1A flowing through it.
    • VR is the maximum reverse voltage that the diode can withstand before breakdown. For example, a diode with a VR of 100V can withstand a reverse voltage of up to 100V before it starts conducting in the reverse direction.
    • PD is the maximum power that the diode can safely dissipate without getting damaged. For example, a diode with a PD of 500mW can safely dissipate up to 500mW of power without getting damaged.
    • Tj is the maximum temperature that the junction of the diode can reach without getting damaged. For example, a diode with a Tj of 150°C can safely operate at a maximum temperature of 150°C.
    • trr is the time taken by the diode to switch from forward conduction to reverse blocking mode. For example, a diode with a trr of 50ns will take 50ns to switch from forward conduction to reverse blocking mode.
    • The package type and dimensions specify the physical size and shape of the diode and are usually given in the mechanical drawing section of the datasheet. For example, a diode may be packaged in a through-hole or surface-mount package with specific dimensions.

    Electronic Diodes and Their Part Numbers

    Rectifier Diodes

    • Small Signal Diode: 1N4148, 1N914
    • Schottky Diode: BAT54, BAT85
    • Silicon Controlled Rectifier: TYN616, C106D
    • PIN Diode: HP5082-2810, HSMP-386L

    Zener Diodes

    • Zener Diode: 1N4728A, 1N5349B

    LED and Laser Diodes

    • Light Emitting Diode (LED): 5mm Red LED, 3mm Green LED
    • Laser Diode: 650nm Red Laser, 405nm Blue Laser

    Special Function Diodes

    • Tunnel Diode: 1N3716, NTT406AB
    • Varactor Diode: BB112, BB204
    • Transient Voltage Suppression Diode: P6KE36A, 1.5KE200A
    • Avalanche Diode: BZX84C5V6, P6KE100CA

    Photodiodes

    • PIN Photodiodes: BPW34, SFH205F
    • Avalanche Photodiodes: S8664, C30932EH
    • Schottky Photodiodes: 1N5711, HSMS-2855-BLKG
    • MSM Photodiodes: YT201M, YT202M
    • InGaAs Photodiodes: G9933, G8941

    Power Diodes

    • General Purpose Power Diodes: 1N4007, 1N5399
    • Fast Recovery Power Diodes: UF4007, FR107
    • Schottky Barrier Diodes: SB560, SB5100
    • Ultrafast Recovery Power Diodes: UF5404, UF5408
    • Super Barrier Diodes: SB540, SB570
    • Avalanche Diodes: MUR1100E, 1N4937GP
    • TVS Diodes (Transient Voltage Suppressor): P6KE15CA, 1.5KE400A
  • What does sticky do in tkinter

    In Tkinter, the sticky option is used to specify how a widget should expand to fill the space allotted to it within its container widget.

    The sticky option is used when placing a widget using the grid geometry manager. When a widget is placed in a cell of the grid, it can be set to “stick” to one or more sides of the cell. The sticky option takes one or more of the following values:

    • N: stick to the top edge of the cell
    • S: stick to the bottom edge of the cell
    • E: stick to the right edge of the cell
    • W: stick to the left edge of the cell
    • NW: stick to the top-left corner of the cell
    • NE: stick to the top-right corner of the cell
    • SW: stick to the bottom-left corner of the cell
    • SE: stick to the bottom-right corner of the cell

    For example, if you want a widget to fill the entire width of a cell and stick to the top edge of the cell, you can use:

    widget.grid(row=0, column=0, columnspan=2, sticky='W' + 'E' + 'N')

    This will place the widget in the first row, first column of the grid, and span two columns. The sticky option is set to 'W' + 'E' + 'N', which means the widget will stick to the left, right, and top edges of the cell, but not the bottom edge. As a result, the widget will expand horizontally to fill the width of the cell, but not vertically.

    Example

    import tkinter as tk
    
    root = tk.Tk()
    
    # Create a label widget and place it in the first row, first column of the grid
    label = tk.Label(root, text="Hello, world!")
    label.grid(row=0, column=0)
    
    # Create a button widget and place it in the second row, first column of the grid
    button = tk.Button(root, text="Click me!")
    button.grid(row=1, column=0)
    
    # Create an entry widget and place it in the second row, second column of the grid
    entry = tk.Entry(root)
    entry.grid(row=1, column=1, sticky='W')
    
    # Create a text widget and place it in the third row, first column of the grid
    text = tk.Text(root)
    text.grid(row=2, column=0, columnspan=2, sticky='W'+'E'+'N'+'S')
    
    branding_label = tk.Label(root, text="Powered by exasub.com")
    branding_label.grid(row=3, column=0, columnspan=2, padx=10, pady=10, sticky='E')
    
    root.mainloop()
    

    In this example, we create a label widget, a button widget, an entry widget, and a text widget, and place them in a grid using the grid geometry manager.

    The label widget is placed in the first row, first column of the grid, with no sticky option specified, so it will not expand to fill the cell.

    The button widget is placed in the second row, first column of the grid, with no sticky option specified, so it will not expand to fill the cell.

    The entry widget is placed in the second row, second column of the grid, with the sticky option set to ‘W’, so it will stick to the left edge of the cell and not expand to fill the cell.

    The text widget is placed in the third row, first column of the grid, with the sticky option set to ‘W’+’E’+’N’+’S’, so it will stick to all four edges of the cell and expand to fill the entire cell.

  • How to blink onboard LED on Raspberry Pi Pico W using Thonny IDE in Windows

    The raspberry pi pico w has a LED on it.
    This LED is not connected to the GPIO pins of RP2040 microcontroller directly.

    As you can see in the image of the pinout taken from the official datasheet.
    The onboard LED is connected to a pin ‘WL_GPIO0’.
    WL_GPIO0 is an internal pin.

    There are different ways to program the pico W.
    The easiest method is to install thonny IDE. And install micropython on the pico w.

    Download Thonny IDE

    After you have installed thonny. Now connect you raspberry pi pico w board to the computer USB port while holding the onboard BOOTSEL button. Then follow the steps shown in the following images.

    After you have done the above steps. You now have to install a MicroPython library.

    picozero is a MicroPython library which has functions for Wifi and other RP2040 chip.

    To complete the projects in this path, you need to install the picozero library as a Thonny package.

    In Thonny, choose Tools > Manage packages.

    Code

    import machine
    import time
    
    # create a Pin object to control the LED on pin 'WL_GPIO0'
    led_pin = machine.Pin('WL_GPIO0', machine.Pin.OUT)
    
    # enter an infinite loop
    while True:
        # set the LED pin to a high (on) state
        led_pin.value(1)
        # pause the program for one second
        time.sleep(1)
        # set the LED pin to a low (off) state
        led_pin.value(0)
        # pause the program for one second
        time.sleep(1)
    

    In this program, we first import the machine module and the time module. The machine module provides access to hardware-level features on the Raspberry Pi Pico, while the time module provides functions for time-related operations.

    Next, we create a Pin object called led_pin to control the LED connected to the pin labeled ‘WL_GPIO0’. The machine.Pin() function is used to create the led_pin object, with the first argument specifying the pin label and the second argument specifying that the pin is an output pin, i.e. we can set its state to high or low.

    Then, we enter an infinite loop using the while True: statement. Within the loop, we use the value() method of the led_pin object to set the state of the LED pin to high (on) or low (off), with a one second delay between each state change using the time.sleep() function.

    Comments are added to explain each line of code and make it easier to understand the purpose and function of the program.