• How to use GPIO of Raspberry Pi Pico as Output Pins

    One of the most important features of the Raspberry Pi Pico is its General-Purpose Input/Output (GPIO) pins. These pins can be used to control external devices, such as LEDs, motors, and relays.

    The Raspberry Pi Pico has 26 GPIO pins, numbered from GP0 to GP25.
    Each pin can be individually programmed to perform a specific task.

    Steps to Use GPIO as Output Pins

    To use the GPIO pins of Raspberry Pi Pico as output pins, follow these steps:

    Step 1: Set up your Raspberry Pi Pico board and connect it to your computer via USB.

    You can make the KiCad project like following.
    Connect a LED via a 220 ohm resistor to the GP4 pins.

    You can download and use the symbol and footprint from link below

    Raspberry Pi Pico Symbol in KiCad 7 Project Library

    To calculate the value of resistor you can use the Ohm’s Law Calculator
    Use the following values
    V (voltage): 3.3
    A (Current) : 0.015
    when you press calculate it will give you a resistance value of 220 ohm.

    Remember never exceed the current value of 0.015A or 15mA for small leds as higher current may damage the component.

    Schematic Diagram Showing LED connected to GP4 Pin via a 220 ohm resistor.

    Step 2: Open your preferred code editor and create a new Python script.

    Step 3: Import the required libraries by adding the following lines of code at the beginning of your script:

    import machine
    import utime

    The “machine” library provides access to the GPIO pins of Raspberry Pi Pico, and the “utime” library allows us to add delays in our code.

    Step 4: Define the pin number you want to use as an output pin. For example, if you want to use GP5 as an output pin, add the following line of code:

    led_pin = machine.Pin(4, machine.Pin.OUT)

    Here, we are using the “machine.Pin” class to define the pin number (4) as an output pin.

    Step 5: Turn on the LED by setting the output value of the pin to 1. Add the following line of code:

    led_pin.value(1)

    This will set the output value of the GP4 pin to 1, which will turn on the LED connected to it.

    Step 6: Add a delay in your code to keep the LED on for a specific time. For example, if you want to keep the LED on for 2 seconds, add the following line of code:

    utime.sleep(2)

    This will add a 2-second delay in your code.

    Step 7: Turn off the LED by setting the output value of the pin to 0. Add the following line of code:

    led_pin.value(0)

    This will set the output value of the GP4 pin to 0, which will turn off the LED connected to it.

    Step 8: Save your code and run it on your Raspberry Pi Pico board. You should see the LED turn on for 2 seconds and then turn off.

    Complete Code

    import machine
    import utime
    
    led_pin = machine.Pin(4, machine.Pin.OUT)
    
    led_pin.value(1)
    
    utime.sleep(2)
    
    led_pin.value(0)
    

    Example Code to try

    import machine
    import time
    
    led_pin = machine.Pin(4, machine.Pin.OUT)
    
    led_pin.value(1)  # turn on the LED
    time.sleep(1)     # wait for a second
    led_pin.value(0)  # turn off the LED
    time.sleep(1)     # wait for a second
    
    for i in range(10):
        led_pin.value(1)  # turn on the LED
        time.sleep(0.5)   # wait for half a second
        led_pin.value(0)  # turn off the LED
        time.sleep(0.5)   # wait for half a second
    
  • Raspberry Pi Pico Symbol in KiCad 7 Project Library

    This project has all the files necessary to make a project using it.

    In this project i have included a symbol library and a footprint library. It is a custom library. You can use this in another project by adding it into the project library list.

    This project is made using the KiCad 7.

    Symbol library name : RP2040_parts.kicad_sym

    Footprint library name: Library.pretty

    This project also has the 3d STEP file in it.

  • Handling errors with strings in MicroPython on Raspberry Pi Pico

    When working with strings in MicroPython on Raspberry Pi Pico, it is important to handle errors that may occur during string operations. Errors can occur for a variety of reasons, such as invalid input or incorrect syntax. Fortunately, MicroPython provides several built-in mechanisms for handling errors with strings.

    One of the most common errors that can occur with strings is a ValueError due to incorrect formatting. For example, if you try to convert a string to a numeric type and the string is not a valid number, a ValueError will be raised. To handle this error, you can use a tryexcept block:

    string = "abc123"
    try:
        num = int(string)
        print(num)
    except ValueError:
        print("Invalid input, cannot convert to int.")

    In this example, the int() function attempts to convert the string "abc123" to an integer. However, since "abc123" is not a valid integer, a ValueError is raised. The tryexcept block catches the error and prints a helpful message.

    Another common error that can occur with strings is an IndexError due to attempting to access an element that does not exist in a string. For example, if you try to access the 10th character of a string that only has 5 characters, an IndexError will be raised. To handle this error, you can use a similar tryexcept block:

    string = "hello"
    try:
        char = string[10]
        print(char)
    except IndexError:
        print("Index out of range, cannot access character.")

    In this example, we attempt to access the 10th character of the string "hello", which does not exist. An IndexError is raised, and the tryexcept block catches the error and prints a helpful message.

    It is also possible to raise your own custom errors when working with strings. For example, you may want to raise an error if a string does not meet certain criteria. To do this, you can use the raise statement:

    def process_string(string):
        if len(string) < 5:
            raise ValueError("String must be at least 5 characters long.")
        # do something with the string

    In this example, the process_string() function raises a ValueError if the input string is less than 5 characters long. This allows the function to provide useful feedback to the user if the input is invalid.

    In summary, handling errors with strings in MicroPython on Raspberry Pi Pico involves using tryexcept blocks to catch built-in errors, and raising your own custom errors when necessary. By using these mechanisms, you can ensure that your code is robust and handles unexpected situations gracefully.

  • Using strings with input/output operations on Raspberry Pi Pico

    Using strings with input/output operations is a common task when working with MicroPython on Raspberry Pi Pico. In this post, we will explore how to use strings with input/output operations, including reading and writing strings to files and the console.

    Reading strings from the console
    The easiest way to read strings from the console is to use the built-in function input(). This function reads a line of text from the console and returns it as a string.

    name = input("Enter your name: ")
    print("Hello,", name)

    This code prompts the user to enter their name and then greets them by name.

    Writing strings to the console
    To output a string to the console, we can use the built-in function print(). This function takes one or more arguments, converts them to strings, and outputs them to the console.

    print("Hello, world!")

    This code outputs the string “Hello, world!” to the console.

    Writing strings to files
    To write a string to a file, we need to open the file for writing and then use the write() method to write the string to the file.

    with open("output.txt", "w") as f:
        f.write("Hello, world!")

    This code creates a new file called “output.txt” in the current directory and writes the string “Hello, world!” to the file.

    Reading strings from files
    To read a string from a file, we need to open the file for reading and then use the read() method to read the string from the file.

    with open("input.txt", "r") as f:
        contents = f.read()
        print(contents)

    This code reads the contents of a file called “input.txt” in the current directory and outputs the contents to the console.

  • String comparison in MicroPython on Raspberry Pi Pico

    String comparison is a common task in programming. In MicroPython, you can compare strings using the same comparison operators as you would in Python. This includes the “==” operator for equality, “!=” for inequality, “>” for greater than, “<” for less than, “>=” for greater than or equal to, and “<=” for less than or equal to.

    It is important to note that when comparing strings, MicroPython compares the underlying Unicode code points of each character in the strings. This means that string comparison is case-sensitive, and that different characters with the same visual representation (such as accented characters or ligatures) may have different code points and therefore be considered different characters.

    Here are some examples of string comparison in MicroPython:

    # Equality
    string1 = "Hello, world!"
    string2 = "Hello, world!"
    if string1 == string2:
        print("The strings are equal.")
    else:
        print("The strings are not equal.")
    
    # Inequality
    string1 = "Hello, world!"
    string2 = "Goodbye, world!"
    if string1 != string2:
        print("The strings are not equal.")
    else:
        print("The strings are equal.")
    
    # Greater than
    string1 = "apple"
    string2 = "banana"
    if string1 > string2:
        print("The first string is greater than the second.")
    else:
        print("The first string is not greater than the second.")
    
    # Less than
    string1 = "apple"
    string2 = "banana"
    if string1 < string2:
        print("The first string is less than the second.")
    else:
        print("The first string is not less than the second.")

    In the above examples, the output would be:

    The strings are equal.
    The strings are not equal.
    The first string is not greater than the second.
    The first string is less than the second.

    As mentioned earlier, string comparison in MicroPython is case-sensitive. This means that the strings “hello” and “Hello” would be considered different. If you want to perform case-insensitive string comparison, you can convert both strings to lowercase (or uppercase) before comparing them. Here is an example:

    string1 = "Hello"
    string2 = "hello"
    if string1.lower() == string2.lower():
        print("The strings are equal, ignoring case.")
    else:
        print("The strings are not equal, even ignoring case.")

    In this example, the output would be “The strings are equal, ignoring case.”

    Overall, string comparison in MicroPython is straightforward and follows the same principles as in Python. It is important to keep in mind the case-sensitivity of string comparison and to be aware of the differences in code points between different characters.

  • Working with Unicode and ASCII in MicroPython on Raspberry Pi Pico

    One of the challenges of working with MicroPython on Raspberry Pi Pico is handling Unicode and ASCII characters, which are used to represent text in different languages and scripts. In this blog post, we will explore how to work with Unicode and ASCII characters in MicroPython on Raspberry Pi Pico.

    By understanding how to work with Unicode and ASCII characters in MicroPython, you can write programs that handle text from different languages and scripts, and interact with other systems that use ASCII encoding.

    Unicode and ASCII

    Unicode is a standard for encoding characters and text in a way that is compatible with all writing systems and languages. It includes more than 100,000 characters from scripts around the world, including Latin, Cyrillic, Chinese, Arabic, and more. Unicode characters are represented using a numerical code point that uniquely identifies each character.

    ASCII (American Standard Code for Information Interchange) is a subset of Unicode that includes 128 characters, including the English alphabet, digits, and some symbols. ASCII was originally developed for telecommunication and is still widely used in computing today.

    Working with Unicode and ASCII in MicroPython

    In MicroPython, text strings are represented using Unicode. This means that you can work with characters from any script or language, including those that are not included in ASCII. However, you may encounter situations where you need to convert between Unicode and ASCII, or work with ASCII characters directly.

    To convert a Unicode string to ASCII in MicroPython, you can use the encode() method. This method takes a string and an encoding type as arguments and returns a bytes object that represents the string in the specified encoding. For example, to convert a Unicode string to ASCII, you can use the following code:

    unicode_string = "Hello, world!"
    ascii_bytes = unicode_string.encode("ascii")

    To convert an ASCII string to Unicode in MicroPython, you can use the decode() method. This method takes a bytes object and an encoding type as arguments and returns a string that represents the bytes in the specified encoding. For example, to convert an ASCII string to Unicode, you can use the following code:

    ascii_bytes = b"Hello, world!"
    unicode_string = ascii_bytes.decode("ascii")

    In some cases, you may need to work with ASCII characters directly, even if your text string is encoded in Unicode. To do this, you can use the ord() function, which takes a character as an argument and returns its ASCII code point. For example, to get the ASCII code point for the letter “A”, you can use the following code:

    ascii_code_point = ord("A")

    Similarly, to convert an ASCII code point to a character, you can use the chr() function, which takes an ASCII code point as an argument and returns the corresponding character. For example, to get the character for the ASCII code point 65 (which represents the letter “A”), you can use the following code:

    character = chr(65)
  • Using regular expressions with strings in MicroPython on Raspberry Pi Pico

    MicroPython is a lightweight implementation of the Python programming language that is optimized to run on microcontrollers, including the popular Raspberry Pi Pico. With MicroPython, you can use regular expressions to manipulate strings just like in regular Python. In this tutorial, we will explore how to use regular expressions with strings in MicroPython on Raspberry Pi Pico.

    What are regular expressions?

    Regular expressions are a powerful way to manipulate strings in Python. They are a special sequence of characters that define a search pattern, which can then be used to find and replace substrings in a larger string. Regular expressions are a standard feature of the Python programming language and can be used in MicroPython as well.

    Using regular expressions in MicroPython

    The ure module in MicroPython provides a simple regular expression implementation. It supports a subset of the regular expressions syntax used in the re module of regular Python. Some of the supported operators and special sequences include:

    • . – Matches any character
    • [] – Matches a set of characters
    • ^ – Matches the start of the string
    • $ – Matches the end of the string
    • ? – Matches zero or one of the previous sub-pattern
    • * – Matches zero or more of the previous sub-pattern
    • + – Matches one or more of the previous sub-pattern
    • () – Groups sub-patterns together
    • \d – Matches digits
    • \D – Matches non-digits
    • \s – Matches whitespace characters
    • \S – Matches non-whitespace characters
    • \w – Matches “word” characters (letters, digits, and underscores)
    • \W – Matches non-“word” characters

    Some more advanced assertions and special character escapes, such as \b and \B, are not supported in MicroPython.

    https://docs.micropython.org/en/v1.14/library/ure.html

    Example usage

    Let’s say we want to extract an email address from a string in MicroPython. We can use regular expressions to define a pattern that matches email addresses. Here’s an example:

    import ure
    
    # Define a regular expression pattern to match email addresses
    email_pattern = r'\w+@\w+\.\w+'
    
    # The string to search for an email address
    string_to_search = "fghgf ghfhfg abhay@example.com .vfgh xyhfghfgz_fgdhbabu@nomghjghjail.com hjkjhkjghjg fjgjgh"
    
    # Search for the pattern in the string
    result = ure.search(email_pattern, string_to_search)
    
    # Check if a match is found
    if result:
        print("Email found:", result.group(0))
    else:
        print("No email found.")
    

    This code defines a regular expression pattern for an email address and searches for it in a string. If the pattern is found, the email address is printed to the console. If not, a message indicating that no email address was found is printed.

    Note that in MicroPython, the ure.search() method returns a match object if the pattern is found, rather than a match object or None as in regular Python.

    Conclusion

    Regular expressions are a powerful tool for working with strings in Python and can be used in MicroPython as well. The ure module in MicroPython provides a simple regular expression implementation that supports a subset of the syntax used in regular Python. With regular expressions, you can search for and manipulate patterns in strings with ease.

  • Finding and replacing substrings in MicroPython on Raspberry Pi Pico

    In programming, finding and replacing substrings is a common task when working with text data. MicroPython on Raspberry Pi Pico provides a variety of built-in functions that can be used to search for and replace substrings within a string. In this blog post, we will explore how to use these functions to find and replace substrings in MicroPython on Raspberry Pi Pico.

    Finding Substrings

    To find a substring within a string in MicroPython, we can use the find() method. The find() method searches for the first occurrence of a substring within a string and returns the index where the substring starts. If the substring is not found, the method returns -1. Here’s an example:

    string = "Hello, World!"
    index = string.find("World")
    print(index)  # Output: 7

    In this example, we use the find() method to search for the substring “World” within the string “Hello, World!”. The method returns the index 7, which is the starting index of the substring within the string.

    Replacing Substrings

    To replace a substring within a string in MicroPython, we can use the replace() method. The replace() method replaces all occurrences of a substring within a string with a new substring. Here’s an example:

    string = "Hello, World!"
    new_string = string.replace("World", "Python")
    print(new_string)  # Output: Hello, Python!

    In this example, we use the replace() method to replace all occurrences of the substring “World” within the string “Hello, World!” with the new substring “Python”. The method returns the new string “Hello, Python!”.

    If we only want to replace a specific occurrence of a substring within a string, we can use the replace() method with an additional argument that specifies the number of occurrences to replace. Here’s an example:

    string = "Hello, World! Hello, World!"
    new_string = string.replace("World", "Python", 1)
    print(new_string)  # Output: Hello, Python! Hello, World!

    In this example, we use the replace() method with an additional argument of 1 to replace only the first occurrence of the substring “World” within the string “Hello, World! Hello, World!” with the new substring “Python”. The method returns the new string “Hello, Python! Hello, World!”.

    Conclusion

    In conclusion, finding and replacing substrings in MicroPython on Raspberry Pi Pico is a straightforward process using the built-in functions find() and replace(). These functions can be used to manipulate strings and perform a variety of text processing tasks in MicroPython programs.

  • Reversing strings in MicroPython on Raspberry Pi Pico

    Reversing a string is a common task in programming and can be useful in various applications. In this blog post, we will explore how to reverse strings in MicroPython on Raspberry Pi Pico and provide some examples.

    In MicroPython, reversing a string is done using string slicing. The slice notation allows you to specify the starting index, ending index, and the step size of the slice. By using a negative step size, you can reverse the string. Here is an example:

    string = "Hello, world!"
    reversed_string = string[::-1]
    print(reversed_string)

    The output of this code will be:

    !dlrow ,olleH

    In the code above, [::-1] specifies a slice that starts from the end of the string, goes to the beginning of the string, and steps backwards by 1 character at a time.

    You can also create a function to reverse a string in MicroPython. Here is an example of such a function:

    def reverse_string(string):
        return string[::-1]
    
    string = "Hello, world!"
    reversed_string = reverse_string(string)
    print(reversed_string)

    The output of this code will be the same as the previous example.

    Another way to reverse a string in MicroPython is to use a loop. Here is an example:

    string = "Hello, world!"
    reversed_string = ""
    
    for i in range(len(string)-1, -1, -1):
        reversed_string += string[i]
    
    print(reversed_string)

    The output of this code will also be:

    !dlrow ,olleH

    In the code above, the loop starts from the last character of the string and iterates backwards until the first character. The += operator is used to concatenate the characters in reverse order.

    In conclusion, reversing a string in MicroPython on Raspberry Pi Pico is a straightforward task that can be done using string slicing or a loop. Knowing how to reverse strings can be useful in various applications, such as data processing and cryptography.

  • Formatting strings in MicroPython on Raspberry Pi Pico

    String formatting is an essential part of programming in any language, including MicroPython on Raspberry Pi Pico. It allows you to insert variables or values into a string and create more complex and dynamic output. In this blog post, we will explore the different methods for formatting strings in MicroPython.

    1. Using the % operator:
      The most common method of string formatting in MicroPython is by using the % operator. It allows you to substitute variables or values into a string using placeholders.

    For example:

    name = "John"
    age = 25
    print("My name is %s and I am %d years old." % (name, age))

    Output: My name is John and I am 25 years old.

    In the example above, %s is a placeholder for the string variable name, and %d is a placeholder for the integer variable age. The variables are substituted in the string using the % operator.

    1. Using the format() method:
      Another method for formatting strings in MicroPython is by using the format() method. It allows you to substitute variables or values into a string using curly braces {} as placeholders.

    For example:

    name = "John"
    age = 25
    print("My name is {} and I am {} years old.".format(name, age))

    Output: My name is John and I am 25 years old.

    In the example above, {} is a placeholder for the variables name and age. The variables are substituted in the string using the format() method.

    1. Using f-strings:
      F-strings are a new and more convenient way of formatting strings in MicroPython. They were introduced in Python 3.6 and are available in MicroPython on Raspberry Pi Pico. F-strings allow you to substitute variables or values directly into a string using curly braces {} as placeholders, preceded by the letter f.

    For example:

    name = "John"
    age = 25
    print(f"My name is {name} and I am {age} years old.")

    Output: My name is John and I am 25 years old.

    In the example above, {} is a placeholder for the variables name and age. The variables are substituted directly in the string using an f-string.

    Conclusion:
    Formatting strings in MicroPython on Raspberry Pi Pico is an essential part of programming. The three methods discussed above – using the % operator, the format() method, and f-strings – allow you to create dynamic and complex output by substituting variables or values into a string. It’s important to choose the method that works best for your needs and coding style.