Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

DroneBot Workshop

Build your own Electronics, IoT, Drones and Robots – Welcome to the
Workshop!

 Home
o Projects
o Tutorials
 Arduino
 Raspberry Pi
 ESP32
 Electronics
 Robots
o Build a REAL Robot
o Quadcopters
 Forum
 YouTube
 About
o Contact Us
o Frequently Asked Questions
o About Bill
o DroneBot Workshop Newsletter
o Privacy and Cookies
o Terms of Use
o Sitemap

Pico W with the Arduino IDE


There are a lot of videos and articles about using the new Raspberry Pi Pico W with
MicroPython, but very little has been produced about using this new board with
the Arduino IDE.
Today we will look at precisely that. While there has been no update to the
Arduino RP2040 boards manager to include the Pico W yet, there is another
boards manager that we can use instead.
Introduction
Amid all the confusion of life in 2020, there was one bright light – the release of
the Raspberry Pi Pico. This was the first microcontroller produced by Raspberry
Pi, which until then was known as a manufacturer of single-board computers
focused on the educational and maker market.
The Pico was not only unique in its position in the Raspberry Pi product lineup, but
it was also unique in that it used a new microcontroller chip that Raspberry Pi also
manufactured. The RP2040 microcontroller is a powerful device that has onboard
voltage regulation and two internal PIO (Programmable Input Output) processors
to allow the creation of custom I/O interfaces.
At only 4 dollars, the Pico joined boards like the Seeeduino XIAO as a low-cost,
high-performance microcontroller. And like the XIAO, it was missing one feature
many makers craved – wireless connectivity.
That all changed in June 2022 when the folks at Raspberry Pi tweeted out a picture
of a cow!
Raspberry Pi Pico W
It was a bit of an odd tweet from Raspberry Pi, a (hopefully) Photoshopped image
of a cow bearing Raspberry Pi logo markings. The picture was titled “Pi Cow”.
Of course, we now know the meaning of the strange image, as “Pi Cow” is just a
rearrangement of the words “Pico W”. Certainly a unique way of announcing a
new microcontroller board!
Pico W Features & Specifications
The “W” in Pico W does, of course, refer to WiFi, as, unlike its predecessor, the Pico
W does indeed have WiFi connectivity.
At a glance, the Pico W looks a lot like the Pico, with the obvious exception of the
huge metal square that contains the WiFi magic. It has the same 40-pin castellated
connector design that the original Pico has and the same 3-pin Debug connector,
which has been moved to a different position to accommodate the WiFi module
and onboard antenna.
The new device has exactly the same specifications as the older one, the only
programming difference (aside from the WiFi) is that the onboard LED is now
addressed differently, as the GPIO pin previously used to control it is required for
the WiFi module.
Speaking of WiFi, the new Raspberry Pi Pico W uses the Infineon CYW43439 WiFi
and Bluetooth module for its wireless network capability. This is a single-band 2.4
GHz 802.11n transceiver with a data rate of up to 96 Mbps. It has an integrated low
noise amplifier (LNA) for improved performance.
As for that onboard LED, it’s now connected to the WL_GPIO0 pin on the Infineon
CYW43439. You can address it using the “LED” constant in MicroPython, instead of
directly addressing GPIO pin 25 as you did in the older Pico. In the Arduino IDE
boards manager that I’ll be showing you soon, the onboard LED uses the
constant LED_BUILTIN(as it does with many Arduino boards).

As with its predecessor, the Pico W is distributed in a simple plastic carrier


package, and groups can be purchased in strips. You can also buy versions with the
pins already soldered in.
What about Bluetooth?
In addition to the cryptic cow picture, the folks at Raspberry Pi have left us with
another mystery – where is the Bluetooth? After all, the Infineon CYW43439 does
indeed support Bluetooth 5.2. So why doesn’t the Pico W offer Bluetooth in
addition to WiFi?
Currently, there is much debate about this in the maker community. Many people
feel that it is just a matter of time before Raspberry Pi releases an official SDK for
using Bluetooth with the Pico W.
But others point out that if you look at the specification sheet for the Infineon
CYW43439, you’ll note that the WiFi and Bluetooth use different interfaces,
although they share many of the same radio components. Bluetooth can use either
a PCM or UART input, however, if you check out the schematic diagram for the Pico
W, those pins appear to be unconnected.

