Posted on Leave a comment

Raspberry Pi Pico Internal Temperature Sensor Based Fan Speed Control using PID Algorithm with Anti-Windup Logic

This system uses the Raspberry pi pico development board which has an RP2040 microcontroller. The RP2040 microcontroller has an internal temperature sensor.

Using its internal temperature sensor I have devised a very simple setup that demonstrates the PID algorithm. Using PID Algorithm control technique I am controlling the fan speed by changing the PWM duty cycle.

Component required:

  1. Raspberry Pi Pico
  2. PC Fan (+12V)
  3. L298n Module
  4. +12V Power supply

Commonly the PC fan changes its speed by PWM signal, I am sending a PWM signal of frequency 29Khz. Most PC fans operate from 25Khz to 30Khz. PWM signal duty cycle can be from 30% to 100%. At duty cycle lower than 30% PC fan won’t start.

We will dive into the code and explain each step of the implementation.

Code Overview:
The code provided is written in MicroPython and utilizes the machine module for hardware interactions. Here’s an overview of the key components and functionalities:

  1. PWM Configuration: The code configures a GPIO pin for Pulse Width Modulation (PWM) and sets the frequency to 29 kHz. PWM is used to control the speed of the fan.
  2. Temperature Sensor Configuration: The internal temperature sensor is configured using the ADC (Analog-to-Digital Converter) module. The conversion factor is calculated to convert the raw ADC readings to temperature values.
  3. PID Algorithm Implementation: The PID algorithm is implemented using proportional (P), integral (I), and derivative (D) control constants. The target temperature is set, and the error between the target temperature and the measured temperature is calculated. The code calculates the proportional, integral, and derivative terms and combines them to obtain the PID value.
  4. Anti-Windup Logic: To prevent windup issues, an anti-windup logic is implemented. It limits the PID value within a valid range to avoid saturation or unstable behavior.
  5. Timer Interrupts: Timer objects are created to trigger callback functions at regular intervals. The 100 ms timer callback updates the PID value and adjusts the fan speed accordingly, while the 1-second timer callback prints relevant information for monitoring and debugging purposes.

Implementation Walkthrough:

  1. PWM and Temperature Sensor Configuration: The code starts by configuring the PWM pin and the internal temperature sensor.
  2. PID Constants and Variables: The proportional control constant (kp), minimum duty cycle value (min_duty_cycle), and target temperature (target_temp) are set. Variables for duty cycle, error, temperature, integral error (i_err), integral count (i_cnt), derivative count (d_cnt), previous error (prev_err), and PID value (PID) are initialized.
  3. Timer Interrupts: Timer objects are created and initialized to trigger the respective callback functions every 100 ms and 1 second.
  4. PID Calculation and Fan Control: In the timer callback function for 100 ms, the raw temperature is converted to a temperature value. The error, integral error, derivative count, proportional count, and PID value are calculated. The PID value is limited to a valid range and converted to an appropriate duty cycle value for the PWM. The duty cycle is applied to control the fan speed.
  5. Monitoring and Debugging: The timer callback function for 1 second prints relevant information such as the PID value, error, duty cycle, temperature, derivative count, integral count, and proportional count.
import machine
import utime

# Configure the GPIO pin for PWM
pwm_pin = machine.Pin(9)
pwm = machine.PWM(pwm_pin)

# Set the PWM frequency to 29 kHz
pwm.freq(29000)

# Configure the internal temperature sensor
sensor_temp = machine.ADC(machine.ADC.CORE_TEMP)
conversion_factor = 3.3 / 65535

# Set the proportional control constants
#target_temp = 25  # Set the desired target temperature
# Set the proportional control constants
#target_temp = 25.63997  # Set the desired target temperature
target_temp = 25.17182  # Set the desired target temperature
#target_temp = 24.70368
#target_temp = 24.23554
#target_temp = 23.76739
#target_temp = 23.29925
kp = (((2**16)-1) * -1)
min_duty_cycle = (((2**16)-1) * 0.3)  # Minimum duty cycle value to start the fan

