background image

SunFounder Thales Kit for Raspberry Pi Pico, Release 1.0

Next you will learn to install MicroPython into the Raspberry Pi Pico.

• Reference:

MicroPython - Wikipedia

• Reference:

realpython

3.1.3 Installing MicroPython

1. Press and hold the

BOOTSEL

button and then connect the Pico to computer via a Micro USB cable.

2. Release the BOOTSEL button after your Pico is mount as a Mass Storage Device called RPI-RP2.

3. Open the drive, you’ll see two files on your Pico:

INDEX.HTM

and

INFO_UF2.TXT

. Double click the first

file, INDEX.HTM, to open it in your browser.

INDEX.HTM

: This is a welcome page telling you all about your Pico.

INFO_UF2.TXT

: Contains the version of the bootloader it’s currently running.

4. When the browser opens, click

Getting started with MicroPython

.

40

Chapter 3. For MicroPython User

Summary of Contents for Thales Kit

Page 1: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 Jimmy SunFounder Jun 04 2021 ...

Page 2: ......

Page 3: ...ur First MicroPython Program 45 3 4 Projects 49 3 5 MicroPython Basic Syntax 109 4 For Arduino User 137 4 1 Getting Started with Arduino 137 4 2 Projects 143 5 FAQ 161 5 1 Q1 NO MicroPython Raspberry Pi Pico Interpreter Option on Thonny IDE 161 5 2 Q2 Cannot open Pico code or save code to Pico via Thonny IDE 162 5 3 Q3 Can Raspberry Pi Pico be used on Thonny and Arduino at the same time 162 5 4 Q4...

Page 4: ...ii ...

Page 5: ...practical projects for you and collected a lot of authoritative related informa tion just turn on your computer and you can complete programming learning in one stop In addition we provide 2 programming languages MicroPython and Arduino C C You can view different tutorials according to your needs If you want to learn another projects which we don t have please feel free to send Email and we will u...

Page 6: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 CONTENTS ...

Page 7: ...will support you every step of the way In the project it can control anything from LEDs and buttons to sensors motors and even other microcontrollers 1 1 Features 21 mm 51 mm form factor RP2040 microcontroller chip designed by Raspberry Pi in the UK Dual core Arm Cortex M0 processor flexible clock running up to 133 MHz 264KB on chip SRAM 2MB on board QSPI Flash 26 multifunction GPIO pins including...

Page 8: ...controller GPxx_ADCx General purpose input output or analog input Used as an analog input as well as a digital input or output but not both at the same time ADC_VREF Analog to digital converter ADC voltage reference A special input pin which sets a reference voltage for any ana log inputs AGND Analog to digital converter ADC 0 volts ground A special ground connection for use with the ADC_VREF pin ...

Page 9: ...ks below Raspberry Pi Pico product brief Raspberry Pi Pico datasheet Getting started with Raspberry Pi Pico C C development Raspberry Pi Pico C C SDK API level Doxygen documentation for the Raspberry Pi Pico C C SDK Raspberry Pi Pico Python SDK Raspberry Pi RP2040 datasheet Hardware design with RP2040 Raspberry Pi Pico design files Raspberry Pi Pico STEP file 1 2 Pico s Pins 5 ...

Page 10: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 6 Chapter 1 Introduction to Raspberry Pi Pico ...

Page 11: ...can check the contents of the list first Some of the components on the kit are very small and look the same the worker may omit or send it wrong when packing Please do not hesitate to send us the picture of the kit and the names of the missing or wrong components via email Here is the Email cs sunfounder com 7 ...

Page 12: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 8 Chapter 2 What is Included in This Kit ...

Page 13: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 2 1 Components List 2 1 Components List 9 ...

Page 14: ...t is used to build and test circuits quickly before finishing any circuit design And it has many holes into which components mentioned above can be inserted like ICs and resistors as well as jumper wires The breadboard allows you to plug in and remove components easily The picture shows the internal structure of a breadboard Although these holes on the breadboard appear to be inde pendent of each ...

Page 15: ...rter one the cathode Pay attention not to connect them inversely There is fixed forward voltage drop in the LED so it cannot be connected with the circuit directly because the supply voltage can outweigh this drop and cause the LED to be burnt The forward voltage of the red yellow and green LED is 1 8 V and that of the white one is 2 6 V Most LEDs can withstand a maximum current of 20 mA so we nee...

Page 16: ... colors by changing the input voltage of the three pins and superimpose them which according to statistics can create 16 777 216 different colors RGB LEDs can be categorized into common anode and common cathode ones In this kit the latter is used The common cathode or CC means to connect the cathodes of the three LEDs After you connect it with GND and plug in the three pins the LED will flash the ...

Page 17: ... 1 0 An RGB LED has 4 pins the longest one is GND the others are Red Green and Blue Touch its plastic shell and you will find a cut The pin closest to the cut is the first pin marked as Red then GND Green and Blue in turn 2 2 Components Introduction 13 ...

Page 18: ... the resistance is marked on it So if you see these symbols in a circuit it stands for a resistor is the unit of resistance and the larger units include K M etc Their relationship can be shown as follows 1 M 1000 K 1 K 1000 Normally the value of resistance is marked on it When using a resistor we need to know its resistance first Here are two methods you can observe the bands on the resistor or us...

Page 19: ...rey White Gold Silver 0 1 2 3 4 5 6 7 8 9 0 1 0 01 The 4 and 5 band resistors are frequently used on which there are 4 and 5 chromatic bands Normally when you get a resistor you may find it hard to decide which end to start for reading the color The tip is that the gap between the 4th and 5th band will be comparatively larger 2 2 Components Introduction 15 ...

Page 20: ...ssible error is 1 brown You can learn more about resistor from Wiki Resistor Wikipedia 2 2 5 Potentiometer Potentiometer is also a resistance component with 3 terminals and its resistance value can be adjusted according to some regular variation Potentiometers come in various shapes sizes and values but they all have the following things in common They have three terminals or connection points The...

Page 21: ...arm has rotated to or the travel it has made 2 Serving as a rheostat When the potentiometer is used as a rheostat connect the middle pin and one of the other 2 pins in the circuit Thus you can get a smoothly and continuously changed resistance value within the travel of the moving contact 3 Serving as a current controller When the potentiometer acts as a current controller the sliding contact term...

Page 22: ...hoto conductivity A photoresistor can be applied in light sensitive detector circuits and light activated and dark activated switching circuits acting as a resistance semiconductor In the dark a photoresistor can have a resistance as high as several megaohms M while in the light a photoresistor can have a resistance as low as a few hundred ohms Here is the electronic symbol of photoresistor Photor...

Page 23: ...opposite fundamental types With NTC thermistors resistance decreases as temperature rises usually due to an increase in conduction elec trons bumped up by thermal agitation from valency band An NTC is commonly used as a temperature sensor or in series with a circuit as an inrush current limiter With PTC thermistors resistance increases as temperature rises usually due to increased thermal lattice ...