Many are puzzled about how Bluetooth will work on the Pico W without those
pins. Perhaps the schematic isn’t complete, or maybe we can use the same
interface for both modes. If that’s the case, it’s possibly just a firmware update.
Eben Upton himself addressed the issue in his blog post announcing the Raspberry
Pi Pico W:
“Eagle-eyed readers of datasheets will notice that CYW43439 supports both
Bluetooth Classic and Bluetooth Low-Energy: we have not enabled Bluetooth on Pico
W at launch, but may do so in the future.”
Until this all gets resolved, I wouldn’t plan on developing Bluetooth applications
with the Raspberry Pi Pico W very soon!
Pico W vs. ESP32
Time to address the obvious question – which is better, the Raspberry Pi Pico W or
the Espressif ESP32?
At a glance, it would seem that the lack of Bluetooth on the Pico W makes the
ESP32 an instant winner, and when the rest of the specifications are compared, the
ESP32 certainly wins in almost every category.

One aspect in which the Pico W may have an advantage is that at 6 US dollars a
piece, the boards are cheaper than most ESP32 boards. And there is also the PIO
feature in the Pico W which is exclusive to the RP2040 chip.
So if your application doesn’t require Bluetooth or touch switches, or if you want to
drive a VGA display or an odd device using the PIO processors, then the Pico W is a
great choice.
Preparing the Arduino IDE
Most tutorials to date will show you how to use the Pico W with MicroPython,
which is a great and easy method of programming this device. And in the future,
I’ll also show you some Pico W applications coded in MicroPython.
But today, we will use the Arduino IDE to program the Pico W with C++. To do this,
we will have to add a Boards Manager to handle the new microcontroller.
I assume you have already installed the Arduino IDE on your Linux, Mac, or
Windows workstation. Note that if you are a Windows user, you should install
the IDE from the ZIP or EXE file on the Arduino website, not from the app in the
Microsoft Store. It has been reported that the Microsoft Store version of the
Arduino IDE has difficulty with the Pico, so it will likely have problems with the
newer Pico W.
Raspberry Pi Pico Arduino core
The Raspberry Pi Pico Arduino core is a boards manager maintained on GitHub by
user Earle F Philhower. This core covers not only the original Pico and the Pico W
but also includes pretty well every RP2040-based board that you can find and is
frequently updated.
In order to add this to your Arduino IDE, you will need to edit your Preferences to
add a JSON string in the same fashion that we have done for other boards like the
ESP32 and Seeeduino XIAO.
You can accomplish this as follows:
 Open the Arduino IDE.
 Click on the File menu item at the top and select Preferences.
The Preferences dialog box will open.
 Within the Preferences dialog box, look for a text box labeled “Additional
Boards Manager URLs”.
 This is where you will be inserting a JSON string. If the box is empty, you
can paste it directly, otherwise, click on the icon on the right of the box to
open a text window that allows you to add several JSON strings, one per
line.
The string you want to add is as follows:
https://github.com/earlephilhower/arduino-
pico/releases/download/global/package_rp2040_index.json
Once you have added the string to your Additional Boards Manager URLs, you can
click OK to save it in your Preferences.
Arduino IDE Boards Manager
The JSON file entry doesn’t actually install the new Pico RP2040 boards. Instead, it
points to a location where your Boards Manager can get updates, mpw including
one with the RP2040 board entries. You’ll need to add the new boards using the
Boards Manager utility in the Arduino IDE.
Open the Boards Manager utility by selecting the Tools menu. Scroll down until you
see an entry for the type of board (i.e., Arduino Uno) you are currently set up for.
Highlight that, and another menu will appear, allowing you to change your existing
board or launch the Boards Manager. You will want to launch the Boards Manager
so that you can install the new Pico W board.
When the Boards Manager window has launched, filter your search by typing in
“Pico”. You’ll get three results back, the second one, “Raspberry Pi Pico/RP2040” is
the one you want.
Select it and click the Install button to install the new Boards Manager entry.
It will take a minute to copy all the files, once it’s done, you are ready to start using
the Pico W on your Arduino IDE.
Testing the Installation – Blink
Now that you have the new boards manager files installed, you’ll want to test it. As
the standard method of testing ANY new board is the Blink sketch, we’ll defer to
tradition and use it.
In this case, it’s a good choice, as it uses the “LED_BUILTIN” constant for the
onboard LED. Remember, with the new Pico W, this is how you need to address the
LED, as it is no longer associated with GPIO port 25 but instead uses the WL_GPIO0
pin on the Infineon 43439 chip.
Load the Blink sketch, found in the Examples collection, into the Arduino IDE. We’ll
be using it as it is, as it already uses “LED_BUILTIN” it should work with pour new
Pico W.
Before we use it, however, we need to select the board and port we require.
Selecting a Board and Port
Now we need to select a board and port. This may not be as easy as it sounds!
Selecting the board is pretty simple. Open the Tools menu and go down to the
listing for your currently selected board. Click on it, and you’ll open up a submenu,
the same one we saw when we accessed the Boards Manager.
This time, you will want to select “Raspberry Pi Pico/RP2040”.
A menu with numerous RP2040 boards will be displayed. Scroll down until you see
the “Raspberry Pi Pico W” and select it.
If you haven’t already, you can plug your Pico W into a USB connector on the
computer. Depending upon your operating system and the current state of the Pico
W, you may get a message regarding a new drive.
Back in the IDE, in the same Tools menu, select the port (COM port on Windows)
that you have connected your board to. When you do this, one of three things will
occur:
 You’ll see a Raspberry Pi Pico, in which case you should select it.
 You’ll see a generic USB port that wasn’t there before, in which case you