duty_cycle = 0
error = 0
temperature = 0

# Initialize the timestamp for 1 second intervals
timestamp_1s = utime.time()
p_cnt = 0
i_err = 0
Ki = -200
i_cnt = 0

prev_err = 0
Kd = -2500
d_cnt = 0
PID = 0
# Timer interrupt callback function for 100 ms interval
def timer_callback_100ms(timer):
    global duty_cycle, error, temperature,i_err,i_cnt,prev_err,Kd,d_cnt,p_cnt,PID,Ki

    raw_temp = sensor_temp.read_u16() * conversion_factor
    temperature = (27 - (raw_temp - 0.706) / 0.001721)
    error = target_temp - temperature
    i_err += (error)
    i_cnt = int(i_err * Ki)
    d_cnt = ((error - prev_err) * Kd)/0.1
    p_cnt = error * kp
    PID = (p_cnt + d_cnt + i_cnt)
    if PID >= 65535:
        PID = 65535
    if PID <= 0 :
        PID = 0
    duty_cycle = int(PID)
    
    pwm.duty_u16(duty_cycle)
    '''
    if error >= 0:
        #duty_cycle = max((duty_cycle - int(error * kp)), 0)
        duty_cycle = int(max(( d_cnt + i_cnt + (1 * error * kp)), 0))
        if duty_cycle <= 0:
            duty_cycle = 0
        pwm.duty_u16(duty_cycle)
    elif error < 0:
        duty_cycle = int(min( d_cnt + i_cnt +  error * kp), 65535))
        
        #duty_cycle = min(max((duty_cycle + int(-1 * error * kp)), int(min_duty_cycle)), 65535)
        pwm.duty_u16(int(duty_cycle))
    '''
    prev_err = error

# Timer interrupt callback function for 1 second interval
def timer_callback_1s(timer):
    print(f"pid: {PID}\terror: {error}\tduty: {duty_cycle}\tTemp: {temperature}\td_cnt: {d_cnt}\ti_cnt: {i_cnt}\tp_cnt: {p_cnt}")

# Create timer objects
timer_100ms = machine.Timer()
timer_1s = machine.Timer()

# Configure the timer to trigger the 100 ms callback function every 100 milliseconds
timer_100ms.init(period=100, mode=machine.Timer.PERIODIC, callback=timer_callback_100ms)

# Configure the timer to trigger the 1 second callback function every 1 second
timer_1s.init(period=1000, mode=machine.Timer.PERIODIC, callback=timer_callback_1s)

# Main loop
while True:
    # Add any other desired non-blocking operations here
    
    # Sleep briefly to avoid excessive CPU usage
    utime.sleep(0.01)

Posted on Leave a comment

Wireless Plant Watering System using Raspberry Pi Pico W

Every morning my mom waters the plant. She has to water them every day and sometimes in summer, she must provide water twice a day.

In winter plant needs water when necessary.

Solution:

For the above problem, I developed this project using raspberry pi pico w.

Here is what it does:

  1. It connects to the WiFi router. The wifi router allocates a fixed IP address. For that, I created a new entry in the DHCP bindings of the router.
  2. When you visit the IP address 192.168.1.101
  3. It samples the soil moisture sensor through the ADC. And display an HTML page that shows the status of ADC and the onboard LED.
  4. The HTML page also has a button for turning on the pump.
    I have kept it manual.
  5. When the PUMP ON button is pressed the water pump is turned ON. The water pump is connected via the L298n module. Which is controlled by a PWM signal of 1Khz frequency. The duty cycle is slowly increased to 75%.
    There is a timeout of 10 Seconds. If the timeout is reached the water pump will be turned off.

Schematic Diagram

Schematic Diagram

Micropython Code