Page 24: ...or is a semiconductor device that controls current by current It functions by amplifying weak signal to larger amplitude signal and is also used for non contact switch A transistor is a three layer structure composed of P type and N type semiconductors They form the three regions internally The thinner in the middle is the base region the other two are both N type or P type ones the smaller region...

Page 25: ...r labels When a High level signal goes through an NPN transistor it is energized But a PNP one needs a Low level signal to manage it Both types of transistor are frequently used for contactless switches just like in this experiment Put the label side facing us and the pins facing down The pins from left to right are emitter e base b and collector c 2 2 Components Introduction 21 ...

Page 26: ...e amount of stored electric charges is called capacitance Because capacitors are one of the most widely used electronic components in electronic equipment they are widely used in direct current isolation coupling bypass filtering tuning loops energy conversion and control circuits Capacitors are divided into electrolytic capacitors solid capacitors etc According to material characteristics capacit...

Page 27: ... or break circuits Although buttons come in a variety of sizes and shapes the one used here is a 6mm mini button as shown in the following pictures Pin 1 is connected to pin 2 and pin 3 to pin 4 So you just need to connect either of pin 1 and pin 2 to pin 3 or pin 4 The following is the internal structure of a button The symbol on the right below is usually used to represent a button in circuits 2...

Page 28: ...berry Pi Pico Release 1 0 Since the pin 1 is connected to pin 2 and pin 3 to pin 4 when the button is pressed the 4 pins are connected thus closing the circuit Examples Reading Button Value 24 Chapter 2 What is Included in This Kit ...

Page 29: ...ations of a small angle The principle is very simple When the switch is tilted in a certain angle the ball inside rolls down and touches the two contacts connected to the pins outside thus triggering circuits Otherwise the ball will stay away from the contacts thus breaking the circuits SW520D Tilt Switch Datasheet Reading Button Value 2 2 Components Introduction 25 ...

Page 30: ...pplies in electric instruments and electric toys widely How it works Set the middle pin as the fixed one When you pull the slide to the left the two pins on the left are connected when you pull it to the right the two pins on the right are connected Thus it works as a switch connecting or disconnecting circuits See the figure below The circuit symbol of the slide switch is shown as below The pin2 ...

Page 31: ...of the sensor one of the slots receives more radiation than the other which makes the output fluctuate high or low This change in output voltage is a result of detection of motion After the sensing module is wired there is a one minute initialization During the initialization module will output for 0 3 times at intervals Then the module will be in the standby mode Please keep the interference of l...

Page 32: ...can also see the sensing delay increasing The maximum of the sensing delay can reach up to 300s On the contrary if rotate it anticlockwise you can shorten the delay with a minimum of 5s Two Trigger Modes Choosing different modes by using the jumper cap H Repeatable trigger mode after sensing the human body the module outputs high level During the subsequent delay period if somebody enters the sens...

Page 33: ...etween an active buzzer and a passive buzzer An active buzzer has a built in oscillating source so it will make sounds when electrified But a passive buzzer does not have such source so it will not beep if DC signals are used instead you need to use square waves whose frequency is between 2K and 5K to drive it The active buzzer is often more expensive than the passive one because of multiple built...

Page 34: ... of rotation based on the current position so it can stop exactly at the right position as defined and hold there The angle is determined by the duration of a pulse that is applied to the control wire This is called Pulse width Modulation The servo expects to see a pulse every 20 ms The length of the pulse will determine how far the motor turns For example a 1 5ms pulse will make the motor turn to...

Page 35: ...e the pixel contains an intelligent digital interface data latch signal shaping amplifier drive circuit and a signal shaping circuit is built in to effectively ensure the color height of the pixel point light Consistent It is flexible can be docked bent and cut at will and the back is equipped with adhesive tape which can be fixed on the uneven surface at will and can be installed in a narrow spac...

Page 36: ...gy making the pixel cascade number is not limited the signal transmission only depend on the speed of signal transmission LED with low driving voltage environmental protection and energy saving high brightness scattering angl e is large good consistency low power long life and other advantages The control chip integrated in LED above becoming more simple circuit small volume convenient installatio...

Page 37: ...ow level SHcp Time sequence input of shift register On the rising edge the data in shift register moves successively one bit i e data in Q1 moves to Q2 and so forth While on the falling edge the data in shift register remain unchanged STcp Time sequence input of storage register On the rising edge data in the shift register moves into memory register CE Output enable pin active at low level DS Ser...

Page 38: ... segment forms part of a numeral to be displayed There are two types of pin connection Common Cathode CC and Common Anode CA As the name suggests a CC display has all the cathodes of the 7 LEDs connected when a CA display has all the anodes of the 7 segments connected In this kit we use the Common Cathode 7 segment display here is the electronic symbol 34 Chapter 2 What is Included in This Kit ...

Page 39: ...ments in a particular order some segments will brighten and others stay dim thus showing the corresponding character on the display Display Codes To help you get to know how 7 segment displays Common Cathode display Numbers we have drawn the following table Numbers are the number 0 F displayed on the 7 segment display DP GFEDCBA refers to the corresponding LED set to 0 or 1 For example 00111111 me...

Page 40: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 Example LED Segment Display 36 Chapter 2 What is Included in This Kit ...

Page 41: ...tions of the controller Therefore LCD1602 with an I2C bus is developed to solve the problem I2C communication I2C Inter Integrated Circuit bus is a very popular and powerful bus for communication between a master device or master devices and a single or multiple slave devices I2C main controller can be used to control IO expander various sensors EEPROM ADC DAC and so on All of these are controlled...

Page 42: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 38 Chapter 2 What is Included in This Kit ...

Page 43: ...pt into a finished implementation MicroPython is supported by a diverse Pythonista community that has a keen interest in seeing the project succeed In addition to testing and supporting the code base the developers provided tutorials code libraries and hardware ports making the project far more than Damien could have done alone Reference realpython 3 1 2 Why MicroPython Although the original Kicks...

Page 44: ...Micro USB cable 2 Release the BOOTSEL button after your Pico is mount as a Mass Storage Device called RPI RP2 3 Open the drive you ll see two files on your Pico INDEX HTM and INFO_UF2 TXT Double click the first file INDEX HTM to open it in your browser INDEX HTM This is a welcome page telling you all about your Pico INFO_UF2 TXT Contains the version of the bootloader it s currently running 4 When ...

Page 45: ...are by clicking the Download UF2 file button 6 Open the Downloads folder and find the file you just downloaded it will be called pico_micropython_xxxx uf2 then drag it to RPI RP2 storage drive Your Pico will reboot and disap pear from the File Manager 3 1 Geting Started with MicroPython 41 ...

Page 46: ... is now running MicroPython Congratulations your re now ready to get started with MicroPython on your Raspberry Pi Pico 3 2 Thonny Python IDE Before you can start to program Pico with MicroPython you need an integrated development environment IDE here we recommend Thonny Thonny comes with Python 3 7 built in just one simple installer is needed and you re ready to learn programming 3 2 1 Download f...