might try selecting it.
 You won’t see a port.
In the third case (and possibly the second one), you can try and resolve this by
pulling the USB cable from the Pico W out of the computer, holding down the Pico
W’s BOOTSEL switch (the only switch on the board), and, keeping the switch held
down, plug the USB cable back in. After you plug in the cable, you can release
the BOOTSEL button.
Again, some operating systems may notify you about a new drive being mounted
when you do this.
Now check the Port selection to see if you now have a Raspberry Pi Pico W
available. Assuming that you do, you can now upload the Blink sketch.
If you get a blinking LED, then you’re in business!
Testing the Installation – ScanNetworks
Of course, blinking an LED is not a lot of fun, especially when we are evaluating a
new board that is WiFi capable. Let’s now use this new feature!
A simple way to test the WiFi is to load one of the WiFi example sketches. A good
test is the ScanNetworks sketch, which scans the area for WiFi networks and
displays them, along with their signal strengths.
Go into the File menu, open Examples, and scroll down to the “Examples for
Raspberry Pi Pico W” section. From there, navigate to the WiFi section.
Open the ScanNetworks sketch. This is a great sketch to test with, as it requires no
WiFi credentials.
As the sketch requires no modifications, load it to your Raspberry Pi Pico. Then
open your Serial Monitor and set the baud rate to 115,200 bps.
You should see a list of local WiFi networks, their SSID (if they allow it to be
displayed), their encryption method, and their signal strengths. The list repeats
after a short delay, so if nothing appears on your screen immediately, wait a few
seconds before pressing the panic button!
WiFi Library with Pico W
Now that we have confirmed that we can work with the Pico W using the Arduino
IDE, we are ready to write some of our own code to exploit the new WiFi feature.
To do that, we need to know how to connect the Pico W to a WiFi network and how
to use web data and build web interfaces.
Connecting to WiFi network
The first task we will examine is a common one, connecting to a WiFi network as a
client. This will require us to pass our login credentials to join an encrypted
network. After connecting successfully, we will be assigned an IP address.
The WiFi Library, already included in the Arduino IDE, is the key to making all of
this work. This library has all the basic functions you’ll need to connect to and
communicate over a WiFi network.
WiFi Demo Sketch
This sketch will illustrate the basic operation of the WiFi library. It just connects
the Pico to your local 2.4 GHz WiFi network and reads the IP address assigned to it
by your network’s DHCP server.

1 /*
2 Pi Pico W WiFi Station Demo
3 picow-wifi-station.ino
4 Use WiFi library to connect Pico W to WiFi in Station mode
5
6 DroneBot Workshop 2022
7 https://dronebotworkshop.com
8 */
9
10// Include the WiFi Library
11#include <WiFi.h>
12
13// Replace with your network credentials
14const char* ssid = "YOUR_SSID";
15const char* password = "YOUR_PASSWORD";
16
17void setup() {
18
19 // Start the Serial Monitor
20 Serial.begin(115200);
21
22 // Operate in WiFi Station mode
23 WiFi.mode(WIFI_STA);
24
25 // Start WiFi with supplied parameters
26 WiFi.begin(ssid, password);
27
28 // Print periods on monitor while establishing connection
29 while (WiFi.status() != WL_CONNECTED) {
30 delay(500);
31 Serial.print(".");
32 delay(500);
33 }
34
35 // Connection established
36 Serial.println("");
37 Serial.print("Pico W is connected to WiFi network ");
38 Serial.println(WiFi.SSID());
39
40 // Print IP Address
41 Serial.print("Assigned IP Address: ");
42 Serial.println(WiFi.localIP());
43
44}
45
46void loop() {
47
48 delay(2000);
49
50 // Print IP Address
51 Serial.print("Assigned IP Address: ");
52 Serial.println(WiFi.localIP());
53
54}
We start, of course, by including the WiFi library.
Next, we define some character constants for the SSID and password for the
network we wish to attach to. Of course, you’ll need to edit the code to match your
network parameters.
In the Setup, we start the serial monitor, as we will use it to display our connection
progress and our resulting IP address.
The next line specifies that we want to run in Station mode. This line is optional, if
you omit it, the library will just default to station mode.
We then use a WiFi.begin to initiate the network connection. Note that we pass the
SSID and password in this command.
We then wait for the network to connect by monitoring the status of
the WL_CONNECTED constant. If it is FALSE, then we are not connected. While
waiting, we print periods to the serial monitor as a progress indicator.
We then connect and print out the resulting IP address to the serial monitor.
In the Loop, we just repeat the IP address printout every two seconds. This is
useful as you can’t have the serial monitor open while you upload to the Pico W, so
by the time you get it open you may well miss the results from the Setup routine.
Load the sketch to your Pico W and observe the serial monitor. You should get an
IP address indicating that you are connected to your network.

