Skip to content

Tutorial: How to use your Raspberry Pi like an Arduino

2012 June 15
by Tedb0t

Finally got to experiment with the Raspberry Pi’s GPIO (General Purpose Input/Output) pins.  I tried three methods: Python, Bash and C, and will describe each.  But first, here’s some setup information.

  • Connecting to the RPi’s GPIO header: I used an old floppy disk drive IDE ribbon cable.  It has 34 pins, but the RPi’s header is only 26 pins, so part of the connector is unused. I soldered some breadboard-friendly header pins onto the other end, which is working pretty well so far. Bear in mind that some IDE cables may be more complicated than they look. Before powering anything up, make sure you check that each conductor is indeed separate and you’re not accidentally grounding or shorting anything. You can always make your own by getting some 26-conductor IDC connectors and using a vice to crimp it onto a piece of ribbon cable.
     
  • Pin Connections: …are confusing! There’s a master table here, and a diagram here.  Looking at the diagram, my breakout header starts with 3.3V and moves left to right, top to bottom.  Here are the pin connections from my header as pictured:
    • Pin 2: 5V
    • Pin 3: “GPIO0″. Connected to one end of the switch (the other end is connected to ground, since this GPIO pin has an internal pull-up resistor.  This means that when the switch is not closed, the pin reads as “High,” and when closed, “Low.”
    • Pin 6: GND (note that it’s jumpered to my ground rail on my breakout board)
    • Pin 7: “GPIO4″. The anode of the LED through a 220-ohm resistor.
  • I’ll use this breakout board setup for all the following examples.  Different libraries/tools use different pin numbers, adding to the confusion, so I’ll try to clear it up.  Also note that I’m doing this through an SSH session, so there’s no monitor attached to the RPi. See my beginning instructions here if you don’t already have an SSH connection to your Pi.
  • Important Note: The RPi Wiki takes pains to remind you that these GPIO pins are unbuffered and unprotected, so if you short something out, you could fry your whole Pi, so be careful!  There are a number of other breakout boards being developed that should make this safer.
  • Important Note: Any program that accesses the GPIO pins must be run as root, so if you get an error, remember to “sudo” your command.
  • Python: One of my preferred languages, so I figured I’d try it out. First, install pip (Python package installer):
    • sudo curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
    • Next, install the RPi.GPIO Python module:
    • sudo pip install rpi.gpio
    • Now, you can enter the python interpreter (sudo python) and do stuff like:
    • import RPi.GPIO as GPIO
      GPIO.setup(7, GPIO.OUT)
      GPIO.output(7, True)
      GPIO.output(7,False)
  • Bash: Something I’ve always loved about Unix is the idea that everything is a file.  On the Raspberry Pi, the GPIO pins are files too! With the pictured breadboard setup, we can do the following to turn the LED on and off (note that this uses the “BCM” pin numbering but the breadboard stays the same!):
    • (You can’t just put sudo before each command because the second command that the output is directed to would not be run as root. So, for simplicity, we drop into root first.)
      sudo su -
      echo "4" > /sys/class/gpio/export
      echo "4" > /sys/class/gpio/export
      echo "out" > /sys/class/gpio/gpio4/direction
      echo "1" > /sys/class/gpio/gpio4/value
      echo "0" > /sys/class/gpio/gpio4/value
    • To read from an input, ‘cat’ it like any other file!
      echo "0" > /sys/class/gpio/export
      echo "in" > /sys/class/gpio/gpio0/direction
      cat /sys/class/gpio/gpio0/value
  • C: Good old C.  The native example for C is really hairy, but luckily a plucky fellow named Gordon wrote an Arduino-like library just for the Raspberry Pi!  Here’s what you need to do:
    • Download and install the library:
      cd /tmp
      wget http://project-downloads.drogon.net/files/wiringPi.tgz
      
      tar xfz wiringPi.tgz
      cd wiringPi/wiringPi
      make
      sudo make install
      cd ../gpio
      make
      sudo make install
    • Your Pi’s system now has the wiringPi library installed, so we can write a little program that uses it.
      cd ~
      nano blink.c
    • Type or paste in this program:
    • And compile it:
      cc -o blink blink.c -L/usr/local/lib -lwiringPi
    • And run it:
      sudo ./blink
    • You should have a happily blinking LED. Yay! Now for something more interesting:
  • Where’s my analogRead?  Sadly, unlike an Arduino, the RPi doesn’t have an onboard ADC (Analog to Digital Converter). However, some of the breakout boards being designed will include an external ADC, such as the Gertboard.  You can add your own external ADC, such as this one, by using the SPI bus on the RPi (the MOSI, MISO and SCK pins).
  • That’s all for now! Hope this helps, and as always, let me know if it works or you run into any problems.

Related Posts:


54 Responses leave one →
  1. bnewbold permalink
    June 15, 2012

    I believe the reason that sudo doesn’t work for the “echo” commands is that you are sudo-ing the echo command but not the bash pipe redirect:

    $ sudo echo “hello world” > ~root/thing bash: /root/thing: Permission denied

    One way to get around this is with the ‘tee’ command:

    $ echo “hello world” | sudo tee ~root/thing

    I’m curious if there is a more idiomatic method.

  2. Chris permalink
    June 16, 2012

    I run into the same sudo issue when I try to drop the extra memory buffers in Linux. Everything up to the re-direction is run as root, but the pipe or the chevron breaks it into a new command, run my myself instead of root. tee is the way to go, as bnewbold stated.

  3. Joonas Pihlajamaa permalink
    June 19, 2012

    Nice post! Have you yet found out the performance specs of the RaspPi GPIO – i.e. what kind of frequencies and bandwith can be achieved for example when compared to 8-bit microcontrollers which often lack the clock cycles for anything above 1-2 MHz?

    By the way, I’ve recently done a level shifting article that may be useful to those wanting to protect their 3.3V RaspPis:

    http://codeandlife.com/2012/04/06/level-shifting-101/

    • RayZ permalink
      January 5, 2013

      they have them on youtube at 100 mhz playing fm radio.

  4. Wouter permalink
    June 22, 2012

    Is it possible to communicate with a webserver?

  5. Jean-Damien POGOLOTTI permalink
    June 23, 2012

    You’re missing to include stdlib.h in the C example code. Compiling will fail on the exit() statement. (using the std debian image)

  6. Jeremy permalink
    June 27, 2012

    Can the GPIO pins generate a PWM signal for controlling things like hobby/rc servos?

  7. minimdr permalink
    July 5, 2012

    Could this code be used with my Raspberry PI? It is running on an Arduino board to control leds on a reef tank.
    Thanks

    byte MoonPhase()

    {

    int m,d,y;

    int yy,mm;

    long K1,K2,K3,J,V;

    byte PWMvalue;

    m = month();

    d = day();

    y = year();

    yy = y-((12-m)/10);

    mm = m+9;

    if (mm>=12) mm -= 12;

    K1 = 365.25*(yy+4712);

    K2 = 30.6*mm+.5;

    K3 = int(int((yy/100)+49)*.75)-38;

    J = K1+K2+d+59-K3;

    V = (J-2451550.1)/0.29530588853;

    V -= int(V/100)*100;

    V = abs(V-50);

    PWMvalue = 4*abs(50-V); // 5.12=100% 4=~80%

    //pinMode(lowATOPin,OUTPUT);

    return (PWMvalue*100)/255;

    }

    It
    returns 0-100.

    You
    can comment the kast line and return PWMvalue for 0-255.

  8. Gordon permalink
    July 6, 2012

    Hi,

    Good article and thanks for the link to wiringPi!

    But can I make a suggestion or 2 :)

    wiringPi is currently under constant development and the one you’ve linked to is a bit old now (well, old as in a few weeks, but things change quickly here!)

    So – the instructions really ought to be:

    cd /tmp
    wget http://project-downloads.drogon.net/files/wiringPi.tgz

    tar xfz wiringPi.tgz
    cd wiringPi/wiringPi
    make
    sudo make install
    cd ../gpio
    make
    sudo make install

    If you stick to just using the wiringPi.tgz filename, it will always pull the latest version down.

    And there’s also a separate GPIO program – the GPIO program allows you to do GPIO operations from the command-line without needing to be root!

    So:

    gpio -g mode 18 pwm
    gpio -g pwm 18 750

    (range is 0-1023)

    Additionally, I recently added features into it to allow the export/unexport from the command-line
    too (again without the need to be root), so it’s worthwhile checking for updates.

    Thanks,

    -Gordon

    • Ted Hayes permalink
      July 6, 2012

      Thanks! I updated the instructions. Any chance you might host the code on github? :)

  9. flo35 permalink
    July 12, 2012

    Hi,

    In my case, i connect a button on 26 pin.

    The state of button isn’t always good (True / false)
    I have connect a pull-up resistor beetween 3,3V pin and 26 pin.
    I resolve my problem :)

    am i alone with this bug ? i have a raspberry pi model B
    my debian distribution ?

    • flo35 permalink
      July 12, 2012

      For information : It’s OK Now, commit/update
      RPi.GPIO 0.2.0 -> RPi.GPIO 0.3.1a :) with pull-up internal

      • Ted Hayes permalink
        July 12, 2012

        WIthout the pull-up (or pull-down) resistor, the pin is said to be “floating.” It will have spurious voltages due to surrounding electromagnetic fields, which is why you get an unreliable reading.

  10. evollidaw permalink
    July 28, 2012

    Great tutorial, thanks!

  11. Michael permalink
    August 8, 2012

    I have some old I/O cards laying around, and the parallel port ribbon cable is a perfect fit for the GPIO headers. This also gives a nice option of putting the Pi in a case and having the DB-25 female connector on the other end to give easy access to GPIOs (and put those old printer cables to some use).

  12. August 25, 2012

    Hi!
    I have problem, I have no pip command, but python is there, any ideas? Thanks
    Eugene

  13. August 25, 2012

    Hi!

    I get error message

    building ‘RPi.GPIO’ extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c source/py_gpio.c -o build/temp.linux-armv6l-2.7/source/py_gpio.o
    source/py_gpio.c:23:20: fatal error: Python.h: No such file or directory
    compilation terminated.
    error: command ‘gcc’ failed with exit status 1

    on sudo pip install rpi.gpio

    Any ideas? Thanks

  14. Victor permalink
    September 26, 2012

    thanks for your post. Its being helpful for my work. I’m having some problems.

    Everything it’s running ok until I try to compile it, then I receive lots of errors.

    blink.c: 33.1: error: stray ‘302’ in program
    blink.c: 33.1: error: stray ‘240’ in program
    blink.c: 33.1: error: stray ‘302’ in program

    and so on.

    Some one can help me?

    Thanks

    • Jason Hoffman permalink
      October 7, 2012

      I had the same error. What’s happening is that when you cut and paste the code into the nano editor it’s reading odd carriage returns from the web browser into nano. Just load the blink.c program into nano again and delete the carriage return from before each line then hit return and it should insert a correct return. Do this with every line and those should go away when you compile.

      • Victor permalink
        October 10, 2012

        thanks, i have wrote it from the beginning and the problem has gone. It was what you have said.

        thanks

  15. dchurch permalink
    October 13, 2012

    It might be worth mentioning that the default Wheezy image doesn’t include setuptools.
    #
    Resolve this by doing:

    sudo apt-get install python-setuptools

    before the ‘curl’ command.

  16. floid permalink
    October 21, 2012

    I just received my new 512 Pi. I’m able to compile the code with no errors, but my LED doesn’t work. I can make it go on and off using the bash commands, so I know the wiring is correct. I even added an extra printf within the loop and the loop is working. I just can’t get the LED to do anything with the C examples. Please help…

    Thanks.

  17. Ignacio permalink
    November 7, 2012

    Hi, I’m thinking to buy an arduino leonardo, but recently I have discoverd raspberry pi. Can I do the same with an arduino than a Raspberry pi?, obiously raspberry pi is a computer and I supose that the probabilities are more biggest. Thanks.

  18. December 22, 2012

    Sweet!

  19. dougm permalink
    January 23, 2013

    Another quick note, I deduced from bnewbold’s post below that everything after a pipe wasn’t run with root permissions. The problem I was having was that python wasn’t able to create directories. So I switched from this:

    sudo curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python

    to this

    sudo curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | sudo python

    and it worked better.

    DougM

  20. michel permalink
    January 31, 2013

    Hi,
    i hope you can help me with this issue.
    I’m using the Python example and it all works great.
    Now i’m also trying to run the python script from PHP, but then the import statement can not be resolved. Is that something you have seen before?

  21. beginner permalink
    February 18, 2013

    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_write_byte’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_read_byte’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_write_byte_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_write_word_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_read_word_data’
    /usr/lib/gcc/arm-linux-gnueabi/4.6/../../../libwiringPi.so:undefined reference to `i2c_smbus_read_byte_data’
    collect2: ld returned 1 exit status
    make: *** [gpio] Error 1
    Do you know what this error means? I get it when i run “make” in /tmp/wiringPi/gpio folder.

    • Andrew Hazlett permalink
      April 3, 2013

      Has anyone figured out what is going on when this error happens?

      • OldMercenary permalink
        April 5, 2013

        Same, getting this error too.

        • David Blackburn permalink
          April 22, 2013

          It seems to have gone wrong in the make for wiringPi where ther are warnings of “implicit declaration of function” for all the items for which there are undefined references. Maybe a source file or include has gone missing?

          • Haolde permalink
            June 11, 2013

            There seems to be a minor error in the makefile (or build script), thus a warning about the missing libi2c-dev may not always be issued. Go ahead and read the file “build”, follow the instructions to apt-get install the lib and do not forget to make clean. After that, a fresh build will recompile the wiringPi files with libi2c-support, and subsequently gpio will link alright.
            Hope you will get along, I went thru this the hard way too ;-)

    • lol permalink
      April 22, 2013

      the libwiringPi.so seg faults when u try to run it by itself

  22. Senthir permalink
    May 1, 2013

    Check out how to orderly shut down your Raspberry Pi using the GPIO and a hard drive jumper:

    http://www.raspberrypi.org/phpBB3/viewtopic.php?f=37&t=42449

  23. Scott permalink
    July 15, 2013

    Just wanted to thank you for doing this. I was able to get the LED blinking and wanted to show my appreciation that you took the time to explain what you did. Thank you.

  24. Ian permalink
    November 17, 2013

    Looking at the other comments, this probably sounds stupid, but where’s the tutorial? My computer is just showing the name of the article, the author, and the comment section, etc.

  25. sim permalink
    November 20, 2013

    I can’t find the tutorial too… help please

Trackbacks and Pingbacks

  1. MAKE | How-To: GPIO on Raspberry Pi
  2. How-To: GPIO on Raspberry Pi | Indoor Digital Billboards
  3. Using the GPIO pins on a Raspberry Pi - Hack a Day
  4. IO Pin Control « Raspberry Pi Projects
  5. My experience with the Raspberry Pi |
  6. Raspberry Pi, como comecei (conversa de café) – blog (arquivo) do nsa
  7. How to use your Raspberry Pi like an Arduino
  8. How to use your Raspberry Pi like an Arduino — Arduino Passion
  9. Anonymous

Leave a Reply

Note: You can use basic XHTML in your comments. Your email address will never be published.

Subscribe to this comment feed via RSS