Page 47: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 3 2 2 Introducing Thonny IDE Ref realpython 3 2 Thonny Python IDE 43 ...

Page 48: ...ors when writing code Errors can take many forms sometimes using incorrect syntax sometimes incorrect logic Debugging is the tool for finding and investigating errors Note The Debug tool cannot be used when MicroPython Raspberry Pi Pico is selected as the interpreter If you want to debug your code you need to select the interpreter as the default interpreter and save as to your computer after debu...

Page 49: ...ur Pico is plugged into your computer via a USB cable The Raspberry Pi Pico interpreter is only available in version 3 3 3 or higher version of Thonny If you are running an older version please update 3 3 Your First MicroPython Program In MicroPython there are two options methods for running code Interactive Mode Script Mode Interactive mode involves running your code directly from the Python shel...

Page 50: ...gain and make sure it is the same as this one and then press Enter You will find that the message hello world will be printed out immediately in the Shell area 3 3 2 Script Mode Interactive mode is not recommended if you need to write a long piece of Python code or if your Python script spans multiple files In this case script mode can be used In script mode you write your code and save it with a ...

Page 51: ...e MicroPython Raspberry Pi Pico displayed in the bottom right corner this is the interpreter you need to select if yours is not this one you can click on it to switch Note When you tell Thonny to save your program on the Raspberry Pi Pico if you unplug the Pico and plug it into someone else s computer your program is still saved on the Pico Choose the location you want to save then enter the file ...

Page 52: ... contents of the script area the EDITOR_CONTENT The second is the output of the program the message you told MicroPython to print In Script mode it is very easy for you to open the previously saved code again but the code entered in Interactive Mode will not be saved and can only be re entered Click the open icon in the Thonny toolbar just like when you save the program you will be asked whether y...

Page 53: ...o Like other LEDs it will glow when power is on and go out when power is off Code Let s copy this code into Thonny and click Run Current Script or simply press F5 to run it to make the LED blink Don t forget to left click on the bottom right corner and switch the python version name to MicroPython Raspberry Pi Pico import machine import utime led_onboard machine Pin 25 machine Pin OUT while True l...

Page 54: ...in OUT tells that the pin should be used as an output instead of an input The above code has set the pin but it will not light up the LED To do this we also need to use the pin led_onboard value 1 We have set up the GP25 pin before and named it led_onboard The function of this statement is to set the value of led_onboard to 1 to turn the on board LED on All in all to use GPIO these steps are neces...

Page 55: ...rewrite the program and it will be what you saw at the beginning of this chapter import machine import utime led_onboard machine Pin 25 machine Pin OUT while True led_onboard value 1 utime sleep 2 led_onboard value 0 utime sleep 2 What More Usually the library will have a corresponding API Application Programming Interface file This is a concise ref erence manual that contains all the information ...

Page 56: ...w to Use a Breadboard Science Buddies What is a BREADBOARD Makezine For breadboards what you need to know clearly is 1 Each group of half rows inside the breadboard such as column A E in row 1 or column F J in row 3 is connected This means that when an electrical signal flows in from A1 it can flow from B1 C1 D1 E1 but not from F1 or A2 2 Both sides of the breadboard are usually used as power buse...

Page 57: ...ed red black black and brown 3 Pick up the LED you will see that one of its leads is longer than the other Insert the longer lead into the same row as the end of the resistor and connect the shorter lead across the middle gap of the breadboard to the same row Note The longer lead is known as the anode and represents the positive side of the circuit the shorter lead is the cathode and represents th...

Page 58: ...Pin OUT while True led toggle utime sleep 1 toggle can switch the pin between high level and low level and you can see the LED blinking Also see reference here machine Pin 3 4 3 Reading Button Value From the name of GPIO General purpose input output we can see that these pins have both input and output func tions In the previous two lessons we used the output function in this chapter we will use t...

Page 59: ...t will connect the two half rows of the same row number together For example in my circuit E23 and F23 have been connected as are E25 and F25 Before the button is pressed the left and right sides are independent of each other and current cannot flow from one side to the other 3 Use a jumper wire to connect one of the button pins to the positive bus mine is the pin on the upper right 4 Connect the ...

Page 60: ... of the breadboard to Pico s GND Code When the button is pressed the current will flow from 3V3 through the button to GP14 in other words GP14 will read a high level signal 1 otherwise it will read a low level signal 0 import machine import utime button machine Pin 14 machine Pin IN while True if button value 1 print You pressed the button utime sleep 1 Pull up Working Mode Next is the wiring and ...

Page 61: ...he upper right 4 Connect the other pin upper left or lower left to GP14 with a jumper wire 5 Use a 10K resistor to connect the pin on the upper left corner of the button and the positive bus 6 Connect the negative power bus of the breadboard to Pico s GND import machine import utime button machine Pin 14 machine Pin IN while True if button value 0 When the button is pressed GPIO will be connected ...

Page 62: ...power bus of the breadboard 2 Insert the tilt switch into the breadboard 3 Use a jumper wire to connect one end of tilt switch pin to the positive bus 4 Connect the other pin to GP14 with a jumper wire 5 Use a 10K resistor to connect the second pin which connected to GP14 and the negative bus 6 Connect the negative power bus of the breadboard to Pico s GND When you put a flat breadboard the circui...

Page 63: ...he breadboard to Pico s GND When you toggle the slide switch the circuit will switch between closed and open Slide Switch Capacitor 3 4 4 Reaction Game Microcontrollers not only appear in industrial equipment they are also used to control a large number of electronic devices in the home including toys and games In this chapter we will use button and LED to build a simple reaction timing game The s...

Page 64: ...n as fast as possible and the program will tell you what your reaction time is import machine import utime import urandom led machine Pin 15 machine Pin OUT button machine Pin 14 machine Pin IN def button_press pin button irq handler None rection_time utime ticks_diff utime ticks_ms timer_light_off print Your reaction time was str rection_time milliseconds led value 1 utime sleep urandom uniform 5...

Page 65: ...eaction time was str rection_time milliseconds led value 1 utime sleep urandom uniform 5 10 led value 0 timer_light_off utime ticks_ms button irq trigger machine Pin IRQ_RISING handler button_press Here a callback function button_press is first defined which is called an interrupt handler It will be executed when an interrupt request is triggered Then set up an interrupt request in the main progra...

Page 66: ... loaded here Use the urandom uniform 5 10 function to generate a random number the uniform part referring to a uniform distribution between those two numbers If needed try running the following example of random number generation import machine import utime import urandom while True print urandom uniform 1 20 utime sleep 1 The last two statements you need to understand are utime ticks_ms and utime...

Page 67: ...time from when the light turns off to when the button is pressed Finally this time will be printed out print Your reaction time was str rection_time milliseconds Also see the reference here machine Pin urandom utime What more Playing with your friends will be more fun why not add buttons and see who can press the buttons the fastest Please try it import machine import utime import urandom led mach...

Page 68: ...electronic devices many microcontrollers can also be found in the social environment including traffic lights Traffic lights are used to direct traffic operation and are generally composed of red green and yellow lights Building a huge traffic management system is a fairly advanced project but using Pico to drive a miniature traffic light is a project we can try Let s make a mini pedestrian crossi...

Page 69: ...ress the button the red LED will be extended to 15 seconds which will give us more time to cross the road import machine import utime import _thread led_red machine Pin 15 machine Pin OUT led_yellow machine Pin 14 machine Pin OUT led_green machine Pin 13 machine Pin OUT button machine Pin 16 machine Pin IN global button_status button_status 0 def button_thread global button_status while True if bu...

Page 70: ...derstood as dividing a thing into multiple parts which are executed by different people or processors Just like when the chef is frying the steak the assistant chef makes the sauce so that the newly prepared sauce can be poured on the properly prepared steak to make the best cooking Look at these lines import machine import utime import _thread led_red machine Pin 15 machine Pin OUT led_yellow mac...

Page 71: ...nge every 2 seconds The two threads work independently of each other Let s go back to the traffic signal program We let the main thread change the light and let the new thread read the button value However the threads are independent of each other and we need a way for the new thread to pass information to the main thread which requires the use of global variable The variables we have used before ...

Page 72: ... line is not needed 3 4 6 Two Kinds of Transistors Transistor is a semiconductor device that controls a large current through a small current Its function is to amplify weak signals into larger amplitude signals and can also be used as a non contact switch It is the core component of electronic circuits This sounds a bit complicated In simple words some components use high current such as Buzzer I...

Page 73: ...ns facing down The pins from left to right are emitter e base b and collector c Note The base is the gate controller device for the larger electrical supply In the NPN transistor the collector is the larger electrical supply and the emitter is the outlet for that supply the PNP transistor is just the opposite 1 Way to connect NPN S8050 transistor 3 4 Projects 69 ...

Page 74: ...pin through a 1k resistor 5 Connect the emitter lead of the transistor to the negative power bus 6 Connect one side of the button to the GP14 pin and use a 10k resistor connect the same side and negative power bus The other side to the positive power bus Note The color ring of 220 resistor is red red black black and brown The color ring of the 1k resistor is brown black black brown and brown The c...

Page 75: ...ve power bus Code Two kinds of transistors can be controlled with the same code When we press the button Pico will send a high level signal to the transistor when we release it it will send a low level signal We can see that diametrically opposite phenomena have occurred in the two circuits The circuit using the NPN transistor will light up when the button is pressed which means it is receiving a ...

Page 76: ...put it will receive infrared radiation emitted from the body thereby detecting the movement of people and other animals More specifically it tells the main control board that someone has entered your room PIR Motion Sensor Now let s use PIR and active buzzer to build an Intruder Alarm Wiring Two types of buzzers are included in the kit We need to use active buzzer Turn them around the sealed back ...

Page 77: ...de pin of the buzzer to the collector lead of the transistor 4 Connect the base lead of the transistor to the GP15 pin through a 1k resistor 5 Connect the emitter lead of the transistor to the negative power bus 6 Connect the OUT of PIR to the GP14 pin VCC to the positive power bus and GND to the negative power bus Note The color ring of the 1k resistor is brown black black brown and brown 3 4 Pro...

Page 78: ...umper cap on the pin with L and the middle pin Copy the following code into Thonny and run it let us analyze its adjustment method along with the experimental results import machine import utime pir_sensor machine Pin 14 machine Pin IN global timer_delay timer_delay utime ticks_ms print start def pir_in_high_level pin global timer_delay pir_sensor irq trigger machine Pin IRQ_FALLING handler pir_in...

Page 79: ... movement of the organism note that it is movement not static in front of the sensor as long as the organism keeps moving within the detection range the PIR will continue to send a high level signal to the main control board We can see in the printed data that the duration of work is an uncertain value 2 Delay Adjustment The potentiometer on the left is used to adjust the interval between two jobs...

Page 80: ...e was used to achieve this goal but this is always unreliable and inefficient Therefore Pulse width modulation PWM has emerged as a feasible solution to such complex problems A digital output composed of a high level and a low level is called a pulse The pulse width of these pins can be adjusted by changing the ON OFF speed Simply put when we are in a short period such as 20ms most people s visual...

Page 81: ... understanding this knowledge let us try to achieve the effect of Fading LED Wiring 1 Here we use the GP15 pin of the Pico board 2 Connect one end either end of the 220 ohm resistor to GP15 and insert the other end into the free row of the breadboard 3 Insert the anode lead of the LED into the same row as the end of the 220 resistor and connect the cathode lead across the middle gap of the breadbo...

Page 82: ...uency However there is no limit when using LEDs alone we set it to 1000Hz The led duty_u16 line is used to set the duty cycle which is a 16 bit interger 2 16 65536 When we assign a 0 to this function the duty cycle is 0 and each cycle has 0 of the time to output a high level in other words turn off all pulses When the value is 65535 the duty cycle is 100 that is the complete pulse is turned on and...

Page 83: ...ided for each anode pin the light of the corresponding color can be displayed By changing the electrical signal intensity of each anode it can be made to produce various colors Wiring Put the RGB LED flat on the table we can see that it has 4 leads of different lengths Find the longest one GND and turn it sideways to the left Now the order of the four leads is Red GND Green Blue from left to right...

Page 84: ...ty the Red LED will be brighter than the other two and a slightly larger resistor needs to be used to reduce its brightness 4 Connect the Green lead to the GP14 pin via a 220 resistor 5 Connect the Blue lead to the GP15 pin via a 220 resistor 6 Connect the GND lead to the negative power bus 7 Connect the negative power bus to Pico s GND Note The color ring of the 220 resistor is red red black blac...

Page 85: ...blue freq 1000 def interval_mapping x in_min in_max out_min out_max return x in_min out_max out_min in_max in_min out_min def color_to_duty rgb_value rgb_value int interval_mapping rgb_value 0 255 0 65535 return rgb_value def color_set red_value green_value blue_value red duty_u16 color_to_duty red_value green duty_u16 color_to_duty green_value blue duty_u16 color_to_duty blue_value color_set 255 ...

Page 86: ...ead of 0 to 255 when the output signals to RGB LED through PWM we have defined color_to_duty and interval_mapping function to map the color values to the duty values 3 4 10 Custom Tone We have used active buzzer in the previous lesson this time we will use passive buzzer Like the active buzzer the passive buzzer also uses the phenomenon of electromagnetic induction to work The difference is that a...

Page 87: ...ct the base lead of the transistor to the GP15 pin through a 1k resistor 5 Connect the emitter lead of the transistor to the negative power bus Note The color ring of the 1k ohm resistor is brown black black brown and brown Code import machine import utime buzzer machine PWM machine Pin 15 def tone pin frequency duration pin freq frequency pin duty_u16 30000 utime sleep_ms duration pin duty_u16 0 ...