To verify this, you can ping the IP address from another terminal on your network.
You should get a response from the Pico W.
Using Web Data – WiFiClient
One reason you might want to connect a microcontroller to the Internet is to use
data from a remote server. One of the examples included with the Pico boards
manager does just that.
The WiFiClient sketch is an adaptation of the same sketch for the ESP8266 (most of
the sample code has been adapted from sketches from other microcontrollers). It
connects to the djxmmx.net server and triggers it every five minutes with a “hello”
message to get a response.
The response is an amusing “quote of the day”, which will be printed on the serial
monitor.
You can find the sketch in the same WiFi section from which we got the
ScanNetworks sketch. After opening it, you’ll need to edit the “ssid” and “password”
constants to reflect the correct values for your WiFi network.
The sketch essentially connects to the server and confirms the connection. It sends
a string that says “hello from ESP8266” (maybe they should edit that for Pico W!)
to the server and listens for a response. That response will be the quote, which
we’ll extract from the data and print on the Serial monitor.
After that, we delay everything for five minutes to avoid flooding the server.
Load the sketch and let it run for a while. You’ll see several amusing quotes from
some famous people, if you run it long enough, you’ll also see some repeat
quotes. I guess that there can only be so many “quotes of the day”!
Pico W LED Control
Now that we have a handle on connecting the Pico W to a WiFi network, we can
use this ability to do something useful.
LED Control Web Page
The useful task we will perform is to control the onboard LED with a web-based
interface. This is essentially the same thing that Raspberry Pi provides an example
for doing in microPython, in our case, we will be using C++ and the Arduino IDE.
The web page will be very simple, displaying just a single toggle button and
indicating the current state of the onboard LED.
Of course, you can modify this example to control just about anything.
LED Control Code
Here is the code we will be using for our web-based LED control.

