Controlling RaspberryPi GPIO through python script

This post is intended to help beginners for getting started with GPIOs in RaspberryPi. RaspberryPi boards having newer version of Raspian OS running may have already installed libraries for working with GPIOs.

RaspberryPi_Logo

 

Raspberry-Pi-GPIO

If you need to install the required libraries from scratch connect your network cable to raspberryPi and type the following commands in the terminal of RaspberryPi.

sudo apt-get update
sudo apt-get install python-dev
sudo apt-get install python-rpi.gpio

Note: running the above commands need internet connectivity.

Next create a file named gpiotest.py and type the following code in it.

import RPi.GPIO as GPIO

# use P1 header pin numbering convention
GPIO.setmode(GPIO.BOARD)

# Set up the GPIO channels - one input and one output
GPIO.setup(11, GPIO.IN)
GPIO.setup(12, GPIO.OUT)

# Input from pin 11
input_value = GPIO.input(11)

# Output to pin 12
GPIO.output(12, GPIO.HIGH)

# The same script as above but using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN)
GPIO.setup(18, GPIO.OUT)
input_value = GPIO.input(17)
GPIO.output(18, GPIO.HIGH)

Save and run the code by typing the follow in terminal

Note: The picture describing the GPIO in this post GPIO.BCM type numbering scheme.

sudo python gpiotest.py

Connect an LED to GPIO18 and see the LED turned on.

 

Advertisements

One thought on “Controlling RaspberryPi GPIO through python script

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s