Page 88: ...h Duration the duration of the tone We use the duty_u16 function to set the duty cycle to 30000 about 50 It can be other numbers and it only needs to generate a discontinuous electrical signal to oscillate What more We can simulate the specific tone according to the fundamental frequency of the piano so as to play a complete piece of music Piano key frequencies Wikipedia import machine import utim...

Page 89: ...a device controlled by PWM signal Servo Servo is a position angle servo device which is suitable for those control systems that require constant angle changes and can be maintained It has been widely used in high end remote control toys such as airplanes submarine models and remote control robots Now try to make the servo sway 3 4 Projects 85 ...

Page 90: ...1 Press the Servo Arm into the Servo output shaft If necessary fix it with screws 2 Connect VBUS not 3V3 and GND of Pico to the power bus of the breadboard 3 Connect the red lead of the servo to the positive power bus with a jumper 86 Chapter 3 For MicroPython User ...

Page 91: ... pulse_width 0 20 0 65535 pin duty_u16 duty while True for angle in range 180 servo_write servo angle utime sleep_ms 20 for angle in range 180 1 1 servo_write servo angle utime sleep_ms 20 How it works We defined the servo_write function to make the servo run This function has two parameters pin the GPIO pin that controls the servo Angle the angle of the shaft output In this function interval_mapp...

Page 92: ... allows the microcontroller to sense the light intensity sound intensity temperature humidity etc of the physical world Usually a microcontroller needs an additional hardware to implement analog input the analogue to digital converter ADC But Pico itself has a built in ADC for us to use directly Pico has three GPIO pins that can use analog input GP26 GP27 GP28 That is analog channels 0 1 and 2 In ...

Page 93: ...le pin of the potentiometer to GP28 with a jumper wire 5 Connect the anode of the LED to the GP15 pin through a 220 resistor and connect the cathode to the negative power bus Code When the program is running we can see the analog value currently read by the GP28 pin in the shell Turn the knob and the value will change from 0 to 65535 At the same time the brightness of the LED will increase as the ...

Page 94: ...entiometer machine ADC 28 servo machine PWM machine Pin 15 servo freq 50 def interval_mapping x in_min in_max out_min out_max return x in_min out_max out_min in_max in_min out_min def servo_write pin angle pulse_width interval_mapping angle 0 180 0 5 2 5 duty int interval_mapping pulse_width 0 20 0 65535 pin duty_u16 duty while True value potentiometer read_u16 angle interval_mapping value 0 65535...

Page 95: ...dition of NTC is opposite to the former In this experiment we use an NTC thermistor to make a thermometer Wiring 1 Connect 3V3 and GND of Pico to the power bus of the breadboard 2 Connect one lead of the thermistor to the GP28 pin then connect the same lead to the positive power bus with a 10K ohm resistor 3 Connect another lead of thermistor to the negative power bus Note The thermistor is black ...

Page 96: ...ibrary which declares a set of functions to compute common mathematical operations and trans formations math temperature_value thermistor read_u16 This function is used to read the value of the thermistor Vr 3 3 float temperature_value 65535 Rt 10000 Vr 3 3 Vr temp 1 math log Rt 10000 3950 1 273 15 25 Cel temp 273 15 Fah Cel 1 8 32 print Celsius 2f C Fahrenheit 2f F Cel Fah utime sleep_ms 200 Thes...

Page 97: ...he effective range This code refers to plugging Rt into the formula TK 1 ln RT RN B 1 TN to get Kelvin temperature temp temp 273 15 Convert Kelvin temperature into centigrade degree Fah Cel 1 8 32 Convert the centigrade degree into Fahrenheit degree print Celsius 2f C Fahrenheit 2f Cel Fah Print centigrade degree Fahrenheit degree and their units in the shell 3 4 14 Light Theremin Theremin is an e...

Page 98: ... bus 5 Insert the passive buzzer and S8050 transistor into the breadboard The anode pin of the buzzer is connected to the positive power bus the cathode pin is connected to the collector lead of the transistor and the base lead of the transistor is connected to the GP15 pin through a 1k resistor emitter lead is connected to the negative power bus Note The color ring of the 22 resistor is red red b...

Page 99: ... to swing our hands up and down on top of the photoresistor and the movement range of the hand will be calibrated to the playing range of this instrument After five seconds the LED will go out and we can wave our hands on the photoresistor to play 3 4 15 Microchip 74HC595 Integrated circuit integrated circuit is a kind of miniature electronic device or component which is represented by the letter ...

Page 100: ... 74HC595 is a 16 pin IC with a semi circular notch on one side usually the left side of the label With the notch facing upwards its pins are shown in the diagram below Refer to the figure below to build the circuit 1 Connect 3V3 and GND of Pico to the power bus of the breadboard 96 Chapter 3 For MicroPython User ...

Page 101: ... 1 2 3 4 5 6 7 of 74HC595 9 Connect the cathode leads of the LEDs with a 220 resistor in series to the negative power bus Code import machine import time sdi machine Pin 0 machine Pin OUT rclk machine Pin 1 machine Pin OUT srclk machine Pin 2 machine Pin OUT def hc595_shift dat rclk low time sleep_ms 5 for bit in range 7 1 1 srclk low time sleep_ms 5 value 1 dat bit sdi value value time sleep_ms 5...

Page 102: ...egment Display is essentially a device packaged by 8 LEDs of which 7 strip shaped LEDs form an 8 shape and there is a slightly smaller dotted LED as a decimal point These LEDs are marked as a b c d e f g and dp They have their own anode pins and share cathodes Their pin locations are shown in the figure below This means that it needs to be controlled by 8 digital signals at the same time to fully ...

Page 103: ...the LED Segment Display into the breadboard and connect a 220 resistor in series with the GND pin to the negative power bus Note The color ring of the 220 ohm resistor is red red black black and brown 9 Follow the table below to connect the 74hc595 and LED Segment Display Table 1 Wiring 74HC595 LED Segment Display Q0 a Q1 b Q2 c Q3 d Q4 e Q5 f Q6 g Q7 dp Code import machine import time SEGCODE 0x3...

Page 104: ...imilarly we can also make the LED Segment Display display other numbers in the same way The following table shows the codes corresponding to these numbers Table 2 Glyph Code Numbers Binary Code Hex Code 0 00111111 0x3f 1 00000110 0x06 2 01011011 0x5b 3 01001111 0x4f 4 01100110 0x66 5 01101101 0x6d 6 01111101 0x7d 7 00000111 0x07 8 01111111 0x7f 9 01101111 0x6f Write these codes into hc595_shift to...

Page 105: ...ontrol IO expander various sensors EEPROM ADC DAC and so on All of these are controlled only by the two pins of host the serial data SDA line and the serial clock line SCL These two pins must be connected to specific pins of the microcontroller There are two pairs of I2C communication interfaces in Pico which are marked as I2C0 and I2C1 as shown in the figure below Here we will use the I2C0 interf...