1 /*
2 Pico W Web Interface Demo
3 picow-web-control-demo.ino
4 Web Interface & WiFi Connection
5 Control the onboard LED with Pico W
6
7 Adapted from ESP32 example by Rui Santos - https://randomnerdtutorials.com
8
9 DroneBot Workshop 2022
10 https://dronebotworkshop.com
11 */
12
13 // Load Wi-Fi library
14 #include <WiFi.h>
15
16 // Replace with your network credentials
17 const char* ssid = "YOUR_SSID";
18 const char* password = "YOUR_PASSWORD";
19
20 // Set web server port number to 80
21 WiFiServer server(80);
22
23 // Variable to store the HTTP request
24 String header;
25
26 // Variable to store onboard LED state
27 String picoLEDState = "off";
28
29 // Current time
30 unsigned long currentTime = millis();
31 // Previous time
32 unsigned long previousTime = 0;
33 // Define timeout time in milliseconds (example: 2000ms = 2s)
34 const long timeoutTime = 2000;
35
36 void setup() {
37
38 // Start Serial Monitor
39 Serial.begin(115200);
40
41 // Initialize the LED as an output
42 pinMode(LED_BUILTIN, OUTPUT);
43
44 // Set LED off
45 digitalWrite(LED_BUILTIN, LOW);
46
47 // Connect to Wi-Fi network with SSID and password
48 WiFi.begin(ssid, password);
49
50 // Display progress on Serial monitor
51 while (WiFi.status() != WL_CONNECTED) {
52 delay(500);
53 Serial.print(".");
54 }
55
56 // Print local IP address and start web server
57 Serial.println("");
58 Serial.print("WiFi connected at IP Address ");
59 Serial.println(WiFi.localIP());
60
61 // Start Server
62 server.begin();
63 }
64
65 void loop() {
66
67 WiFiClient client = server.available(); // Listen for incoming clients
68
69 if (client) { // If a new client connects,
70 currentTime = millis();
71 previousTime = currentTime;
72 Serial.println("New Client."); // print a message out in the serial port
73 String currentLine = ""; // make a String to hold incoming data from the client
74 while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's
75 connected
76 currentTime = millis();
77 if (client.available()) { // if there's bytes to read from the client,
78 char c = client.read(); // read a byte, then
79 Serial.write(c); // print it out the serial monitor
80 header += c;
81 if (c == '\n') { // if the byte is a newline character
82 // if the current line is blank, you got two newline characters in a row.
83 // that's the end of the client HTTP request, so send a response:
84 if (currentLine.length() == 0) {
85 // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
86 // and a content-type so the client knows what's coming, then a blank line:
87 client.println("HTTP/1.1 200 OK");
88 client.println("Content-type:text/html");
89 client.println("Connection: close");
90 client.println();
91
92 // Switch the LED on and off
93 if (header.indexOf("GET /led/on") >= 0) {
94 Serial.println("LED on");
95 picoLEDState = "on";
96 digitalWrite(LED_BUILTIN, HIGH);
97 } else if (header.indexOf("GET /led/off") >= 0) {
98 Serial.println("LED off");
99 picoLEDState = "off";
100 digitalWrite(LED_BUILTIN, LOW);
101 }
102
103 // Display the HTML web page
104 client.println("<!DOCTYPE html><html>");
105 client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-
106scale=1\">");
107 client.println("<link rel=\"icon\" href=\"data:,\">");
108
109 // CSS to style the on/off buttons
110 client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-
111align: center;}");
112 client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px
11340px;");
114 client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
115 client.println(".button2 {background-color: #F23A3A;}</style></head>");
116
117 // Web Page Heading
118 client.println("<body><h1>Pico W LED Control</h1>");
119
120 // Display current state, and ON/OFF buttons for Onboard LED
121 client.println("<p>Onboard LED is " + picoLEDState + "</p>");
122
123 // Set buttons
124 if (picoLEDState == "off") {
125
126 //picoLEDState is off, display the ON button
127 client.println("<p><a href=\"/led/on\"><button class=\"button\">ON</button></a></p>");
128 } else {
129
130 //picoLEDState is on, display the OFF button
131 client.println("<p><a href=\"/led/off\"><button class=\"button
132button2\">OFF</button></a></p>");
133 }
134
135 client.println("</body></html>");
136
137 // The HTTP response ends with another blank line
138 client.println();
139 // Break out of the while loop
140 break;
141 } else { // if you got a newline, then clear currentLine
142 currentLine = "";
143 }
144 } else if (c != '\r') { // if you got anything else but a carriage return character,
145 currentLine += c; // add it to the end of the currentLine
146 }
147 }
148 }
149 // Clear the header variable
150 header = "";
151 // Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Once again, we start by loading the WiFi library and defining the SSID and
password information.
Next, we create a WiFiServer object named “server”. We put it on port 80, which is
the HTTP port.
We define variables to hold the HTTP request from the browser and to hold the
state of the onboard LED, We use a string variable for the LED state so that we can
print its value on our web page.
We also define variables to hold Time so we can have a timeout on our web page.
This is essential; otherwise, we would never disconnect and eventually use up
connections.
In Setup, we start the serial monitor. We then initialize the onboard LED pin as an
output and set it LOW to keep the LED off.
We then proceed to connect to the WiFi network, exactly as we did in our earlier
demo sketch.
Finally, after we connect, we start the WiFiServer object we created.
In the Loop, we listen for incoming client connections. When we get a connection
(i.e.when a web browser accesses the page), we start the timeout and see if there is
any information from the client. Remember, our client can send information to
control the LED.
If we get information from the client (an HTTP request), we break it down to see
what value is in the URL string. Depending on the value, we set our LED on or off
and style the onscreen pushbutton accordingly.
You can modify the style sheet settings in the HTML if you wish to change the
button shape or colors.
Load the code and give it a try. You should observe the LED responding to the
onscreen push button, which will change color and label every time it is toggled.
Of course, you can expand upon this concept to add more buttons and control
additional GPIO ports.
Pico W Servo Control
Our final Pico W experiment will be building another web-based interface. This
time, instead of a LED, we will be controlling the position of a servo motor.
Servo Hookup
Let’s get started by hookup up a servo motor to our Raspberry Pi Pico W.

The hookup is very simple, I used GPIO pin 2 on the Pico W so that I could also run
the “Sweep” demo to test the servo before I worked on my code. You could
actually use any GPIO pin.
Note that I’m using a 6-volt battery pack to power the servo motor. Most hobby-
grade servos require 5 to 6 volts and actually favor the higher voltage, so a power
pack consisting of 4 AA cells is a great choice. Otherwise, any external power pack
with the correct voltage specifications will work.
Adapting old code
This was a pretty simple example to put together, as I just grabbed some code
from a previous article that I did on using servo motors with the ESP32. The servo
control code is exactly what I need.
I needed to perform a few minor modifications to get it to work, but they were
pretty simple.
 I change the servo library from ESP32Servo.h to Servo.h.
 I removed the lines allocating timers for the servo.
 I removed the line for setting the servo PWM frequency.