import network
import socket
import time
from time import sleep
from picozero import pico_temp_sensor, pico_led
import machine

ssid = 'Abhay'
password = 'AK26@#36'
'''
# Pin GP9 (physical pin 5) on PicoZero
GPIO_PIN = 9

# Set up the GPIO pin as an output
pin9 = machine.Pin(GPIO_PIN, machine.Pin.OUT)

# Turn off the GPIO pin
pin9.off()
'''
GPIO_PIN_9 = machine.Pin(9)
pwm9 = machine.PWM(GPIO_PIN_9)

    
def ADC():
    adc = machine.ADC(0)  # Initialize ADC on pin A0
    sensor_value = adc.read_u16()  # Read the analog value from the sensor
    # Add your code to process and display the sensor value as per your requirements
    #print(sensor_value)
    #time.sleep_ms(500)  # Delay between readings (adjust as needed)
    #sensor_value = 18756
    percentage = 100 - ((sensor_value / 65535) * 100)
    #print(f"sensor_value: {sensor_value} percentage: {percentage}")
    return sensor_value,percentage
    
    
def gen_pwm(duration, timeout):
    # Set PWM frequency
    pwm9.freq(1000)  # Set frequency to 1 kHz

    start_time = time.ticks_ms()  # Get the initial timestamp
    pump_started = False

    while time.ticks_diff(time.ticks_ms(), start_time) < timeout:
        # Check water level using ADC
        ADC_Read = ADC()
        water_level = ADC_Read[1]
        #adc.read()

        if not pump_started and water_level < 50:
            # Start the pump by gradually increasing the duty cycle
            for duty in range(0, 32767, 100):
                pwm9.duty_u16(duty)
                time.sleep_ms(duration)  # Adjust the delay as needed for smooth transition
                ADC_Read = ADC()
                water_level = ADC_Read[1]
                
                if water_level >=50 :
                    break
            pump_started = True

        if water_level >= 50 or pump_started and water_level <= 0:
            # Stop the pump by setting the duty cycle to 0
            pwm9.duty_u16(0)
            break

    # Stop the PWM signal
    pwm9.duty_u16(0)

def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        sleep(1)
    ip = wlan.ifconfig()[0]
    print(f'Connected on {ip}')
    return ip

def open_socket(ip):
    # Open a socket
    address = (ip, 80)
    connection = socket.socket()
    connection.bind(address)
    connection.listen(1)
    return connection

def webpage(temperature, state,user_value):
    #Template HTML
    ADC_Value = ADC()
    html = f"""
            <!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <form action="./lighton" style="display: flex; justify-content: center;">
        <input type="submit" value="Light on" style="font-size: 40px;" />
    </form>
    <form action="./lightoff" style="display: flex; justify-content: center;">
        <input type="submit" value="Light off" style="font-size: 40px;" />
    </form>
    <p style="font-size: 20px;">LED is {state}</p>
    <p style="font-size: 20px;">Temperature is {temperature}</p>
    <p style="font-size: 20px;">ADC Value is {ADC_Value[0]}</p>
    <p style="font-size: 20px;">ADC % is {ADC_Value[1]}</p>
    
    <form action="./pumpon" style="display: flex; justify-content: center;">
        <input type="submit" value="Pump on" style="font-size: 40px;" />
    </form>
    <form action="./pumpoff" style="display: flex; justify-content: center;">
        <input type="submit" value="Pump off" style="font-size: 40px;" />
    </form>
    
    <h1>Numeric Form</h1>
    <form method=POST action="/usrval">
        <label for="value">Enter a numeric value:</label><br>
        <input type="number" id="value" name="value" required><br><br>
        <input type="submit" value="Submit">
    </form>
    <p>User value: {user_value}</p>  <!-- Display the user-submitted value -->
</body>
</html>


            """
    return str(html)