Page 106: ...brary import machine import time class LCD def __init__ self addr 0x27 blen 1 sda machine Pin 0 scl machine Pin 1 self bus machine I2C 0 sda sda scl scl freq 400000 print self bus scan self addr addr self blen blen self send_command 0x33 Must initialize to 8 line mode at first time sleep 0 005 self send_command 0x32 Then initialize to 4 line mode time sleep 0 005 self send_command 0x28 2 Lines 5 7...

Page 107: ...4 buf 0x04 RS 0 RW 0 EN 1 self write_word buf time sleep 0 002 buf 0xFB Make EN 0 self write_word buf def send_data self data Send bit7 4 firstly buf data 0xF0 buf 0x05 RS 1 RW 0 EN 1 self write_word buf time sleep 0 002 buf 0xFB Make EN 0 self write_word buf Send bit3 0 secondly buf data 0x0F 4 buf 0x05 RS 1 RW 0 EN 1 self write_word buf time sleep 0 002 buf 0xFB Make EN 0 self write_word buf def...

Page 108: ... utime sleep 2 lcd clear After the program runs you will be able to see two lines of text appear on the LCD in turn and then disappear How it works In the lcd1602 library we integrate the relevant functions of lcd1602 into the LCD class Import lcd1602 library from lcd1602 import LCD Declare an object of the LCD class and name it lcd lcd LCD This statement will display the text on the LCD It should...

Page 109: ...t utime import math thermistor machine ADC 28 lcd LCD while True temperature_value thermistor read_u16 Vr 3 3 float temperature_value 65535 Rt 10000 Vr 3 3 Vr temp 1 math log Rt 10000 3950 1 273 15 25 Cel temp 273 15 Fah Cel 1 8 32 print Celsius 2f C Fahrenheit 2f F Cel Fah utime sleep_ms 200 string Temperature is n str 2f format Cel C lcd message string utime sleep 1 lcd clear 3 4 Projects 105 ...

Page 110: ... After transmission for each pixelthe signal to reduce 24bit pixel adopt auto reshaping transmit technology making the pixel cascade number is not limited the signal transmission only depend on the speed of signal transmission Wiring 1 Connect the 5V of the LED Strip to the VBUS of the Pico 2 Connect the GND of the LED Strip to the GND of the Pico 3 Connect the DIN of the LED Strip to the GP0 of P...

Page 111: ... 8 def write_all self value for i in range self led_nums self __setitem__ i value self write def list_to_hex self color if isinstance color list and len color 3 c color 0 8 color 1 16 color 2 return c elif isinstance color int value color 0xFF0000 8 color 0x00FF00 8 color 0x0000FF return value else raise ValueError Color must be 24 bit RGB hex or list of 3 8 bit RGB def hex_to_list self color if i...

Page 112: ...with the following statement from ws2812 import WS2812 Declare a WS2812 type object named ws it is connected to pin there are number RGB LEDs on the WS2812 strip ws WS2812 pin number ws is an array object each element corresponds to one RGB LED on the WS2812 strip for example ws 0 is the first one ws 7 is the eighth We can assign color values to each RGB LED these values must be 24 bit color repre...

Page 113: ...ust like you type them line by line in the Shell A program that just browses the instruction list line by line is not very smart though so MicroPython just like Python has its own method to control the sequence of its program execution indentation You must put at least one space before print otherwise an error message Invalid syntax will appear It is usually recommended to standardise spaces by pr...

Page 114: ...icropython from running the code print Can t run it print hello world This is a annotationhello world Run c EDITOR_CONTENT hello world Multi line comment If you want to comment on multiple lines you can use multiple signs This is a comment written in more than just one line print Hello World Run c EDITOR_CONTENT Hello World Or you can use multi line strings instead of expected Since MicroPython ig...

Page 115: ... a variable is very simple You only need to name it and assign it a value You don t need to specify the data type of the variable when assigning it because the variable is a reference and it accesses objects of different data types through assignment Naming variables must follow the following rules Variable names can only contain numbers letters and underscores The first character of the variable ...

Page 116: ...pe You can get the data type of a variable with the type function x 5 y hello z 5 0 print type x type y type z Run c EDITOR_CONTENT class int class str class float Single or Double Quotes In MicroPython single quotes or double quotes can be used to define string variables x hello is the same as x hello Case Sensitive Variable names are case sensitive a 5 A lily A will not overwrite a print a A Run...

Page 117: ...expression is True If test expression is False then statement s will not be executed In MicroPython indentation means the body of the if statement The body starts with an indentation and ends with the first unindented line Python interprets non zero values as True None and 0 are interpreted as False if Statement Flowchart Example num 8 if num 0 print num is a positive number print End with this li...

Page 118: ...nd will execute the body of if only when the test condition is True If the condition is False the body of else is executed Indentation is used to separate the blocks if else Statement Flowchart Example num 8 if num 0 print num is a positive number else print num is a negative number Run c EDITOR_CONTENT 8 is a negative number 114 Chapter 3 For MicroPython User ...

Page 119: ...f is False the condition of the next elif block is checked and so on If all conditions are False the body of else is executed Only one of several if elif else blocks is executed according to the conditions The if block can only have one else block But it can have multiple elif blocks if elif else Statement Flowchart Example if x y print x is greater than y elif x y print x and y are equal continue...

Page 120: ...to execute a program in a loop under certain conditions to handle the same task that needs to be processed repeatedly Its basic form is while test expression Body of while In the while loop first check the test expression Only when test expression evaluates to True enter the body of the while After one iteration check the test expression again This process continues until test expression evaluates...

Page 121: ...ease 1 0 x 10 while x 0 print x x 1 Run c EDITOR_CONTENT 10 9 8 7 6 5 4 3 2 1 Break Statement With the break statement we can stop the loop even if the while condition is true x 10 while x 0 print x if x 6 break x 1 3 5 MicroPython Basic Syntax 117 ...

Page 122: ...r Run c EDITOR_CONTENT 10 9 8 7 6 5 4 3 2 1 Game Over 3 5 7 For Loops The for loop can traverse any sequence of items such as a list or a string The syntax format of for loop is as follows for val in sequence Body of for Here val is a variable that gets the value of the item in the sequence in each iteration The loop continues until we reach the last item in the sequence Use indentation to separat...

Page 123: ... The sum is sum Run c EDITOR_CONTENT The sum is 10 The break Statement With the break statement we can stop the loop before it has looped through all the items numbers 1 2 3 4 sum 0 for val in numbers sum sum val if sum 6 break print The sum is sum Run c EDITOR_CONTENT The sum is 6 3 5 MicroPython Basic Syntax 119 ...

Page 124: ...nerate every number it contains However this is not an iterator because it supports in len and __getitem__ operations This function will not store all values in memory it will be inefficient So it will remember the start stop step size and generate the next number during the journey To force this function to output all items we can use the function list print range 6 print list range 6 print list ...