Another change I made was to the color of the header text, that was just a personal
preference and had nothing to do with conversion from ESP32 code!
Otherwise, the sketch is unchanged.
This illustrates the ability to reuse old ESP32 or ESP8266 code with the Raspberry
Pi Pico W. In this case, the main change was the library, as the ESP32 won’t work
with the Arduino Servo Library. In many cases, you can run ESP32 code unaltered.
Servo Control Code
Here is the code for the servo motor controller. You might want to compare it to
the code in the ESP32 article to see how they match. The article also describes the
operation of the sketch, which uses JavaScript to exchange the data for the slider
position with the web server.

1 /*
2 Pico W Web Servo Control Demo
3 picow-web-servo-control.ino
4 Web interface for servo motor position
5 Adapted from ESP32 code - https://dronebotworkshop.com/esp32-servo
6
7 DroneBot Workshop 2022
8 https://dronebotworkshop.com
9 */
10
11 // Include WiFi and Servo libraries
12 #include <WiFi.h>
13 #include <Servo.h>
14
15 // Create a servo object
16 Servo myservo;
17
18 // Servo GPIO pin
19 static const int servoPin = 2;
20
21 // Network credentials
22 const char* ssid = "YOUR SSID";
23 const char* password = "YOUR PASSWORD";
24
25 // Web server on port 80 (http)
26 WiFiServer server(80);
27
28 // Variable to store the HTTP request
29 String header;
30
31 // Decode HTTP GET value
32 String valueString = String(5);
33 int pos1 = 0;
34 int pos2 = 0;
35
36 // Current time
37 unsigned long currentTime = millis();
38 // Previous time
39 unsigned long previousTime = 0;
40 // Define timeout time in milliseconds (example: 2000ms = 2s)
41 const long timeoutTime = 2000;
42
43 void setup() {
44
45 // Attach to servo and define minimum and maximum positions
46 // Modify as required
47 myservo.attach(servoPin, 600, 2400);
48
49 // Start serial
50 Serial.begin(115200);
51
52 // Connect to Wi-Fi network with SSID and password
53 WiFi.begin(ssid, password);
54 while (WiFi.status() != WL_CONNECTED) {
55 delay(500);
56 Serial.print(".");
57 }
58 // Print local IP address and start web server
59 Serial.println("");
60 Serial.println("Pico W is connected!");
61 Serial.print("Assigned IP address: ");
62 Serial.println(WiFi.localIP());
63 server.begin();
64 }
65
66 void loop(){
67
68 // Listen for incoming clients
69 WiFiClient client = server.available();
70
71 // Client Connected
72 if (client) {
73 // Set timer references
74 currentTime = millis();
75 previousTime = currentTime;
76
77 // Print to serial port
78 Serial.println("New Client.");
79
80 // String to hold data from client
81 String currentLine = "";
82
83 // Do while client is connected
84 while (client.connected() && currentTime - previousTime <= timeoutTime) {
85 currentTime = millis();
86 if (client.available()) { // if there's bytes to read from the client,
87 char c = client.read(); // read a byte, then
88 Serial.write(c); // print it out the serial monitor
89 header += c;
90 if (c == '\n') { // if the byte is a newline character
91 // if the current line is blank, you got two newline characters in a row.
92 // that's the end of the client HTTP request, so send a response:
93 if (currentLine.length() == 0) {
94
95 // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) and a content-type
96 client.println("HTTP/1.1 200 OK");
97 client.println("Content-type:text/html");
98 client.println("Connection: close");
99 client.println();
100
101 // Display the HTML web page
102
103 // HTML Header
104 client.println("<!DOCTYPE html><html>");
105 client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-
106scale=1\">");
107 client.println("<link rel=\"icon\" href=\"data:,\">");
108
109 // CSS - Modify as desired
110 client.println("<style>body { text-align: center; font-family: \"Trebuchet MS\", Arial; margin-
111left:auto; margin-right:auto; }");
112 client.println(".slider { -webkit-appearance: none; width: 300px; height: 25px; border-radius: 10px;
113background: #ffffff; outline: none; opacity: 0.7;-webkit-transition: .2s; transition: opacity .2s;}");
114 client.println(".slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width:
11535px; height: 35px; border-radius: 50%; background: #ff3410; cursor: pointer; }</style>");
116
117 // Get JQuery
118 client.println("<script
119src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>");
120
121 // Page title
122 client.println("</head><body style=\"background-color:#70cfff;\"><h1
123style=\"color:#f7e00a;\">Servo Control</h1>");
124
125 // Position display
126 client.println("<h2 style=\"color:#ffffff;\">Position: <span
127id=\"servoPos\"></span>&#176;</h2>");
128
129 // Slider control
130 client.println("<input type=\"range\" min=\"0\" max=\"180\" class=\"slider\" id=\"servoSlider\"
131onchange=\"servo(this.value)\" value=\""+valueString+"\"/>");
132
133 // Javascript
134 client.println("<script>var slider = document.getElementById(\"servoSlider\");");
135 client.println("var servoP = document.getElementById(\"servoPos\"); servoP.innerHTML =
136slider.value;");
137 client.println("slider.oninput = function() { slider.value = this.value; servoP.innerHTML = this.value;
138}");
139 client.println("$.ajaxSetup({timeout:1000}); function servo(pos) { ");
140 client.println("$.get(\"/?value=\" + pos + \"&\"); {Connection: close};}</script>");
141
142 // End page
143 client.println("</body></html>");
144
145 // GET data
146 if(header.indexOf("GET /?value=")>=0) {
147 pos1 = header.indexOf('=');
148 pos2 = header.indexOf('&');
149
150 // String with motor position
151 valueString = header.substring(pos1+1, pos2);
152
153 // Move servo into position
154 myservo.write(valueString.toInt());
155
156 // Print value to serial monitor
157 Serial.print("Val =");
158 Serial.println(valueString);
159 }
160 // The HTTP response ends with another blank line
161 client.println();
162
163 // Break out of the while loop
164 break;
165
166 } else {
167 // New lline is received, clear currentLine
168 currentLine = "";
169 }
170 } else if (c != '\r') { // if you got anything else but a carriage return character,
171 currentLine += c; // add it to the end of the currentLine
172 }
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
Load the sketch to your Pico W and then read the serial monitor to get its IP
address (if you’ve performed the previous sketches, it will likely just grab the same
IP address). Then open your web browser to that page.

You should see a slider control and a display of the servo position, from 0 to
180. Moving the slider will change the position of the servo motor.
Conclusion
Using the Pico W with the Arduino IDE expands the possibilities for this new,
inexpensive microcontroller, especially as you can repurpose code written for the
Arduino, the ESP32, and ESP8266.
While it certainly won’t replace the ESP32, especially where Bluetooth is
concerned, it is still a viable choice, given its low price tag and the support of an
already huge RP2040 community.
And you have to love a board named after a cow!
Resources
Code from this article – Pico W code in a ZIP file for your convenience!
RP2040 Boards Manager – GitHub page for the boards manager.
Arduino IDE – Download the Arduino IDE.

Related

Build a Pico “Uno” – Prototyping with the Pico


March 27, 2022
In "Arduino"

Pico Simon Game


February 28, 2022
In "Raspberry Pi"
Raspberry Pi Pico – How to Interface (almost) Everything!
February 13, 2021
In "Raspberry Pi"
Summary

Article Name
Pico W with the Arduino IDE
Description
Learn to program the Raspberry Pi Pico W using C++ and the Arduino IDE. Instructions for
installing Boards Manager and using WiFi with the new Pico W.
Author
DroneBot Workshop
Publisher Name
DroneBot Workshop
Publisher Logo

Tagged on: Raspberry Pi Tutorial


DroneBot WorkshopAugust 7, 2022Raspberry Pi, Software7 Comments

 ← Building a Dual-Boot Workstation


If you have a question...


Comments about this article are encouraged and appreciated. However, due to
the large volume of comments that I receive, it may not be possible for me to
answer you directly here on the website.

You are much more likely to get answers to technical questions by making a
post on the DroneBot Workshop Forum. Your post will be seen not only by
myself, but by a large group of tech enthusiasts who can quickly answer your
question. You may also add code samples, images and videos to your forum
posts.
Having said that, please feel free to leave constructive comments here. Your
input is always welcome. Please note that all comments may be held for
moderation.

{}[+]
7 COMMENTS
Oldest
Guddu
3 months ago
Really loved to learn the little board’s abilities. Thank you and stay well.
0
Reply

Mark Lewus
2 months ago
it was a great idea to avoid the micropython crowd and show your readers how
to use the Arduino IDE to access Wi-Fi on the pico. Thanks a lot
2
Reply

Bo Mathisen
2 months ago
Hi,
Thank’s for your work to get the Raspberry Pi Pico W up and running.
/ Bo Mathisen
0
Reply

Kim Madsen
1 month ago
It’s working.
Good work.
Thx here from Denmark.
0
Reply

Michael Griffiths
18 days ago
The post was very encouraging and I had no difficulty in getting some very
similar code up and running on my Raspberry Pi pico. When I tried something a
bit more ambitious (based on code working on an Arduino MKR 1010) I hit
problems. A generated web page included rather more JavaScript than your
Servo example and it was clear that a lot of the code was not being rendered to
the browser. I cut the JS to a minimum to test and in the end arrived at a
workaround – I wrote each line to the Serial object in… Read more »
0
Reply

Paul Humphreys
16 days ago
As always excellent presentation and understandable content.
Keep up the good work. Will be transfering some arduino nano projects to Pico
W
Thanks
Paul H
0
Reply

Luís Gema
2 days ago
Thank you very much for making your presentation available.
As always, very well explained and detailed.
All sketches worked.
hug from Portugal
Luís G.
0
Reply

Table of Contents
 1 Introduction
 2 Raspberry Pi Pico W
2.1 Pico W Features & Specifications
o
2.2 What about Bluetooth?
o
2.3 Pico W vs. ESP32
o
 3 Preparing the Arduino IDE
o3.1 Raspberry Pi Pico Arduino core
o3.2 Arduino IDE Boards Manager
o3.3 Testing the Installation – Blink
 3.3.1 Selecting a Board and Port
o 3.4 Testing the Installation – ScanNetworks
 4 WiFi Library with Pico W
o4.1 Connecting to WiFi network
o4.2 WiFi Demo Sketch
o4.3 Using Web Data – WiFiClient
 5 Pico W LED Control
o5.1 LED Control Web Page
o5.2 LED Control Code
 6 Pico W Servo Control
o 6.1 Servo Hookup
o 6.2 Adapting old code
o6.3 Servo Control Code
 7 Conclusion
o 7.1 Resources
Welcome to the Newsletter!
Let’s keep in touch!

Subscribe to the DroneBot Workshop Newsletter and be the first to find out
about new projects and new features on the website.

No spam - just useful information and updates sent to you every once in a while.
I’d love to be a regular visitor to your Inbox!

Subscribe Today!
Popular Articles

Getting started with ESP32


April 2, 2020
By DroneBot Workshop | 89 Comments
Time to move up to another microcontroller, the ESP32. This amazing
device has multiple I/O ports, WiFi, Bluetooth and BLE,...

Getting started with the ESP32-CAM


May 24, 2020
By DroneBot Workshop | 135 Comments
Today we will look at the amazing ESP32-CAM module from A-Thinker. This
10-dollar module features a 2MP camera, microSD card...

Stepper Motors with Arduino – Getting Started with Stepper


Motors
February 10, 2018
By DroneBot Workshop | 97 Comments
Stepper motors are used in a variety of devices ranging from 3D printers
and CNC machines to Blu Ray drives,...

Controlling DC Motors with the L298N Dual H-Bridge and an
Arduino
March 11, 2017
By DroneBot Workshop | 164 Comments
Controlling DC Motors is an essential skill for constructing robots and other
hobby projects. An easy way to control DC...

Using Inexpensive 433MHz Transmit and Receive Modules


with Arduino
February 17, 2018
By DroneBot Workshop | 51 Comments
Those inexpensive RF transmitter and receiver modules that you can get on
eBay and Amazon are perfect when you need...

Projects
 Arduino Projects
 Drone Projects
 Electronics Projects
 Internet of Things Projects
 Raspberry Pi Projects
 Robot Projects

6-Wheel Rover
 6-Wheel Rover – Introduction
 6-Wheel Rover – Rover Base – Not wild about the Wild Thumper Chassis
 6-Wheel Rover – Providing Power with Voltage Regulators
 6-Wheel Rover – 11.4-Volt Battery Connections
 6-Wheel Rover – ESCs and Motor Wiring

What's New?
 Driving DC Motors with Microcontrollers
 Measure Air Quality with Microcontrollers
 Pico W with the Arduino IDE
 Building a Dual-Boot Workstation
 Designing and Building Linear DC Power Supplies
 Using GC9A01 Round LCD Modules
 Sound with ESP32 – I2S Protocol
 Using Arduino Interrupts – Hardware, Pin Change and Timer
 Using the ESP32-CAM MicroSD Card

What’s Popular
 Getting started with ESP32
 Sound with ESP32 - I2S Protocol
 Using Servo Motors with ESP32
 Getting started with the ESP32-CAM
 ESP32 WiFiManager - Easy WiFi Provisioning
 Measure DC Voltage and Current with an Arduino

Workshop Connections
 View dronebotworkshop’s profile on Facebook
 View @DroneBotWS’s profile on Twitter
 View DroneBotWorkshop’s profile on GitHub
 View UCzml9bXoEM0itbcE96CB03w’s profile on YouTube
 View dronebotworkshop’s profile on Vimeo

Copyright © 2022 DroneBot Workshop.


 Home
 Arduino
 Raspberry Pi
 Drones
 Robots
 Electronics
 IoT
 Reviews
 Tutorials
 About Us
 Contact Us
 Privacy and Cookies
7

You might also like