Search Code

Course Lesson 2 of 10: Basic Python to drive Raspberry Pi Pico 4WD Smart Car Kit

Această lecție face parte din: Mașină inteligentă Raspberry Pi Pico 4WD

Course Lesson 2 of 10: Basic Python to drive Raspberry Pi Pico 4WD Smart Car Kit

In this second lesson of the Robojax Raspberry Pi Pico 4WD Smart Car course, we dive into the fundamental Python programming concepts that will empower you to control your robot. This guide is designed to take you from zero coding experience to confidently writing scripts that control hardware. Instead of just memorizing syntax, we'll explore the "why" behind each concept, giving you the tools to build and customize your own projects. By the end of this lesson, you will have a solid understanding of variables, control flow, functions, and lists—the building blocks for all future projects.

This knowledge isn't just for a smart car. The principles you'll learn here are the same ones used in countless real-world applications. You could apply these skills to:

  • Automating a home greenhouse to control fans, pumps, and lights based on sensor data.
  • Building a custom security system that triggers alarms or sends notifications.
  • Creating interactive art installations that respond to the environment.
  • Developing your own custom robot behaviors beyond the pre-programmed ones.

Hardware/Components

To follow along with the hardware examples in this lesson, you will need the following components. These are all part of the SunFounder Raspberry Pi Pico 4WD Smart Car Kit, but can be purchased individually for standalone experiments.

  • Raspberry Pi Pico: The microcontroller brain of the project.
  • An LED: Used to demonstrate digital output control.
  • A Resistor (150Ω - 330Ω): To limit current and protect the LED.
  • Jumper Wires: For making connections on a breadboard.
  • A Breadboard: For prototyping your circuit.

Wiring Guide

For the hardware demonstration in this lesson, we will build a simple circuit to control an LED with a Raspberry Pi Pico. The wiring is straightforward and is a classic first step in physical computing. The key is to use a current-limiting resistor to prevent the LED from burning out. The resistor is connected in series with the LED. The long leg of the LED (the anode) is the positive connection, and the short leg (the cathode) is the negative connection.

In the video, the instructor uses a resistor connected to the ground pin and the short leg of the LED. The long leg is connected to GPIO pin 22. This setup allows the Pico to send a high (3.3V) signal to the pin to turn the LED on and a low (0V) signal to turn it off.

Note: The wiring diagram is shown in the video. Please refer to the visual guide for exact placement.

Code Explanation

This lesson focuses on core Python syntax and logic, which is essential for controlling your robot. Let's break down the key concepts covered in the video. The code examples are written in MicroPython, a version of Python designed to run on microcontrollers like the Raspberry Pi Pico.

Variables and Data Types

Variables are like labeled boxes where you store information. In Python, you don't need to declare a variable's type; it is inferred from the value you assign. (in video at 03:33)


age = 23  # This is an integer
name = "Ahmad"  # This is a string (text)
pi = 3.14  # This is a float (decimal)

You can use these variables in calculations and print their values. For example, to calculate the number of days in a given age, you could use days = age * 365. The print() function is used to display output to the console.

Conditional Statements (If/Else)

Conditional statements allow your code to make decisions. This is crucial for a robot to react to its environment, like stopping when it detects an obstacle. (in video at 07:39)


age = 16
if age >= 17:
    print("You can drive")
else:
    print("Too young to drive")

The if statement checks a condition. If the condition is True, the indented code block below it is executed. If it's False, the code under the else statement runs. The indentation (spaces at the beginning of a line) is critical in Python; it defines which code belongs to which block.

Loops (For and While)

Loops are used to repeat a block of code. This is ideal for tasks like scanning sensor values or moving a motor through a sequence of steps. (in video at 09:04)

For Loop: This loop iterates a specific number of times.


for x in range(5):  # x will be 0, 1, 2, 3, 4
    print(x)

While Loop: This loop continues as long as a condition is true. This is useful for creating a main program loop that runs forever until a specific event occurs. (in video at 12:13)


x = 9
while x > 5:
    print("Value of x is:", x)
    x = x - 1  # Decrement x
print("Loop finished")

Be careful with while True: loops. They will run forever unless you use a break statement to exit the loop or you stop the program.

Functions

Functions are reusable blocks of code that perform a specific task. They help keep your code organized and prevent repetition. (in video at 14:52)


def calculate_days(years):
    days = years * 365
    return days

# Now we can use this function multiple times
days_in_10_years = calculate_days(10)
print("Days in 10 years:", days_in_10_years)

Here, calculate_days is a function that takes an argument (years) and returns a value. This is more efficient than writing the same calculation over and over. The video also demonstrates how one function can call another, allowing you to build complex operations from simple, testable parts.

Lists

Lists are used to store an ordered collection of items. This is perfect for storing a sequence of commands for your robot, like "forward", "back", "left", and "right". (in video at 19:15)


move = ["forward", "back", "left", "right", "stop"]
print(len(move))  # Prints the number of items in the list (5)
print(move[0]) # Prints the first item, "forward"

# You can add items
move.append("cliff")
# You can remove items
move.pop()  # Removes "cliff"
# You can change items
move[2] = "fly"  # Changes the third item to "fly"

Lists are zero-indexed, meaning the first item is at index 0. The len() function gives you the list's length, and you can use a for loop to iterate through all items. The enumerate() function is also introduced, which gives you both the index and the value during a loop, which is useful for working with multiple pins or sensors.

Working with Pins and Time

This is where you connect Python logic to the physical world. You use the machine library to control the Pico's GPIO pins. (in video at 25:16)


from machine import Pin
import time

# Set up pin 22 as an output
led = Pin(22, Pin.OUT)

# Turn the LED on and off
led.on()
time.sleep(1)
led.off()
time.sleep(1)

You can also read from a pin by setting it as an input with Pin(2, Pin.IN). The time library is essential for adding delays (time.sleep()) and for measuring elapsed time using time.ticks_ms() or converting between time formats with time.localtime() and time.mktime(). This is crucial for timing-based logic, like creating a pulse-width modulation (PWM) signal to control motor speed.

Live Project/Demonstration

In the video, the instructor provides a live demonstration of these concepts. He starts by showing simple print() statements and variable assignments in a Python interpreter. He then moves on to more complex examples, visually showing how if statements change a program's flow based on a variable's value.

The instructor then demonstrates a practical hardware example by connecting an LED to the Raspberry Pi Pico. He writes a simple MicroPython script that turns the LED on and off with a one-second delay, showing the direct result of controlling a physical output with code. This hands-on example solidifies the connection between the programming logic and real-world action. The lesson concludes by showing how to use enumerate to manage multiple pins and how to use the time module for more advanced timing and scheduling operations.

Chapters

  • [00:00] Introduction to the Raspberry Pi Pico Smart Car Course
  • [01:31] Course Overview and Kit Capabilities
  • [03:33] Variables and Data Types in Python
  • [07:39] Conditional Statements (If/Else)
  • [09:04] Understanding For Loops
  • [12:13] Exploring While Loops
  • [14:52] Defining and Using Functions
  • [19:15] Working with Lists and Data Structures
  • [25:16] Controlling GPIO Pins with MicroPython
  • [29:54] Practical Example: Blinking an LED
  • [31:15] Advanced Pin Control with Enumerate
  • [31:24] Working with Time Functions
Nu există cod atașat.

Resurse și referințe

Încă nu sunt resurse.

Fișiere📁

Nu sunt disponibile fișiere.