Page 125: ...e 5 if val 2 break print val else print Finished Run c EDITOR_CONTENT 0 1 3 5 8 Functions In MicroPython a function is a group of related statements that perform a specific task Functions help break our program into smaller modular blocks As our plan becomes larger and larger functions make it more organized and manageable In addition it avoids duplication and makes the code reusable Create a Func...

Page 126: ...t to avoid errors An optional return statement to return a value from the function Calling a Function To call a function add parentheses after the function name def my_function print Your first function my_function Run c EDITOR_CONTENT Your first function The return Statement The return statement is used to exit a function and return to the place where it was called Syntax of return return express...

Page 127: ...ome name msg This is a welcome function for the person with the provided message print Hello name msg welcome Lily Welcome to China Herethe function welcome has 2 parameters Since we called this function with two arguments the function runs smoothly without any errors If it is called with a different number of arguments the interpreter will display an error message The following is the call to thi...

Page 128: ...ts For example if we define the above function header as def welcome name Lily msg We will receive the following error message Run c EDITOR_CONTENT Traceback most recent call last File stdin line 1 in module SyntaxError non default argument follows default argument Keyword Arguments When we call a function with certain values these values will be assigned to arguments based on their position For e...

Page 129: ... China Lily Welcome to China John Welcome to China Wendy Here we have called the function with multiple arguments These arguments are packed into a tuple before being passed into the function Inside the function we use a for loop to retrieve all the arguments Recursion In Python we know that a function can call other functions It is even possible for the function to call itself These types of cons...

Page 130: ...Recursive functions make the code look clean and elegant A complex task can be broken down into simpler sub problems using recursion Sequence generation is easier with recursion than using some nested iteration Disadvantages of Recursion Sometimes the logic behind recursion is hard to follow through Recursive calls are expensive inefficient as they take up a lot of memory and time Recursive functi...

Page 131: ...ype z Run c EDITOR_CONTENT class str class int class list Setting the Specific Data Type If you want to specify the data type you can use the following constructor functions Example Date Type x int 20 int x float 20 5 float x complex 1j complex x str Hello World str x list apple banana cherry list x tuple apple banana cherry tuple x range 6 range x dict name John age 36 dict x set apple banana che...

Page 132: ...the string represents a whole number float constructs a float number from an integer literal a float literal or a string literal providing the string represents a float or an integer str constructs a string from a wide variety of data types including strings integer literals and float literals a float 5 b int 3 7 c str 6 0 print a print b print c Note You cannot convert complex numbers into anothe...

Page 133: ...e common mathematical operations Operator Name Addition Subtraction Multiplication Division Modulus Exponentiation Floor division x 5 y 3 a x y b x y c x y d x y e x y f x y g x y print a print b print c print d print e print f print g Run c EDITOR_CONTENT 8 2 15 1 666667 2 125 1 8 2 15 3 5 MicroPython Basic Syntax 129 ...

Page 134: ...a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a a 6 a 6 a 6 print a Run test py 36 Comparison Operators Comparison operators are used to compare two values Operator Name Equal Not equal Less than Greater than Greater than or equal to Less than or equal to a 6 b 8 print a b Run test py False Return False beause the a is less than the b 130 Chapter 3 For MicroPython...

Page 135: ... operators are used to compare the objects not if they are equal but if they are actually the same object with the same memory location Operator Description is Returns True if both variables are the same object is not Returns True if both variables are not the same object a hello welcome b hello welcome c a print a is c returns True because z is the same object as x print a is b returns False beca...

Page 136: ...R_CONTENT True Bitwise Operators Bitwise operators are used to compare binary numbers Operator Name Description AND Sets each bit to 1 if both bits are 1 OR Sets each bit to 1 if one of two bits is 1 XOR Sets each bit to 1 if only one of two bits is 1 NOT Inverts all the bits Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off Signed right shift Sh...

Page 137: ...duplicate print C_list 0 print C_list 1 ordered C_list 2 Purple changeable print C_list Run c EDITOR_CONTENT Red Blue Green Blue Red Blue Red Blue Purple Blue A list can contain different data types A_list Banana 255 False 3 14 print A_list Run c EDITOR_CONTENT Banana 255 False 3 14 List Length To determine how many items are in the list use the len function A_list Banana 255 False 3 14 print len ...

Page 138: ...e Orange print A_list Run c EDITOR_CONTENT Banana True Orange 3 14 Change the second value by replacing it with two values A_list Banana 255 False 3 14 A_list 1 2 True Orange print A_list Run c EDITOR_CONTENT Banana True Orange False 3 14 Add List Items Using the append method to add an item C_list Red Blue Green C_list append Orange print C_list Run c EDITOR_CONTENT Red Blue Green Orange Insert a...

Page 139: ... the pop method removes the last item A_list Banana 255 False 3 14 True Orange A_list pop 1 print A_list A_list pop print A_list Run c EDITOR_CONTENT 255 Banana False 3 14 True Orange Orange Banana False 3 14 True The del keyword also removes the specified index C_list Red Blue Green del C_list 1 print C_list Run c EDITOR_CONTENT Red Green The clear method empties the list The list still remains b...

Page 140: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 136 Chapter 3 For MicroPython User ...

Page 141: ...ort time even if you are a beginner It provides an integrated development environment IDE for code compiling compatible with multiple control boards So you can just download the Arduino IDE upload the sketches i e the code files to the board and then you can see relative experimental phenomena For more information refer to Arduino Website 4 1 1 Install Arduino IDE Go to Arduino Software Page to do...

Page 142: ...ales Kit for Raspberry Pi Pico Release 1 0 4 1 2 Setup the Raspberry Pi Pico 1 Open the Boards Manager by clicking Tools Board Boards Manager 2 Search for Pico and click install button 138 Chapter 4 For Arduino User ...

Page 143: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 3 Once the installation is complete you can select the board as Raspberry Pi Pico 4 Now open a example blink 4 1 Getting Started with Arduino 139 ...

Page 144: ...Pi Pico Release 1 0 5 Click on the upload icon to run the code 6 When the compiling message shown in the figure below appears press BOOTSEL immediately and connect Pico to the computer with a Micro USB cable 140 Chapter 4 For Arduino User ...

Page 145: ...co will be recognized by the computer as COMxx Raspberry Pi Pico You only need to plug it into the computer the next time you use it 7 After the Done Uploading appear you will see the LED on the Pico blinking 4 1 3 Introduction the Arduino Software IDE Double click the Arduino icon arduino exe created by the installation process Then the Arduino IDE will appear Let s check details of the software ...

Page 146: ...iting window 4 Open Open an ino sketch 5 Save Save the sketch 6 Serial Monitor Click the button and a window will appear It receives the data sent from your control board It is very useful for debugging 7 File Click the menu and a drop down list will appear including file creating opening saving closing some parameter configuring etc 8 Edit Click the menu On the drop down list there are some editi...

Page 147: ... path the details of error prompts 14 Board and Port Here you can preview the board and port selected for code upload You can select them again by Tools Board Port if any is incorrect 15 The editing area of the IDE You can write code here 4 2 Projects Note The Pico Arduino core is a recent development so it may take a long time to compile and upload or the COM port may suddenly disappear during us...

