How to set WiFi programmatically on Raspberry Pi

Yiqiang Zhao
2 min readNov 22, 2019

--

This tutorial will show you how to set up WiFi programmatically on Raspberry Pi.

In many cases when we using a Raspberry Pi, we may not have the keyboard, mouse or monitor. We access it through ways such as SSH, VNC etc. But before use that, if you need to update the OS or some packages, or even get the IP address before using the SSH connection, you get to connect to the Internet first. In other ways, maybe you just prefer the command-line interface rather than the graphic interface.

Here is the solution:

First, make sure you already have a connection with your Raspberry Pi.

Open the Terminal and type:

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

This is to open the wpa_supplicant.conf file by nano editor. After opening the file, you’ll see something like this:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

We’ll add your WiFi configuration based on this.

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=XX
network={
ssid="xxxxx"
psk="xxxxx"
}
  1. Here, country=XX is the WiFi country code. It’s really important otherwise sometimes you can’t access the WiFi. For example, I’m based in UK, so I’ll type country=GB.
  2. In the parenthesis of network block. the string of the “ssid=” is your WiFi name, and the string of the “psk=” is your WiFi password.
  3. ps: In many cases, you may use a public WiFi which don’t need password. It just read your MAC address, store in their system and you can access the Internet. You may need to go to your WiFi provider’s page register an account and manually add your Raspberry Pi’s MAC address into their database. After doing that, in the network block, your just type:
network={
ssid=“publicWiFi”
key_mgmt=NONE
}

That’s it. Here is our example:

ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=GB
network={
ssid="myWifi"
psk="12345654321"
}

then ctrl+X and Y save the file.

sudo reboot now

reboot the OS and you could check the Internet by some simple ping in Terminal:

ping 1.1.1.1

If you see some information about the connection such as :

64 bytes from 1.1.1.1: icmp_seq=0 ttl=61 time=4.709 ms

64 bytes from 1.1.1.1: icmp_seq=1 ttl=61 time=3.217 ms

It means you can access the Internet.🤘

(You can check my last tutorial that connects Raspberry Pi Zero with a Mac by just a single micro-USB cable.)

Thanks for reading!

--

--

Yiqiang Zhao

PhD candidate at the University of Edinburgh. Architect🏛, iOS developer🖥, environment science tutor👨🏻‍🏫.