Tag Archives: Arduino

Raspberry Pi 001: Setup and Run first Arduino-Python project.

Hey. One week ago I receive my Raspberry Pi model B. I order it with a 8GB SD card, with heat sinks (installed on the picture), a USB HUB (quite useful, you are going to need it and the Pi can be powered from it), and a case (which was immediately modded with a Star Trek Decal), and a WiFi and bluetooth USB (remember that Lego NXT now comes with bluetooth, so it can be handy).

2013-10-02 20.29.13

I bought everything from a very nice on-line shop (and quite fast, one day delivery). It’s call ModMyPi. And I don’t know if it is a standard feature or something offered by this shop, but the SD card was already pre charged with the most common Linux OS for Raspberry Pi, so it was quite easy starting for first time.

logo

Ok. So basic things to know about Raspberry Pi. Basically Raspberry Pi is a 30$ computer. That means that it’s able to do most of the things a computer does, but at the same time don’t expect a great performance. It includes an audio output, a HDMI connector for a screen, a mini USB for powering, 2 USB (one for keyboard and one for mouse and… and that’s why you need a USB HUB), an an Ethernet connector.

More basic things.

If you are buying your Raspberry without a precharged Linux OS, you will need to mount a Linux image on the SD card. Is not difficult, but it could become problematic if you don’t know how to do it. In my case, I choose Raspberrian, which was one of the OS precharged.

The Pi doesn’t have an On/Off button, you just plug it in.

If you already have the OS installed in the SD card (assuming that you get the image and run the initial installation). Every time you start your Pi, it will start on the shell, no graphic interface, just the command prompt.

And now some basic commands.

If you are prompted to put an user name and password, they are by default:

User: Pi
Password: Raspberry

2013-10-09 20.34.03
People forget it and tend to panic.

Other very useful thing is that if you have the Pi connected with the Ethernet cable, you can install updates straight away (If this is your first time with Linux this may be new for you). Just execute this 2 commands:

$ sudo apt-get update

$ sudo apt-get upgrade

Basically one command looks for updates on-line in the most common repositories and the other one install that updates.

And now, the command that most of the people will use, it is for starting the graphic interface

$ startx

And this is how it looks in my case.

2013-10-09-193603_1824x984_scrot

Note: For doing screen shots you can use the commands

$ sudo apt-get install scrot

$ scrot -s

The second command is for taking the screen shots (they will be stored in the working directory).

Ok. So those new to Raspberry Pi, it has 3 important things to us.

Midori: Web browser.
LXTerminal: OS Command Shell.
IDLE: Python command shell.

And here ends the basics. Let’s go for Python and Arduino.

First thing, install Arduino IDE (Integrated Development Environment). Something as simple as this.

$ sudo apt-get install arduino

And voilà! we have the Arduino IDE on the menu ready to do any script we want and load it into an Arduino board. Isn’t it great?

I try it with an Arduino Mega board, a led and a variable resistor. The script I made is a rough modification of the blink LED. Basically, the LED will blink every x seconds, where x is the voltage measured through the variable resistor.  And at the same time, that voltage will be written into the Serial Port. Here it is.

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
  This example code is in the public domain.
 */
// Pin 13 has an LED connected on most Arduino boards.
int led = 13;
int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
// the setup routine runs once when you press reset:
void setup() {           
// initialize the digital pin as an output.
  pinMode(led, OUTPUT);  
Serial.begin(9600); //This initialices the USB as a serial port
}
// the loop routine runs over and over again forever:
void loop() {
 sensorValue = analogRead(sensorPin); //Reads the voltage of the resistor.
 Serial.println(sensorValue); //Writes the voltage on the Serial port.
 digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(int(sensorValue/5));               // wait an amount of time set by the resistor
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(int(sensorValue/5));               // wait again
}

And this is the set-up. Quite simple, but enough for the next example. (Note: It is necessary a resistor in series with the LED just in case the current is too high).

2013-10-09 21.20.35

Perfect. So now that the script is loaded into the Arduino, it will run it continuously. I have to point that the Arduino is powered by the Raspberry Pi which is powered by the USB HUB!

Now for Python. Because the Python libraries included in Raspberrian are quite limited, we need to install a few things, and it’s going to take a long time. Basically, we are going to install Scipy, Matplotlib and the libraries for the serial port communication. If you check some of my Python posts, we will see some nice applications for them.

maths with Python

maths with Python 2: Rössler system

maths with Python 3: Diffusion Equation

maths with Python 4: Loading data.

The commands for the OS shell are:

$ sudo apt-get install libblas-dev        ## 1-2 minutes
$ sudo apt-get install liblapack-dev      ## 1-2 minutes
[$ sudo apt-get install python-dev        ## Optional]
[$ sudo apt-get install libatlas-base-dev ## Optional speed up execution]
$ sudo apt-get install gfortran           ## 2-3 minutes
$ sudo apt-get install python-setuptools  ## ?
$ sudo easy_install scipy                 ## 2-3 hours
$ ## previous might also work: python-scipy without all dependencancies
$ sudo apt-get install python-matplotlib  ## 1 hour

And for the serial port we have:

$ sudo apt-get install python-serial

Hey, and now we are ready! Let’s rock.

I prepared a Python script that is going to read a number from the serial port (the number that Arduino is sending), and is going to plot it into a graph in real time. Here is the code:

import numpy

import matplotlib

#Read a value on the serial port and plot it in real time

#Libraries needed

import matplotlib.pyplot as plt

import serial

import pylab

from pylab import *

#Initialize the serial port

ser=serial.Serial('/dev/ttyACM0',9600)

#Clean the data on the serial port .

#This must be performed each time if we are only interested in the most recent value

ser.flush()

ser.flushInput()

ser.flushOutput()

#The data will be stored in these variables.

#Basically, t for time, s for signal an a is for help.

t=[]

s=[]

a=0

#Initialize a figure with axis.

fig=pylab.figure(1)

ax=fig.add_subplot(111)

ax.grid(True)

line1=ax.plot(t,s,'r-')

manager=pylab.get_current_fig_manager()

#This function when called will try to read a value from the Serial port and store it in t and s

def serialget(arg):

    global t,s,a

    ser.flush()

    ser.flushInput()

    ser.flushOutput()

    try:

        s.append(ser.readline())

        t.append(a)

        a=a+1

        print(ser.readline())

    except:

    1 #This is a trick in case of error.

#This function when called will update the graph

def RealtimePloter(arg):

    global t,s,a

    line1[0].set_data(t,s)

    ax.axis([0,len(t),0,800])

    manager.canvas.draw()

#These two timers will call the functions periodically while the script is being executed

timer=fig.canvas.new_timer(interval=10)

timer.add_callback(RealtimePloter,())

timer2=fig.canvas.new_timer(interval=1)

timer2.add_callback(serialget,())

timer2.start()

timer.start()

#This order will make the figure visible.

pylab.show()

And here is the result.

2013-10-09-202855_1824x984_scrot

It has only one problem… a little bit slow updating the plot, but I think is related to the fact that Raspberry Pi has no graphic card!

Hope you like it, and learn something new. Next time more applications.