Page 148: ...black black and brown 3 Pick up the LED you will see that one of its leads is longer than the other Insert the longer lead into the same row as the end of the resistor and connect the shorter lead across the middle gap of the breadboard to the same row Note The longer lead is known as the anode and represents the positive side of the circuit the shorter lead is the cathode and represents the negat...

Page 149: ...se a delay 1000 code to let the controller do nothing for 1000 ms delay 1000 4 2 2 Fading LED In last projects we have used only two output signals high level and low level or called 1 0 ON OFF which is called digital output However in actual use many devices do not simply ON OFF to work for example adjusting the speed of the motor adjusting the brightness of the desk lamp and so on In the past a ...

Page 150: ... independent PWM outputs instead of 30 distributed between GP0 to GP15 on the left and the PWM output of the right GPIO is equivalent to the left copy What we need to pay attention to is to avoid setting the same PWM channel for different purposes during programming For example GP0 and GP16 are both PWM_0A After understanding this knowledge let us try to achieve the effect of Fading LED 146 Chapte...

Page 151: ...he free row of the breadboard 3 Insert the anode lead of the LED into the same row as the end of the 220 resistor and connect the cathode lead across the middle gap of the breadboard to the same row 4 Connect the LED cathode to the negative power bus of the breadboard 5 Connect the negative power bus to the GND pin of Pico Note The color ring of the 220 ohm resistor is red red black black and brow...

Page 152: ...ge the brightness for next time through the loop brightness brightness fadeAmount Use an if statement to limit the range of brightness to 0 255 the brightness will accumulate from 0 to 255 and then decrement from 255 to 0 alternating repeatedly if brightness 0 brightness 255 fadeAmount fadeAmount 4 2 3 Warning Light From the name of GPIO General purpose input output we can see that these pins have...

Page 153: ...adboard 5 Insert the slide switch into the breadboard 6 Use a jumper wire to connect one end of slide switch pin to the negative bus 7 Connect the middle pin to GP14 with a jumper wire 8 Use a jumper wire to connect last end of slide switch pin to the positive bus 9 Use a 10K resistor to connect the middle pin of the slide switch and the negative bus 10 Use a 104 capacitor to connect the middle pi...

Page 154: ...LED on digitalWrite ledPin HIGH delay 1000 digitalWrite ledPin LOW delay 1000 Otherwise turn off the LED else digitalWrite ledPin LOW 4 2 4 Table Lamp In the previous lessons we have used the digital input on the Pico For example a button can change the pin from low level off to high level on This is a binary working state However Pico can receive another type of input signal analog input It can b...

Page 155: ...at can use analog input GP26 GP27 GP28 That is analog channels 0 1 and 2 In addition there is a fourth analog channel which is connected to the built in temperature sensor and will not be introduced here In this lesson we try to read the analog value of potentiometer 4 2 Projects 151 ...

Page 156: ...s respectively 4 Connect the middle pin of the potentiometer to GP28 with a jumper wire 5 Connect the anode of the LED to the GP15 pin through a 220 resistor and connect the cathode to the negative power bus Code Once the code has been successfully uploaded open Serial Monitor and then ensure that baudrate is 9600 rotate the potentiometer in 2 directions and you will see that the value range is 0 ...

Page 157: ... and you have selected the correct board and port but the upload is still not successful At this point you can click on the Upload icon again when the progress below shows Upload unplug the USB cable again and plug it in and the code will be uploaded successfully 4 2 Projects 153 ...

Page 158: ... the value of SensorValue in Serial Monitor Serial println sensorValue Here the map value fromLow fromHigh toLow toHigh function is required as the potentiometer value read is in the range 0 1023 and the value of a PWM pin is in the range 0 255 It is used to Re maps a number from one range to another That is a value of fromLow would get mapped to toLow a value of fromHigh to toHigh values in betwe...

Page 159: ...pins and setting initial values of variables In order to quickly set the input output status and HIGH LOW for the 5 LEDs in the following code here we use the array ledPin to define the 5 LEDs connected to the corresponding pins of the Pico The element number of the array usually starts from 0 For example ledPin 0 refers to GPIO11 and ledPin 4 refers to GPIO15 array void setup Serial begin 9600 st...

Page 160: ...alWrite ledPins i HIGH turn on LEDs less than the level else digitalWrite ledPins i LOW turn off LEDs higher than level Now we need to find a way to display the brightness level at this time with LEDs The for statement is used here to perform loop detection in the ledPin array If the element bit in the array is less than the value of Level the corresponding GPIO is set to high level that is the co...

Page 161: ...high level signal is given to the base of the NPN transistor the transistor is turned on and the buzzer can emit a sound When a pin is floating its level may be high or low so we connect a 10K resistor in the upper left corner of the button to keep the button in a low state when it is not pressed You can also try to remove this 10K resistor and you will find that even if it is not pressed the buzz...

Page 162: ... If you cannot find pitches h after downloading or opening the code you can just install one manually Click the button below the serial monitor icon and select New Tab or use Ctrl Shift N Then paste from Code and save it as pitches h int melody NOTE_C4 NOTE_G3 NOTE_G3 NOTE_A3 NOTE_G3 0 NOTE_B3 NOTE_C4 int buttonPin 14 note durations 4 quarter note 8 eighth note int noteDurations 4 8 8 4 4 4 4 4 Th...

Page 163: ...on in loop When the button is pressed buttonState will be equal to 1 In the for statement a tone is used to let the buzzer play one note at a time and then after 8 times the buzzer can play the notes in the array melody one by one tone 15 melody i noteDuration 15 The pin on which to generate the tone the buzzer pin melody i The frequency of the tone in hertz noteDuration The duration of the tone i...

Page 164: ...SunFounder Thales Kit for Raspberry Pi Pico Release 1 0 160 Chapter 4 For Arduino User ...

Page 165: ... into your computer via a USB cable Check that you have installed MicroPython for Pico Installing MicroPython The Raspberry Pi Pico interpreter is only available in version 3 3 3 or higher version of Thonny If you are running an older version please update Thonny Python IDE Plug in out the micro USB cable sveral times 161 ...

Page 166: ... on Thonny IDE you need to Installing MicroPython on it If you used it on Thonny first and now you want to use it on Arduino IDE you need to Setup the Raspberry Pi Pico 5 4 Q4 Code upload failed in Arduino IDE Make sure you have installed the Pico board in the Arduino IDE Check that the Board Raspberry Pi Pico or portCOMxx Raspberry Pi Pico is selected correctly Make sure you have plugged the Pico...

Page 167: ...it for personal study investigation enjoyment or other non commercial or nonprofit purposes under therelated regulations and copyrights laws without infringing the legal rights of the author and relevant right holders For any individual or organization that uses these for commercial profit without permission the Company reserves the right to take legal action 163 ...

Reviews: