Wireless Communication with the Pico W¶
Summary¶
This chapter covers wireless communication on the Pico W. It explains how to connect to Wi-Fi (credentials, SSID, DHCP, the CYW43 wireless chip) and use that connection for HTTP requests, a simple web server, and MQTT publish/subscribe messaging over a broker. It then introduces Bluetooth Low Energy -- advertising, peripheral and central roles, services, characteristics, and pairing -- as the basis for peer-to-peer swarm robotics communication, along with practical networking concerns like latency, packet loss, wireless range, and basic network security. Students finishing this chapter will be able to connect a Pico W to Wi-Fi and exchange data with another device over HTTP, MQTT, or BLE.
Concepts Covered¶
This chapter covers the following 36 concepts from the learning graph:
- Wi-Fi
- Wi-Fi Credentials
- Network SSID
- IP Address
- DHCP
- Wireless Module
- CYW43 Chip
- Socket Programming
- HTTP Protocol
- HTTP Request
- HTTP Response
- Web Server
- REST Endpoint
- JSON Data Format
- MQTT Protocol
- MQTT Broker
- MQTT Topic
- Publish Subscribe Model
- Bluetooth Low Energy
- BLE Advertising
- BLE Peripheral
- BLE Central
- BLE Service
- BLE Characteristic
- Pairing Process
- Swarm Robotics
- Peer To Peer Communication
- Network Latency
- Packet Loss
- Wireless Range
- Firewall Basics
- Network Security
- Captive Portal
- Access Point Mode
- Station Mode
- Remote Control Interface
Prerequisites¶
This chapter builds on concepts from:
- Chapter 2: Choosing the Right Raspberry Pi Product
- Chapter 4: Digital I/O, PWM, and the MicroPython Workflow
- Chapter 7: Building and Programming a No-Display STEM Robot
Time to Cut the Cord!
Every project so far has needed a USB cable tethering it to your computer. Not anymore! This chapter unlocks a genuine superpower: talking to your Pico W over the air, whether that's to a web browser, a phone, a cloud service, or another robot sitting three feet away. Let's build something wireless!
Your robot from the previous chapter can sense, think, and act — but only within reach of a cable. This chapter breaks that leash. The Pico W is a version of the Raspberry Pi Pico with a built-in radio, and once you understand how to use that radio, your robot can report its sensor readings to a phone across the room, receive drive commands from a web page, or coordinate with a swarm of other robots without any of them being plugged into anything. Wireless communication is what turns a single isolated gadget into a connected system — the same shift that turned early standalone computers into the internet.
This chapter builds that connected system in layers. First, you'll connect the Pico W to a Wi-Fi network the way a phone or laptop does. Then you'll use that connection two different ways — a familiar web-style conversation (HTTP) and a lightweight messaging system built for tiny devices (MQTT). After that, you'll look at the practical realities every wireless project runs into: delay, dropped data, limited range, and security. Finally, you'll meet Bluetooth Low Energy, a short-range wireless technology better suited to two robots talking directly to each other than to browsing the web.
From Pico to Pico W: Adding a Radio¶
The plain Raspberry Pi Pico you used in earlier chapters has no way to send or receive wireless signals at all — every bit of data has to travel over a wire. Wi-Fi is a family of wireless networking standards that lets devices exchange data over radio waves within roughly the range of a house or classroom, the same technology your laptop and phone already use to reach the internet. To use it, a device needs a wireless module — a self-contained chip or circuit that handles the low-level work of sending and receiving radio signals, so the rest of the system doesn't have to.
On the Pico W, that wireless module is a specific chip: the CYW43 chip, made by Infineon (originally Cypress), which handles both Wi-Fi and Bluetooth radio duties from the same physical package. You don't program the CYW43 chip's radio signals directly — MicroPython's network module talks to it for you, the same way earlier chapters let you blink a NeoPixel without writing your own timing-critical LED protocol from scratch.
Berry's Key Insight
A plain Pico and a Pico W run the exact same MicroPython language and the exact same GPIO pins for sensors and actuators. The CYW43 chip is the only hardware difference that matters here — everything you already know about sense-think-act still applies, this chapter just adds a new way to "act": sending data somewhere else entirely.
Joining a Wireless Network¶
Before a Pico W can send a single byte over Wi-Fi, it has to join a network the same way your phone does when you type in a password at a coffee shop. A network SSID (Service Set Identifier) is the human-readable name of a Wi-Fi network — the text you see when you scan for available networks on any device. Alongside the SSID, most networks require Wi-Fi credentials, typically a password, to prove a device is allowed to join. In MicroPython, you hand both of these to the wireless module in a single connect() call.
Once a device is accepted onto the network, it still needs an address so other devices can find it — the network equivalent of a street address. DHCP (Dynamic Host Configuration Protocol) is the process a router uses to automatically hand out that address to each new device, rather than requiring a person to type one in by hand. The address DHCP assigns is an IP address: a numeric label (like 192.168.1.42) that uniquely identifies a device on that network so data sent to it arrives at the right place.
There are actually two different roles a Wi-Fi radio can play, and the Pico W's network module lets you choose either one. Station mode is the familiar role — the device joins an existing network created by a router, the same way your laptop joins your home Wi-Fi. Access point mode flips that around: the Pico W creates its own network that other devices can join directly, useful when there's no existing Wi-Fi available, such as a robot working in a field or gym with no router in range. A common use for access point mode is a captive portal — a small web page a device automatically serves to anyone who joins its network, similar to the login page you see when connecting to hotel or airport Wi-Fi. A Pico W robot might use a captive portal to let you type in your home Wi-Fi's SSID and password the first time you set it up, without needing a computer at all.
Before looking at how these pieces fit together during connection, notice that SSID and credentials happen first (joining the network), while DHCP and the IP address happen second (getting an identity on it) — that ordering is exactly what the next diagram lets you step through.
Diagram: Wi-Fi Connection Process Explorer¶
Run the Wi-Fi Connection Process Explorer MicroSim fullscreen
Wi-Fi Connection Process Explorer (interactive diagram)
Type: interactive-diagram
sim-id: wifi-connection-process-explorer
Library: p5.js
Template: https://github.com/dmccreary/learning-micropython/tree/main/docs/sims/iot-data-flow
Status: Specified
Learning objective: Students will explain (Bloom L2: Understand) the sequence of steps a Pico W follows to join a Wi-Fi network and obtain an IP address.
Canvas: 700x460px default, responsive — recompute step-box positions as fractions of width inside windowResized() so the row of steps reflows to a stacked column below 480px wide.
Layout: a horizontal row (vertical stack on narrow screens) of five connected step boxes with arrows between them: "1. Scan for networks," "2. Send SSID + Wi-Fi credentials," "3. Router accepts device," "4. DHCP assigns IP address," "5. Connected — ready to send data." Boxes 1-2 are tinted raspberry #C2185B (the "joining" phase), boxes 3-5 are tinted circuit green #2E7D32 (the "identity" phase), visually grouping SSID/credentials separately from DHCP/IP address.
Controls: a createButton() labeled "Step Forward" that advances a highlighted marker one box at a time, and a createButton() labeled "Reset" that returns the marker to box 1. A createSlider() labeled "Auto-Play Speed" (range 0 = off to 5 = fast) auto-advances the marker when non-zero.
Interaction: clicking any step box (in addition to using the buttons) jumps the marker directly to that box and opens an infobox below the diagram with a one-sentence definition of the term involved, matching the definitions given in the surrounding chapter text (e.g., clicking box 4 shows the DHCP definition). Only one infobox is open at a time.
Implementation: p5.js. Store the five steps as an array of objects {label, phase, definition}. Track currentStep as state; redraw all boxes each frame with the active one outlined in a brighter stroke. Use rectangle bounds-checking in mousePressed() for hit-testing. Parent the canvas to the enclosing <div> per project convention.
Berry's Tip
Never type your real Wi-Fi password directly into a script you plan to share or push to GitHub. Keep credentials in a separate file that stays off of version control, and import them into your main program instead. A leaked password is a berry bad way to end an otherwise great project.
Talking Over the Network: Sockets, HTTP, and a Simple Web Server¶
Once the Pico W has an IP address, it's a full participant on the network — but it still needs a way to actually exchange data with another device. That low-level exchange happens through socket programming: writing code that opens a two-way communication channel, called a socket, between two devices identified by an IP address and a port number. A socket is the fundamental building block underneath nearly every kind of network communication, including the two you'll use most in this chapter.
The most common way two devices exchange structured data over a network is the HTTP protocol (HyperText Transfer Protocol) — the same protocol your web browser uses every time it loads a page. HTTP defines a simple back-and-forth pattern: a client sends an HTTP request — a message asking for something, containing a method like GET or POST and a target address — and the server replies with an HTTP response — a message containing a status code (like 200 for success) and the requested data. A web server is a program that listens for incoming HTTP requests and sends back HTTP responses, and a Pico W can run a tiny one of its own using nothing more than the socket programming shown below.
Before that code, two more terms are worth defining, since real Pico W web servers rely on both. A REST endpoint is a specific URL a web server recognizes as a request for a particular piece of data or action — /sensor/distance and /led/on could each be separate endpoints on the same tiny server. Data sent between endpoints is usually formatted using JSON data format (JavaScript Object Notation), a lightweight, human-readable text format for structuring data as key-value pairs, such as {"distance_cm": 12.5} — easy for both a Python program and a web browser to parse.
The code below opens a socket, binds it to port 80 (the standard HTTP port), and waits for a single connection at a time. socket.socket() creates the socket object itself. bind(addr) claims that port on every network interface the device has ("0.0.0.0" means "any interface"). listen(1) tells the network stack to allow one pending connection to queue up while the loop is busy. accept() pauses the program until a client connects, then returns a new socket dedicated to that one conversation along with the client's address. recv(1024) reads up to 1024 bytes of the incoming HTTP request, and send() transmits a properly formatted HTTP response back to the client.
import socket
addr = socket.getaddrinfo("0.0.0.0", 80)[0][-1]
server = socket.socket()
server.bind(addr)
server.listen(1)
while True:
client, client_addr = server.accept()
request = client.recv(1024)
response = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"distance_cm\": 12.5}"
client.send(response)
client.close()
Before the diagram below, remember what each side of this exchange is doing: a browser or phone sends an HTTP request naming a REST endpoint, and the Pico W's tiny web server sends back an HTTP response carrying JSON data — that request/response round trip is exactly what the next diagram lets you trace step by step.
Diagram: HTTP Client-Server Request/Response Explorer¶
Run the HTTP Client-Server Request/Response Explorer MicroSim fullscreen
HTTP Client-Server Request/Response Explorer (interactive infographic)
Type: interactive-infographic
sim-id: http-client-server-explorer
Library: p5.js
Template: https://github.com/dmccreary/learning-micropython/tree/main/docs/sims/iot-data-flow
Status: Specified
Learning objective: Students will analyze (Bloom L4: Analyze) the structure of an HTTP request and its matching HTTP response as they travel between a client and a Pico W web server.
Canvas: 700x420px, responsive — two labeled boxes ("Client: browser or phone" and "Pico W: web server") positioned at left and right on wide screens, stacked top and bottom below 520px wide, recalculated inside windowResized().
Layout: an animated message bubble travels from the Client box to the Server box labeled with the HTTP request's method and REST endpoint (e.g., "GET /sensor/distance"), pauses briefly at the Server box, then a second bubble travels back labeled with the HTTP response's status code and a short JSON snippet (e.g., "200 OK — {\"distance_cm\": 12.5}").
Controls: a createSelect() dropdown labeled "Choose Endpoint" with three preset options (/sensor/distance, /led/on, /status), each producing a different request/response pair; a createButton() labeled "Send Request" that triggers the animation for the selected endpoint; a createSlider() labeled "Animation Speed."
Interaction: clicking the request bubble mid-flight pauses the animation and opens an infobox explaining the HTTP request's method and target endpoint in plain language; clicking the response bubble does the same for the status code and JSON payload. Clicking the Client or Server box itself shows a one-sentence reminder of what a web server or REST endpoint is, matching the chapter's definitions.
Implementation: p5.js, message bubble position interpolated linearly between the two box centers over a duration controlled by the speed slider, using lerp() on progress from 0 to 1. Store the three endpoint presets as an array of {endpoint, method, statusCode, json} objects. Hit-test bubble clicks using distance-to-bubble-center comparisons against a fixed bubble radius.
Berry's Gentle Warning
The tiny web server above has no security at all — anyone on the network can hit its REST endpoints. That's fine for a classroom demo on a trusted network, but never expose a Pico W's raw web server directly to the open internet without adding authentication first.
A Lighter-Weight Option: MQTT Publish/Subscribe¶
HTTP works well when one device asks another for something specific, but it's a poor fit for a robot that wants to broadcast a sensor reading every second to whoever happens to be listening. The MQTT protocol (Message Queuing Telemetry Transport) was designed for exactly that situation: it's a lightweight messaging protocol built for small, low-power devices sending frequent, small updates over an unreliable network.
MQTT works through a middleman rather than a direct connection. An MQTT broker is a server that receives messages from devices and forwards them to any other device that has asked to receive them — no device ever contacts another device directly. Messages are organized by an MQTT topic: a labeled channel, written like a file path (for example, stem/robot1/distance), that groups related messages together so a device only receives the topics it cares about. This arrangement is called the publish-subscribe model: one device publishes a message to a topic, and any number of other devices that have subscribed to that topic receive a copy, without the publisher needing to know who — or how many devices — are listening.
The code below publishes a single sensor reading to a broker using the umqtt.simple library. MQTTClient("pico-w-robot", "broker.example.com") creates a client object, naming this device "pico-w-robot" (so the broker can tell it apart from other connected devices) and pointing it at the broker's network address. connect() opens the connection to that broker. publish(topic, message) sends the given message as a message on the given topic — both arguments are given as byte strings, shown here with the b prefix. disconnect() closes the connection cleanly when the device is done.
from umqtt.simple import MQTTClient
client = MQTTClient("pico-w-robot", "broker.example.com")
client.connect()
client.publish(b"stem/robot1/distance", b"12.5")
client.disconnect()
Berry's Key Insight
Publish-subscribe is event-driven programming again, just spread across a network instead of living inside one device. A subscriber's code doesn't poll the broker asking "anything new yet?" — it registers interest in a topic once, and the broker triggers it the moment a matching message arrives, the same way an interrupt from Chapter 1 triggers code the instant an event happens.
Now that both protocols have been explained, the table below summarizes when each one is the better fit.
| HTTP | MQTT | |
|---|---|---|
| Communication pattern | Client asks, server answers (request/response) | Publisher sends, broker forwards to any subscribers |
| Best for | Fetching or sending one specific piece of data on demand | Frequent small updates broadcast to multiple listeners |
| Connection style | Opens and closes a connection per request | Stays connected, sending many messages over time |
| Overhead per message | Higher — full request and response headers each time | Lower — designed for small, low-power devices |
| Typical use in this book | A phone's browser checking a robot's status page | A robot streaming sensor readings to a dashboard |
Diagram: MQTT Publish-Subscribe Simulator¶
Run the MQTT Publish-Subscribe Simulator MicroSim fullscreen
MQTT Publish-Subscribe Simulator (MicroSim)
Type: microsim
sim-id: mqtt-publish-subscribe-simulator
Library: p5.js
Status: Specified
Learning objective: Students will understand (Bloom L2: Understand) how a publisher, an MQTT broker, and one or more subscribers exchange messages organized by topic.
Canvas: 700x480px, responsive via windowResized() recalculating the three-column layout as fractions of width, collapsing to a stacked single column below 500px wide.
Layout: three columns — "Publishers" on the left (two icons, one Pico W robot and one classroom sensor), "MQTT Broker" in the center (a single labeled hub icon), and "Subscribers" on the right (three icons: a phone, a laptop dashboard, and a second robot). Each publisher and subscriber has a small colored tag showing which topic it publishes to or is subscribed to, chosen from stem/robot1/distance, stem/robot1/battery, and stem/room/temperature.
Controls: a createSelect() dropdown per publisher icon (two total) letting a student choose which topic that publisher sends to; a createButton() labeled "Publish Message" per publisher that fires an animated message packet toward the broker; checkboxes (via createCheckbox()) next to each subscriber letting a student toggle which topic(s) that subscriber listens to.
Interaction: when a publisher fires a message, it animates from the publisher icon to the broker, then the broker fans out a copy of that message only to subscriber icons currently subscribed to the matching topic — those copies animate onward to the matching subscribers while non-matching subscribers stay idle, making the topic-based filtering visible. Clicking the broker icon opens an infobox reminding the student that the broker never contacts a device that hasn't subscribed. Clicking any topic tag shows the topic string being used.
Implementation: p5.js. Represent topic subscriptions as a simple object per subscriber, e.g. {distance: true, battery: false, temperature: true}, checked against the topic of a fired message to decide which fan-out animations to launch. Animate packets with linear interpolation between fixed icon coordinates recalculated on resize.
Real-World Networking: Latency, Loss, and Range¶
Wireless networks never behave as cleanly as the diagrams above suggest, and every project in this chapter runs into the same three practical limits. Network latency is the delay between sending a message and it arriving at its destination — even a fast Wi-Fi network has some latency, and a robot waiting on a delayed "stop" command can travel farther than expected before it reacts. Packet loss happens when some of the data sent over a network never arrives at all, usually from interference or a weak signal, forcing the software to detect the gap and decide whether to resend. Wireless range is the maximum distance a device can move from its access point or peer before the signal becomes too weak to maintain a reliable connection — walls, metal objects, and other wireless devices can all shrink it well below its advertised maximum.
These three limits matter most for a robot, since it's the one hardware tier in this book that moves. A robot that relies on live network commands needs to handle latency, tolerate occasional packet loss gracefully (never assume every message arrives), and stay within wireless range of its controller.
Diagram: Network Reliability Simulator¶
Run the Network Reliability Simulator MicroSim fullscreen
Network Reliability Simulator (chart)
Type: chart
sim-id: network-reliability-simulator
Library: Chart.js
Status: Specified
Learning objective: Students will analyze (Bloom L4: Analyze) how increasing distance between a robot and its access point affects network latency and packet loss.
Canvas: 700x420px responsive line chart with two y-axes — left axis "Latency (ms)," right axis "Packet Loss (%)" — and x-axis "Distance from Access Point (meters), 0-30." Chart.js responsive: true and maintainAspectRatio: false so the chart resizes with its container.
Controls: a createSlider() (rendered as an HTML range input alongside the chart, range 0-30, default 5, labeled "Robot Distance (m)") that moves a vertical marker line across the chart to the current distance value; a createSelect() labeled "Environment" with options "Open room," "Walls between," and "Crowded Wi-Fi," each swapping in a different pre-computed latency/packet-loss curve to illustrate how obstacles and interference shrink effective wireless range.
Interaction: hovering (or tapping, on touch devices) any point on either curve shows a Chart.js tooltip with the exact latency and packet-loss values at that distance. Moving the distance slider updates a small readout below the chart: "At 12 m in a Crowded Wi-Fi environment: ~85 ms latency, ~4% packet loss." The three environment curves use visually distinct colors matching the book's palette (open room: circuit green #2E7D32; walls: copper gold #D4AF37; crowded Wi-Fi: raspberry #C2185B).
Implementation: Chart.js line chart with two Y scales (yLatency and yLoss) and three pre-defined datasets (arrays of 31 points, one per meter, generated from a simple increasing curve formula rather than live physics). The distance slider updates a Chart.js annotation or a manually drawn vertical line plugin. Register a resize listener that calls the chart's resize() method so the canvas stays responsive inside its container.
Keeping the Network Safe¶
A device that can send and receive data over the open air also needs to be defended, and two related ideas cover the basics every project in this book should follow. Firewall basics describes the general idea of a firewall: a system that filters incoming and outgoing network traffic based on rules, blocking connections that don't match anything expected — most home routers include one by default, quietly rejecting unsolicited traffic from the internet before it ever reaches your Pico W. Network security is the broader set of practices that keep a network and its devices safe from unauthorized access, including strong Wi-Fi passwords, keeping software updated, and — as mentioned earlier — never hardcoding credentials into code you share publicly.
None of the projects in this book need enterprise-grade security, but a few habits go a long way:
- Use WPA2 or WPA3 encryption on any Wi-Fi network a project connects to — never an open, password-free network for anything beyond a quick demo.
- Keep the tiny web server example from earlier in this chapter on a trusted local network, not exposed to the public internet.
- Store Wi-Fi credentials and MQTT broker addresses in a separate file kept out of version control, as Berry's tip mentioned earlier.
- Treat any unexpected connection attempt to a classroom robot's web server as worth investigating, not ignoring.
Bluetooth Low Energy: Short-Range, Low-Power Communication¶
Wi-Fi is built for connecting to a network — usually one with internet access behind it. But two robots sitting next to each other don't need a whole network; they just need to talk directly, briefly, and without draining their batteries. Bluetooth Low Energy (BLE) is a short-range wireless technology designed for exactly that: low power consumption, modest data rates, and connections measured in meters rather than the wider reach of Wi-Fi.
BLE communication starts before any connection exists. BLE advertising is the process where a device regularly broadcasts a small packet announcing its presence and what it offers, without yet being connected to anything — similar to a vendor at a market calling out what they're selling before anyone walks up. Once another device notices that advertisement and connects, the two devices take on different roles. A BLE peripheral is the device being connected to — it advertises, then waits, and typically has limited power (a sensor, a robot). A BLE central is the device that scans for advertisements and initiates the connection — typically a phone, computer, or another more capable device.
Once connected, a BLE peripheral organizes the data it offers using two more structures. A BLE service is a named collection of related data and functions a peripheral exposes — a robot might expose a "Motor Control" service and a separate "Battery Status" service. Inside each service, a BLE characteristic is an individual piece of data or a controllable value, such as "left motor speed" or "battery percentage," that a central device can read, write, or subscribe to for updates. For a connection to exchange anything beyond public advertising data, many devices also require a pairing process — a one-time exchange that establishes trust and, often, an encryption key between two specific devices, so future connections don't need to repeat that setup.
Before the diagram below, notice how these terms nest inside each other: a peripheral offers one or more services, and each service contains one or more characteristics — that hierarchy is exactly what the next diagram makes explorable.
Diagram: BLE GATT Structure Explorer¶
Run the BLE GATT Structure Explorer MicroSim fullscreen
BLE GATT Structure Explorer (graph data model)
Type: graph-data-model
sim-id: ble-gatt-structure-explorer
Library: vis-network
Status: Specified
Learning objective: Students will analyze (Bloom L4: Analyze) how a BLE peripheral organizes the data it exposes into services and characteristics, and how a central device connects to access them.
Canvas: 700x480px vis-network graph, responsive — call network.fit() inside a window.addEventListener('resize', ...) handler so the graph re-centers and rescales to its container.
Layout: a hierarchical vis-network graph with a "BLE Central (phone)" node at the top, connected by a labeled edge "connects to" down to a "BLE Peripheral (robot)" node. The peripheral node branches to two service nodes, "Motor Control Service" and "Battery Status Service," each colored circuit green #2E7D32. Each service branches further to its own characteristic nodes, colored copper gold #D4AF37: Motor Control Service branches to "Left Motor Speed" and "Right Motor Speed"; Battery Status Service branches to "Battery Percentage." The Central and Peripheral nodes are colored raspberry #C2185B and drawn larger than the service/characteristic nodes.
Interaction: clicking any node opens an infobox below the graph with a one-sentence definition matching the chapter's prose (e.g., clicking "Left Motor Speed" explains that a characteristic is an individual readable/writable value). Hovering any edge shows a vis-network tooltip describing the relationship ("connects to," "offers," "contains"). A small "Simulate Pairing" button (native HTML button, styled to match the book's theme) animates a brief highlight pulse traveling from Central to Peripheral along the "connects to" edge, representing the one-time pairing process described in the chapter text, then settles into a steady highlighted connection state.
Implementation: vis-network with a hierarchical layout option (direction top-down). Node and edge data defined as vis-network DataSet objects. Register a click event to populate the infobox from a lookup table keyed by node id. The pairing animation can be implemented by temporarily updating the edge's width and color properties on a setTimeout sequence, then reverting to a steady highlighted style.
Now that Wi-Fi and BLE have both been explained, the table below compares them directly, since choosing between them is a decision every wireless project in this book has to make.
| Wi-Fi | Bluetooth Low Energy | |
|---|---|---|
| Typical range | Tens of meters, extended by routers/repeaters | A few meters to roughly 30 meters, line-of-sight dependent |
| Power use | Higher — fine for a plugged-in or well-charged robot | Very low — designed for coin-cell and small battery devices |
| Needs a router/broker? | Yes, for internet or MQTT access | No — devices can connect directly |
| Best for | Internet access, web dashboards, MQTT telemetry | Two nearby devices exchanging small amounts of data |
| Used in this book for | HTTP requests, MQTT publish/subscribe | Peer-to-peer swarm robot communication |
Berry's Tip
A handy way to remember the difference: reach for Wi-Fi when your project needs the internet, and reach for BLE when it just needs to whisper to a nearby friend. Plenty of great projects in this book use both at once — Wi-Fi to report status to a dashboard, and BLE to coordinate with another robot right next to it.
Robots Talking to Robots: Peer-to-Peer and Swarm Communication¶
Most of the communication patterns so far have involved a client and a server, or a publisher and a broker — some kind of go-between. BLE also supports a more direct pattern: peer-to-peer communication, where two devices exchange data directly with each other as equals, without going through a router, broker, or central server at all. Two Pico W robots can use BLE peer-to-peer communication to compare sensor readings, agree on which one moves first, or share a simple "found the wall" signal — all without any Wi-Fi network in range.
That direct device-to-device pattern is the foundation of swarm robotics: a field of robotics where many simple robots coordinate their behavior through communication with each other, producing complex group behavior — following, spreading out, taking turns — that no single robot could plan on its own. A full swarm robotics implementation belongs to a companion volume in this series (STEM Robots), but the wireless building blocks covered in this chapter — BLE peripheral and central roles, services, and characteristics — are exactly what a swarm project would use to let robots detect and talk to each other.
You've Got This!
If your first attempt at a BLE connection times out, or your MQTT messages seem to vanish into the void, that's completely normal — wireless bugs are some of the trickiest to debug because you can't see the radio waves. Fall back on root cause analysis from Chapter 1: check one link in the chain at a time (power, pairing, topic name, broker address) instead of guessing at all of them at once.
Everything in this chapter also enables one more idea that ties it together: a remote control interface — any system, whether a web page, phone app, or dashboard, that lets a person send commands to a device over a network instead of a wired connection. A robot's tiny HTTP web server from earlier in this chapter, with REST endpoints like /motor/forward and /motor/stop, is a remote control interface once a simple web page or phone app is built to call those endpoints. The same idea works over MQTT (publishing to a stem/robot1/command topic) or BLE (writing to a "Motor Control" characteristic) — the specific protocol changes, but the goal is the same: letting a human direct a robot without a cable in the way.
Bringing It Together¶
You've now given your Pico W projects a voice. A robot that used to need a USB tether can report its sensor readings over MQTT, serve a status page over HTTP, or trade messages directly with a nearby robot over BLE — and you understand the real-world limits of latency, packet loss, range, and security that come with all of it. The next chapters shift to a completely different hardware tier: the Raspberry Pi 500+, a full Linux computer rather than a microcontroller, where these same networking ideas reappear at a larger scale — SSH instead of a serial cable, a full desktop instead of a REPL, and a much more capable machine to build on.
You Unlocked a Superpower!
That's berry impressive — you just cut the cord for good! Wi-Fi, HTTP, MQTT, and Bluetooth Low Energy are now all part of your toolkit, and every future robot you build can talk to the world without a wire in sight. STEM is our superpower! Let's build something — see you in Chapter 11!