def serve(connection):
    #Start a web server
    state = 'OFF'
    pico_led.off()
    temperature = 0
    user_value = None  # Variable to store the user-submitted value
    while True:
        client = connection.accept()[0]
        request = client.recv(1024)
        request = str(request)
        rqst1 = request.split()
        '''
        for x1 in rqst1:
            if(x1.find("usrval") != -1):
                print(rqst1)
                #print(x1)
        #print(rqstfind)
        '''
        try:
            
            for x1 in rqst1:
                if "value=" in x1:
                    user_value = x1.split("=")[2].strip("'")
                    print(user_value)
        except:
            pass
        
        try:
            request = request.split()[1]
        except IndexError:
            pass
        if request == '/lighton?':
            pico_led.on()
            state = 'ON'
        elif request =='/lightoff?':
            pico_led.off()
            state = 'OFF'
        elif request =='/pumpon?':
            #pin9.on()
            gen_pwm(10,10000)
            print("\n\n"+request)
            #state = 'OFF'
        elif request =='/pumpoff?':
            #pin9.off()
            print("Pump OFF")
        elif request == '/usrval':
          #  print("\n\n"+request)
            index = request.find('value=')
            
            if index != -1:
                end_index = request.find(' ', index)
                if end_index == -1:
                    end_index = len(request)
                user_value = request[index + len('value='):end_index]
                print(f"\n\nValue: \t {user_value}\n\n")
        temperature = pico_temp_sensor.temp
        html = webpage(temperature, state,user_value)
        client.send(html)
        client.close()

try:
    ip = connect()
    connection = open_socket(ip)
    serve(connection)
except KeyboardInterrupt:
    machine.reset()
Posted on Leave a comment

How to use button with Raspberry Pi Pico using micropython

The Pico has internal pull up /down circuits inside it.

I have made this simple circuit for demonstration.

Schematic showing LED connected to GP4 and a Button connected to GP22

Button could be connected in two ways.

  1. Internal Pull Up/Down
  2. External Pull UP/Down

In the schematic i connected a button to GP22 using a external pull up of resistor 10k. I also used a capacitor in parallel with the button to debounce the button externally.

Using a external pull-up resistor can also help to protect the GPIO pin from damage due to excessive current flow. Without a pull-up resistor, a short circuit or other electrical fault in the switch or button could potentially allow a large current to flow through the GPIO pin, damaging it or the microcontroller itself.

Sample Code

import machine

# Set up the button on GPIO22 with external pull-up resistor
button = machine.Pin(22, machine.Pin.IN, machine.Pin.PULL_UP)

# Set up the LED on GPIO4
led = machine.Pin(4, machine.Pin.OUT)

# Loop forever
while True:
    # Read the current button value
    curr_button = button.value()

    # If the button is pressed, turn on the LED
    if curr_button == 0:
        led.value(1)
    # Otherwise, turn off the LED
    else:
        led.value(0)

Posted on Leave a comment

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
Posted on Leave a comment

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.

Posted on Leave a comment

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.

Posted on Leave a comment

Splitting strings in MicroPython on Raspberry Pi Pico

Strings are an essential part of any programming language, and MicroPython on Raspberry Pi Pico is no exception. They can contain a sequence of characters and can be used for a variety of purposes, from storing user input to displaying information on the screen. One of the useful operations that can be performed on strings is splitting them into smaller pieces. In this blog post, we will explore how to split strings in MicroPython on Raspberry Pi Pico.

The split() method in MicroPython is used to split a string into a list of substrings based on a delimiter. A delimiter is a character that separates each substring in the original string. The syntax for the split() method is as follows:

string.split(delimiter, maxsplit)

where string is the original string, delimiter is the character used to separate the substrings, and maxsplit is the maximum number of splits to be performed.

Let’s take a look at an example:

string = "apple,banana,orange"
fruits = string.split(",")
print(fruits)

In this example, we define a string string that contains a list of fruits separated by commas. We then use the split() method to split the string into a list of substrings based on the comma delimiter. The resulting list fruits contains the substrings as individual elements:

['apple', 'banana', 'orange']

We can also specify the maximum number of splits to be performed. For example:

string = "apple,banana,orange"
fruits = string.split(",", 1)
print(fruits)

In this example, we specify a maximum of one split. The resulting list fruits contains the first substring before the comma as the first element and the remaining string as the second element:

['apple', 'banana,orange']

It’s important to note that the split() method in MicroPython returns a list of substrings. Each substring is a separate element in the list, which can be accessed using indexing. For example:

string = "apple,banana,orange"
fruits = string.split(",")
print(fruits[0])  # Output: apple
print(fruits[1])  # Output: banana

In conclusion, splitting strings is a useful operation when working with strings in MicroPython on Raspberry Pi Pico. It allows you to break down a string into smaller pieces and process each piece individually. By using the split() method, you can split a string into a list of substrings based on a delimiter, which can be used for further manipulation in your code.

Posted on Leave a comment

Concatenating Strings in MicroPython on Raspberry Pi Pico

In programming, concatenation is the process of combining two or more strings into a single string. This operation is commonly used in MicroPython on Raspberry Pi Pico to create dynamic messages and strings that can be used in various applications. In this blog post, we will explore the concept of string concatenation in MicroPython and how to use it in your code.

Concatenating Strings

In MicroPython, you can concatenate two or more strings using the + operator. For example:

string1 = "Hello"
string2 = " world!"
result = string1 + string2
print(result) # Output: Hello world!

In this example, we first define two strings string1 and string2. We then concatenate them using the + operator and store the result in a new variable result. Finally, we print the value of result, which gives us the concatenated string "Hello world!".

You can also concatenate multiple strings at once using the + operator. For example:

string1 = "Hello"
string2 = " world"
string3 = "!"
result = string1 + string2 + string3
print(result) # Output: Hello world!

In this example, we define three strings string1, string2, and string3. We then concatenate them using the + operator and store the result in a new variable result. Finally, we print the value of result, which gives us the concatenated string "Hello world!".

Concatenating Strings with Variables

In MicroPython, you can also concatenate strings with variables. For example:

name = "Alice"
message = "Hello, " + name + "!"
print(message) # Output: Hello, Alice!

In this example, we define a variable name with the value "Alice". We then concatenate the string "Hello, " with the value of the variable name using the + operator and store the result in a new variable message. Finally, we print the value of message, which gives us the concatenated string "Hello, Alice!".

Concatenating Strings with Numbers

In MicroPython, you can also concatenate strings with numbers using the str() function. For example:

age = 25
message = "I am " + str(age) + " years old."
print(message) # Output: I am 25 years old.

In this example, we define a variable age with the value 25. We then concatenate the string "I am " with the value of the variable age, which is converted to a string using the str() function. We then concatenate the string " years old." using the + operator and store the result in a new variable message. Finally, we print the value of message, which gives us the concatenated string "I am 25 years old.".

Conclusion

Concatenating strings is an important concept in MicroPython on Raspberry Pi Pico that is used in many applications. By using the + operator, you can easily concatenate strings and create dynamic messages and strings in your code. With the knowledge of string concatenation, you can create more powerful and complex programs.

Posted on Leave a comment

String manipulation in MicroPython on Raspberry Pi Pico

String manipulation is a common task in programming, including in MicroPython on Raspberry Pi Pico. It involves modifying, searching, and extracting data from strings. In this blog post, we will explore string manipulation techniques in MicroPython and how to use them effectively.

Modifying Strings

In MicroPython, strings are immutable, which means that once a string is defined, it cannot be modified. However, you can create a new string with the desired modification. One of the most common string modification tasks is to replace one substring with another. This is done using the replace() method. For example:

string = "Hello, world!"
new_string = string.replace("world", "MicroPython")
print(new_string) # Output: Hello, MicroPython!

The replace() method replaces all occurrences of the specified substring with the new substring.

Another common task is to convert a string to all uppercase or lowercase. This is done using the upper() and lower() methods, respectively. For example:

string = "Hello, world!"
upper_string = string.upper()
lower_string = string.lower()
print(upper_string) # Output: HELLO, WORLD!
print(lower_string) # Output: hello, world!

Searching Strings

Searching for a substring within a string is a common task in programming. In MicroPython, you can use the find() method to search for a substring within a string. For example:

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

The find() method returns the index of the first occurrence of the specified substring in the string, or -1 if the substring is not found.

substring not found
-1 means Substring not found

Extracting Data from Strings

Extracting a portion of a string is also a common task in programming. In MicroPython, you can use slicing to extract a portion of a string. For example:

string = "Hello, world!"
substring = string[7:]
print(substring) # Output: world!

The substring variable contains all characters in the original string from index 7 until the end.

You can also split a string into a list of substrings using the split() method. For example:

string = "The quick brown fox"
substring_list = string.split()
print(substring_list) # Output: ["The", "quick", "brown", "fox"]

The split() method splits the string at whitespace characters by default and returns a list of substrings.

String Formatting

String formatting is the process of inserting variables or values into a string. In MicroPython, you can use the format() method or f-strings to format strings. For example:

name = "Alice"
age = 25
string = "My name is {} and I am {} years old.".format(name, age)
print(string) # Output: My name is Alice and I am 25 years old.

f_string = f"My name is {name} and I am {age} years old."
print(f_string) # Output: My name is Alice and I am 25 years old.

The curly braces {} act as placeholders for variables or values that will be replaced during string formatting.

Conclusion
String manipulation is an important skill for any programmer, and MicroPython on Raspberry Pi Pico provides many useful tools for manipulating strings. By mastering these techniques, you can create more powerful and complex programs.

Posted on Leave a comment

Understanding string data types in MicroPython on Raspberry Pi Pico

Strings are one of the most commonly used data types in programming, including in MicroPython on Raspberry Pi Pico. In this blog post, we will explore the concept of string data types in MicroPython and how to work with them.

A string is a sequence of characters enclosed within single or double quotes. It can contain alphabets, numbers, and special characters. In MicroPython, strings are immutable, which means that once a string is defined, it cannot be modified. Instead, operations on strings create new strings.

To define a string in MicroPython, simply enclose the characters within single or double quotes. For example:

string1 = 'Hello, world!'
string2 = "Hello, again!"

Both string1 and string2 are examples of string variables in MicroPython.

In MicroPython, strings can also be indexed and sliced. The index of a string starts from 0 for the first character and increases by 1 for each subsequent character. To access a particular character in a string, simply use its index within square brackets. For example:

string = 'Hello, world!'
print(string[0])  # Output: H
print(string[4])  # Output: o

Slicing is the process of extracting a portion of a string. It is done by specifying the starting and ending indices within square brackets and separating them with a colon. For example:

string = 'Hello, world!'
print(string[0:5])  # Output: Hello
print(string[7:])  # Output: world!

The first slice string[0:5] extracts characters from index 0 up to index 5 but not including index 5, while the second slice string[7:] extracts all characters from index 7 until the end of the string.

String concatenation is the process of combining two or more strings into one. In MicroPython, it is done using the + operator. For example:

string1 = 'Hello,'
string2 = ' world!'
string3 = string1 + string2
print(string3)  # Output: Hello, world!

String formatting is another useful feature of strings in MicroPython. It allows you to insert variables or values into a string. The most common way to format a string in MicroPython is by using the % operator. For example:

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

The %s and %d are placeholders for the string and integer variables name and age, respectively.

In conclusion, understanding string data types in MicroPython on Raspberry Pi Pico is essential for anyone working with strings in their code. With the knowledge of string manipulation and formatting, you can create more powerful and complex programs.