PiTFT – Load the desktop with a physical button (startx)

I recently discovered the PiTFT screen, a 2.5″ TFT screen from Adafruit that sits on top of a Raspberry Pi. You can send it images, video, or set it up as a desktop environment. This became immediately appealing as I realised I could setup the pi as a webserver for my home automation, and load the browser fullscreen to interact with it. Oh yeah, it has a touchscreen, making interacting with the interface really nice.

pitft2

One small issue it getting the screen to start a desktop. You have 2 options:

  1. Start the pi, connect to ssh and type startx
  2. Start the pi and make the default desktop the tft (meaning no output anymore on hdmi)

Neither of these are great, one involves having to login every boot, the other means you don’t get your regular desktop over hdmi.

Enter option 3!

Boot normally, but map one of the physical buttons on the front of the PiTFT to the startx command. This means you have your normal desktop environment over hdmi for everyday stuff, but with 1 button press you have enabled your mini TFT, and can start using it as an interface.

I have installed a webserver locally, and am using the screen to interact with a mini web app I created for home automation.

So, how do we map the button?

First step is to create yourself a python script with the button logic

sudo nano ~/button.py

Copy this code in

import time
import RPi.GPIO as GPIO
import subprocess 

def main():

    # tell the GPIO module that we want to use the 
    # chip's pin numbering scheme
    GPIO.setmode(GPIO.BCM)

    # setup pin 23 as an input
    GPIO.setup(23,GPIO.IN)

    while True:
        if GPIO.input(23):
             # the button is being pressed, so startx
             subprocess.call("FRAMEBUFFER=/dev/fb1 startx", shell=True)

        time.sleep(0.1)

    GPIO.cleanup()

if __name__=="__main__":
    main()

Save that (control o, y, control x)

Then make sure its executable

sudo chmod +x ~/button.py

We can test it by running

sudo ./button.py

You should see the desktop boot to the TFT screen when you press the button on the far left.

But we can do better, we can have it run at boot!

sudo nano /etc/rc.local

Just before exit 0 add the following line

python /home/pi/button.py

Save, reboot, and now button 1 will start x on your new TFT.

1 Comments

  1. Elmer

    Thank you! Got it assigned to my second button now, have power on/off button on button 1.

    Good guide! 🙂

    //Elmer

Leave a Reply

Your email address will not be published. Required fields are marked *