The W in Pico 2 W
The silver box next to the antenna of the Pico 2 W is its wireless chip, the CYW43439: Wi-Fi and Bluetooth in one. The RP2350 talks to it over GP23, GP24, GP25 and GP29, which are not on the board's edge, so every pin you can reach stays free. Its Wi-Fi is 2.4 GHz only (a network that only sends on 5 GHz stays invisible) and IPv4 only. PicoRuby's library is named after the chip: CYW43. Join the simulated network chunkynet, password chunkybacon:
require "cyw43"
# the country decides which radio channels are allowed
CYW43.init("CH")
# station mode: join a network (not be one)
CYW43.enable_sta_mode
ok = CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
puts "connected: #{ok}"
puts CYW43.tcpip_link_status_name
CYW43.ipv4_address
The last argument of connect_timeout is the timeout in seconds: PicoRuby 4.0.3's C code multiplies it by 1000, so an example that passes 10_000 waits almost three hours. The address comes from the simulated router (192.168.4.23 is the simulation's choice). When it fails, connect_timeout does not answer false: it raises CYW43::ConnectTimeout. A wrong password (in the simulation it gives up after one and a half seconds; a real chip may keep trying until the timeout):
require "cyw43"
CYW43.init("CH")
CYW43.enable_sta_mode
begin
CYW43.connect_timeout("chunkynet", "streaky bacon",
CYW43::Auth::WPA2_AES_PSK, 10)
rescue CYW43::ConnectTimeout => e
"no Wi-Fi: #{e.message}"
end
On R2P2 the password does not go into app.rb. The shell command nmcli asks for the country, the network and the password and writes them to /etc/network/wifi.yml, the password encrypted with a key made from the board's own serial number (Machine.unique_id), so the file is useless on another board. At start-up R2P2 joins the network by itself. The cells here keep the password in the code because it opens nothing but a pretend router.
Now the internet. Net::HTTP.get takes the server with its scheme and a path, and answers the body as a String. Mind the https://: without it PicoRuby speaks plain HTTP, even on port 443. The rubygems.org API tells you about a gem:
require "cyw43"
require "net/http"
require "json"
CYW43.init("CH")
CYW43.enable_sta_mode
CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
# with https:// in front, or it is plain HTTP
body = Net::HTTP.get("https://rubygems.org", "/api/v1/gems/rake.json")
info = JSON.parse(body)
"#{info["name"]} #{info["version"]}"
This Net::HTTP is no stand-in: it is PicoRuby's own library (picoruby-net-http 4.0.3), running here unchanged. Only the layer beneath it is simulated: the socket hands the request to your browser, which fetches it for real. When the server cannot be reached, the simulation answers with a copy saved when the lesson was written, and the Wi-Fi card on the bench says so ("canned").
Next, the weather from Open-Meteo, which needs no key. One thing found in PicoRuby's source: in 4.0.3 Net::HTTP.get_response returns the connection, not the response, so take the long way with Net::HTTP.new, use_ssl = true and get, then finish: get opens the connection but does not close it, and a Pico that asks every few minutes would soon run out of memory. And look closely at the body:
require "cyw43"
require "net/http"
CYW43.init("CH")
CYW43.enable_sta_mode
CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
path = "/v1/forecast?latitude=47.37&longitude=8.54" +
"¤t=temperature_2m,weather_code,wind_speed_10m"
# the long way: get_response gives no response in 4.0.3
http = Net::HTTP.new("api.open-meteo.com", 443)
http.use_ssl = true
res = http.get(path)
http.finish # closes the connection
puts res.code
puts res["transfer-encoding"]
puts res.body
The body starts with a short line like b5, and more such lines sit in the middle of the JSON. Open-Meteo sends its answer chunked (Transfer-Encoding: chunked): in pieces, each after a line with its size in hexadecimal, and a 0 at the end. A browser or CRuby puts the pieces back together. PicoRuby 4.0.3's Net::HTTP hands them on as they are, and JSON.parse fails on them. (The size of each piece is the simulation's; the real server picks its own.)
The fix is a small helper in the tab dechunk.rb. This tab is yours: you can change it, and it is saved with your code. It checks whether the first line is hex digits byte by byte, not with a regexp, because PicoRuby in the browser uses JavaScript's regexps, which have no \A (the real Pico's regexp engine has it). Byte by byte works on every PicoRuby:
require "cyw43"
require "net/http"
require "json"
require "dechunk"
CYW43.init("CH")
CYW43.enable_sta_mode
CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
path = "/v1/forecast?latitude=47.37&longitude=8.54" +
"¤t=temperature_2m,weather_code,wind_speed_10m"
http = Net::HTTP.new("api.open-meteo.com", 443)
http.use_ssl = true
res = http.get(path)
http.finish
# dechunk comes from the tab dechunk.rb
now = JSON.parse(dechunk(res.body))["current"]
"#{now["temperature_2m"]} C, wind #{now["wind_speed_10m"]} km/h"
A weather dashboard
All of it together: Wi-Fi, HTTPS, JSON and the e-paper from lesson 99. The weather_code is a WMO code: 0 and 1 are clear, 45 and 48 fog, 51 to 67 drizzle and rain, 71 to 77 snow, from 80 showers and thunderstorms. The icon is drawn from lines and rectangles. The time is UTC, because the request asks for no time zone:
require "cyw43"
require "net/http"
require "json"
require "spi"
require "epd2in13"
require "dechunk"
CYW43.init("CH")
CYW43.enable_sta_mode
CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
path = "/v1/forecast?latitude=47.37&longitude=8.54" +
"¤t=temperature_2m,weather_code,wind_speed_10m"
http = Net::HTTP.new("api.open-meteo.com", 443)
http.use_ssl = true
res = http.get(path)
http.finish
now = JSON.parse(dechunk(res.body))["current"]
# WMO weather code: 0 clear ... 95 thunderstorm
wmo = now["weather_code"]
spi = SPI.new(unit: :RP2040_SPI1, frequency: 4_000_000,
sck_pin: 10, copi_pin: 11)
epd = EPD2in13.new(spi: spi, cs_pin: 9, dc_pin: 8,
rst_pin: 12, busy_pin: 13)
epd.clear
epd.text(6, 6, "Zurich", scale: 2)
epd.text(6, 32, "#{now["temperature_2m"]} C", scale: 4)
epd.text(6, 76, "wind #{now["wind_speed_10m"]} km/h", scale: 2)
epd.text(6, 104, "#{now["time"]} UTC")
cx = 205
case wmo
when 0, 1
# a sun: a round disc of lines, and eight rays
(-9..9).each do |d|
w = d.abs > 5 ? 14 - d.abs : 9
epd.line(cx - w, 40 + d, cx + w, 40 + d)
end
rays = [[0, -1], [1, -1], [1, 0], [1, 1],
[0, 1], [-1, 1], [-1, 0], [-1, -1]]
rays.each do |dx, dy|
epd.line(cx + dx * 14, 40 + dy * 14, cx + dx * 22, 40 + dy * 22)
end
when 45, 48
# fog: four grey lines
4.times { |i| epd.line(cx - 25, 28 + i * 8, cx + 25, 28 + i * 8) }
else
# a cloud, with rain or snow under it
epd.rect(cx - 25, 38, 50, 16, fill: true)
epd.rect(cx - 13, 27, 24, 12, fill: true)
if (51..67).include?(wmo) || wmo >= 80
5.times { |i| epd.line(cx - 20 + i * 10, 58, cx - 24 + i * 10, 68) }
elsif (71..77).include?(wmo)
5.times { |i| epd.rect(cx - 21 + i * 10, 62, 3, 3, fill: true) }
end
end
epd.refresh
Small memory, big answers
A Pico 2 W has 520 KB of memory, and JSON.parse builds the whole tree of an answer in it. So ask an API for little: current= asks Open-Meteo for three values, a few hundred bytes. For a big answer PicoRuby has JSON::Digger, which picks one value out of the text without building the rest. Try it in the cell above:
JSON::Digger.new(dechunk(res.body)).dig("current", "temperature_2m").parse And use_ssl = true encrypts the connection. Whether the Pico also checks the server's certificate is another matter: on RP2040 and RP2350, ca_file= is not supported, and a certificate authority has to be stored in flash and given to the connection with set_ca.
Wi-Fi needs a Pico 2 W with the R2P2-PICORUBY firmware from picoruby.org. The official firmware for the plain Pico runs on a Pico W too, but without the radio; a Pico W with Wi-Fi needs a firmware you build yourself. Connect with the R2P2 web terminal, run nmcli once and give it your country, network and password. Then app.rb can leave out the lines with CYW43: R2P2 is connected before it starts your program. Copy epd2in13.rb, font5x7.rb and dechunk.rb to /lib. Your router has to offer 2.4 GHz.
https://rubygems.org/api/v1/gems/rake.json and show rake and its newest version, for example rake 13.4.2, on the e-paper. The cell already joins the network and sets up paper.require "cyw43"
require "net/http"
require "json"
require "spi"
require "epd2in13"
CYW43.init("CH")
CYW43.enable_sta_mode
CYW43.connect_timeout("chunkynet", "chunkybacon",
CYW43::Auth::WPA2_AES_PSK, 10)
spi = SPI.new(unit: :RP2040_SPI1, frequency: 4_000_000,
sck_pin: 10, copi_pin: 11)
paper = EPD2in13.new(spi: spi, cs_pin: 9, dc_pin: 8,
rst_pin: 12, busy_pin: 13)
paper.clear
# fetch https://rubygems.org/api/v1/gems/rake.json and show
# "rake <version>" on the paper, then refresh
Ideas for a Pico 2 W on your desk, each a free API that needs no key:
- Gem watcher with a light: ask every hour and blink the LED from lesson 96 when the version changes.
/api/v1/versions/rake/latest.jsonis an even smaller answer. - Weather clock: the dashboard above every 15 minutes (Open-Meteo's
currentvalues change that often), with a partial refresh and a full one every hour. - Next train:
transport.opendata.ch/v1/stationboard?station=Zürich&limit=3, the next departures from a Swiss station. The answer is big: dig into it withJSON::Digger. - Where is the ISS?
http://api.open-notify.org/iss-now.json(plain HTTP, about a hundred bytes): a dot on a small world map. - Star counter: the stars of
api.github.com/repos/picoruby/picorubyas a needle on a servo, which PWM from lesson 98 drives.
PicoRuby also has libraries for NTP time (picoruby-net-ntp) and for MQTT (picoruby-net-mqtt), for a clock that sets itself or a doorbell that sends a message.