Have you wondered how to code in C on your Raspberry Pi? Well today we are going to show you how to write a C program on a Raspberry Pi running in headless mode, that is the Raspberry Pi is only connected to WiFi and power, no keyboard or monitor. Programming on C on a normal Raspberry Pi is quite straightforward, you can just install VSCode and program away. However on a headless install like the one I set up in the video linked in the cards above, it makes things a little more complicated as we have no direct access to the machine, only over SSH.
Command Line Method
sudo nano hello-world-cmd.c
The following simple hello world code is used:
#include <stdio.h>
int main(){
printf("Hello from the command line! \n");
return 0;
}
The next three lines of commands are used to compile and run the program we just wrote:
gcc hello-world-cmd.c -o hello-world-cmd
chmod +x hello-world-cmd
./hello-world-cmd
However, this method of writing a C code over an SSH connection is not great for anything more than a few lines of code! That’s where VSCode is going to come in.
VSCode Setup
On your local machine, open VSCode. Follow the following steps to set-up the device:
- Install Remote Development Extension
- Open command pallet (ctrl+shift+p) and select “SSH Add new host”, type ssh then your username at the Pi’s IP address. Eg: ssh pi@192.168.1.200 hit enter and then enter again.
- Open command pallet and select “SSH Connect to Host”. Select your raspberry Pi’s IP address.
- Select linux as the platform then enter your password when prompted.
- Install c/c++ extension on the SSH device. Press the install on SSH:192.168.X.X.
- Open the explorer panel and select open folder. Open your user folder when prompted (this may reload VSCode).
- Create a new file (hello-world-vscode.c) and copy the same code as used above in the basic hello world tutorial. Save the file.
- Build the file using ctrl+shift+B then selecting “gcc Build Active Task”.
- In the terminal tab run the file using the command: ./hello-world-vscode
We now have VSCode configured so you can program in C on your headless raspberry pi!
Took a while to follow you through the Windows set up and run parts, but I finally got it. Whew!
Thanks, just what I needed.
Love what you are doiing with the site.
Feel free to edit the “doiing”. ha