Hardware
Raspberry Pi 3 Model B
Scratch Programming Car Infrared Tracking
The overall power supply uses two 3.7V 18650 lithium batteries. The Raspberry Pi requires 5V power, so a step-down module like the Lm2596 is needed. The assembly is the same as the previous C language-controlled car.
Now let’s learn how to program the Raspberry Pi car using Scratch.
First, open all programs -> Programming -> Scratch ->
When opening the software, you can set the language to Chinese.
We control the car through the Scratch software, which means our main task is to use this software to control the Raspberry Pi GPIO, and to use it to receive signals from sensors via GPIO and process the signals.
The first step to open the software: set StartGPIOServer
Once all preparations are ready, let’s start
When the flag is clicked, gpioserveron opens the GPIOSERVER, then sets pins 18 23 24 25 (BCM encoding, corresponding to WPI encoding GPIO1, 4, 5, 6) to output mode. Set pins 12 16 (BCM encoding, corresponding to WPI encoding GPIO26 27) to input mode, which can receive high and low level signals sent by sensors. First, let’s see how to track objects or light sources using two infrared sensors or a photoresistor sensor.
We have set pins 12 and 16 to input mode, with the left sensor connected to pin 12 and the right sensor connected to pin 16. Then we add a conditional statement: when both infrared sensors have obstacles in front, move forward; if there is an obstacle on the left, turn left; if there is an obstacle on the right, turn right; if there are no obstacles, stay still. If pins 12 and 16 are connected to a photoresistor sensor, then it will follow the light. The same principle can be applied to follow a black line.
Next, let’s see how to control the car to move forward, backward, left, and right using buttons.
If set this way, when I press the W key, the car will keep moving forward without stopping. This is not very user-friendly. So I changed the running steps:
Move forward for 0.001 seconds and then stop. This way, as long as the W key is pressed, the car moves forward; when released, it stops. The same applies for backward and left/right. Everyone can write their own scripts according to their needs. Or run a small script that I have written first.
Reply “Raspberry Pi Scratch” to get the script file.