• Loop Control Statements in MicroPython on Raspberry Pi Pico

    Loop control statements are used to alter the normal flow of execution within loops. They can be used to skip iterations or terminate loops prematurely based on certain conditions. In MicroPython on Raspberry Pi Pico, there are three loop control statements: break, continue, and pass.

    1. Break statement:
      The break statement is used to terminate a loop prematurely. When a break statement is encountered within a loop, the loop is immediately exited and program execution continues with the statement immediately following the loop. The break statement can be used with both for and while loops.

    Here’s an example:

    for i in range(1, 11):
        if i == 5:
            break
        print(i)

    In this example, the loop will iterate over the values from 1 to 10. However, when i equals 5, the break statement is encountered and the loop is terminated prematurely. As a result, only the values from 1 to 4 will be printed.

    1. Continue statement:
      The continue statement is used to skip the current iteration of a loop and move on to the next iteration. When a continue statement is encountered within a loop, the remaining statements within the loop for that iteration are skipped and the loop moves on to the next iteration. The continue statement can be used with both for and while loops.

    Here’s an example:

    for i in range(1, 11):
        if i % 2 == 0:
            continue
        print(i)

    In this example, the loop will iterate over the values from 1 to 10. However, when i is even, the continue statement is encountered and the remaining statements for that iteration are skipped. As a result, only the odd values from 1 to 10 will be printed.

    1. Pass statement:
      The pass statement is used to do nothing. It can be used as a placeholder when a statement is required syntactically, but no action is needed. The pass statement is typically used when a block of code is not yet implemented but is required for the program to run without error.

    Here’s an example:

    for i in range(1, 11):
        pass

    In this example, the loop will iterate over the values from 1 to 10. However, the pass statement does nothing, so the loop will simply run through all iterations without doing anything. The pass statement can be used with both for and while loops.

    Loop control statements are a useful tool in programming, as they allow us to alter the normal flow of execution within loops based on certain conditions. The break statement can be used to terminate a loop prematurely, the continue statement can be used to skip the current iteration and move on to the next iteration, and the pass statement can be used as a placeholder when no action is needed.

    Sure, here is an example of how you can use continue, pass, and break statements in a loop:

    # Example of using loop control statements in MicroPython
    
    # Loop from 1 to 10
    for i in range(1, 11):
        # If i is even, skip to the next iteration
        if i % 2 == 0:
            continue
    
        # If i is 5, do nothing and continue to the next iteration
        if i == 5:
            pass
    
        # If i is greater than 8, break out of the loop
        if i > 8:
            break
    
        # Print the value of i
        print(i)

    In this example, the continue statement is used to skip over even numbers in the loop. The pass statement is used to do nothing and simply continue to the next iteration when the value of i is 5. Finally, the break statement is used to exit the loop when the value of i becomes greater than 8.

    When you run this code, you will see the following output:

    1
    3
    7

    As you can see, the even numbers (2, 4, 6, 8, and 10) are skipped over with the continue statement. The value of 5 does nothing with the pass statement, and the loop stops when the value of i reaches 9 because of the break statement.

  • Nested Loops in MicroPython on Raspberry Pi Pico

    Nested loops in MicroPython on Raspberry Pi Pico refer to the use of one loop inside another loop. The inner loop is executed multiple times for each iteration of the outer loop. This technique is useful when we want to perform repetitive tasks or calculations on a set of data.

    To create nested loops in MicroPython on Raspberry Pi Pico, we simply need to place one loop inside another loop. Here’s an example:

    for i in range(3):
        for j in range(2):
            print(i, j)

    In this example, we have an outer loop that iterates from 0 to 2, and an inner loop that iterates from 0 to 1. For each iteration of the outer loop, the inner loop is executed twice. The output of this code would be:

    0 0
    0 1
    1 0
    1 1
    2 0
    2 1

    We can also use nested loops to access and modify elements of a two-dimensional list or array. Here’s an example:

    matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    
    for row in matrix:
        for element in row:
            print(element)

    In this example, we have a two-dimensional list called matrix. The outer loop iterates over each row of the matrix, while the inner loop iterates over each element in the current row. The output of this code would be:

    1
    2
    3
    4
    5
    6
    7
    8
    9

    Nested loops can also be used to perform more complex calculations or operations.

  • 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