Using GPIO with Python

This image of QNX for Raspberry Pi is preloaded with the Python3 interpreter, so it is ready to run your scripts out of the box. The content on this page will assume you are familiar with at least the basics of Python development, and will focus instead on how to work with Python projects on QNX.

There is a much more detailed walkthrough of Python development in the ebook "Introduction to the QNX OS with Raspberry Pi" linked in the Projects repo.

Working with Python programs

To execute a Python program on your Pi, the process is the same as any other system:

qnxuser@qnxpi:~$ python3 myprogram.py

If you are coding your program directly on the Pi, this is enough. If you are coding on a host and want to execute your program on Pi target, you can either copy the file(s) to the Pi and then run the program, or you can execute it remotely.

Copy and run a program from the command line

Assume we are working with myprogram.py and we are storing our Python project in the ~/python directory on our QNX target. For the default user qnxuser the full path is /data/home/qnxuser/python/myprogram.py or, using an abbreviated notation, ~/python/myprogram.py. If this directory does not yet exist, log into your Raspberry Pi and create it with the mkdir ~/python command.

If you write the code directly on the Raspberry Pi, or if you use SSHFS to mount a directory from the Raspberry Pi into your image, then you're ready to go. On the other hand, if you saved it on your development host computer then it needs to be copied to the Raspberry Pi:

user@host:~$ scp myprogram.py qnxuser@qnxpi:python/

You can now invoke the Python interpreter to run the program. If you haven't done so already, log into the Raspberry Pi with SSH and type the following commands:

qnxuser@qnxpi:~$ cd ~/python
qnxuser@qnxpi:~/python$ python3 myprogram.py

Execute a program remotely

While SSH can be used to start a shell on the Raspberry Pi, it can also be used to execute a command remotely. The following commands first copy the file from the computer to the Raspberry Pi, and then run the program:

user@host:~$ scp myprogram.py qnxuser@qnxpi:python/
user@host:~$ ssh -t qnxuser@qnxpi python3 python/myprogram.py
Note:

Make sure to specify -t as part of the SSH command. Without it, the program may continue running on the Raspberry Pi even after the SSH command exits.

Page updated: