Plotting real-time data from Arduino using Python

The below Arduino sketch reads the values from analog pins A0 and A1 and prints it to the serial port.
This is the code

void setup()
{
  Serial.begin(9600); 
}

void loop()
{
  // read A0
  int val1 = analogRead(0);
  // read A1
  int val2 = analogRead(1);
  // print to serial
  Serial.print(val1);
  Serial.print(" ");
  Serial.print(val2);
  Serial.print("\n");
  // wait 
  delay(50);
}

The serial port sends values in this format

Screenshot--dev-ttyUSB5

Using python and Matplotlib am plotting this data as a function of time.I wanted to display this as a scrolling graph that moves to the right as data keeps coming in. For that, I am using the Python deque class to keep and update a fixed number of data points for each time frame.

import sys, serial
import numpy as np
from time import sleep
from collections import deque
from matplotlib import pyplot as plt

# class that holds analog data for N samples
class AnalogData:
  # constr
  def __init__(self, maxLen):
    self.ax = deque([0.0]*maxLen)
    self.ay = deque([0.0]*maxLen)
    self.maxLen = maxLen

  # ring buffer
  def addToBuf(self, buf, val):
    if len(buf) < self.maxLen:
      buf.append(val)
    else:
      buf.pop()
      buf.appendleft(val)

  # add data
  def add(self, data):
    assert(len(data) == 2)
    self.addToBuf(self.ax, data[0])
    self.addToBuf(self.ay, data[1])
    
# plot class
class AnalogPlot:
  # constr
  def __init__(self, analogData):
    # set plot to animated
    plt.ion() 
    self.axline, = plt.plot(analogData.ax)
    self.ayline, = plt.plot(analogData.ay)
    plt.ylim([0, 1023])

  # update plot
  def update(self, analogData):
    self.axline.set_ydata(analogData.ax)
    self.ayline.set_ydata(analogData.ay)
    plt.draw()

# main() function
def main():
  # expects 1 arg - serial port string
  if(len(sys.argv) != 2):
    print 'Example usage: python showdata.py "/dev/tty.usbmodem411"'
    exit(1)

 #strPort = '/dev/tty.usbserial-A7006Yqh'
  strPort = sys.argv[1];

  # plot parameters
  analogData = AnalogData(100)
  analogPlot = AnalogPlot(analogData)

  print 'plotting data...'

  # open serial port
  ser = serial.Serial(strPort, 9600)
  while True:
    try:
      line = ser.readline()
      data = [float(val) for val in line.split()]
      #print data
      if(len(data) == 2):
        analogData.add(data)
        analogPlot.update(analogData)
    except KeyboardInterrupt:
      print 'exiting'
      break
  # close serial
  ser.flush()
  ser.close()

# call main
if __name__ == '__main__':
  main()

The program must be run in this format

python showdata.py /dev/ttyUSB5

Instead of ttyUSB5 add your ttyUSB device.And this is how the plot looks like.

Screenshot-Figure 1

Happy Hacking 🙂

Send TV Remote signal using Arduino

First decode the tv remote and get the hex code for each button..This code will do that…

#include 

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}

void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}

Copy the codes for the button say for channel up is 80BFA15E…ok to send this code connect an IR Led to pin no 3..

ir

 

Check whether the remote model is NEC or SONY and use this code to send the value

#include <IRremote.h>

IRsend irsend;
const int buttonPin = 2; // the number of the pushbutton pin
//const int ledPin = 3;
int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
// pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {

buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
irsend.sendNEC(0x80BFA15E, 32);
}

}

Now when the button is pressed the channel will change..If the remote is sony then use irsend.sendSony…

 

 

Happy Hacking 🙂

Arduino IR Remote identification

Download IR remote library from the following link

https://github.com/shirriff/Arduino-IRremote

Unzip the download.Rename it as IRremote and put it in arduino’s libraries folder.

To detect the remote

ir1

Set up a TSOP sensor like the above schematic…

Load the example code from File -> Examples -> IRremote -> IRrecvDemo then click the “Upload” button.Click the “Serial Monitor” button to bring up a window that will allow us to see the codes being returned to us by the Arduino. Start mashing buttons and you should see a lot of numbers scroll by like in the image below.

Screenshot-dev-ttyACM1

The ones that start off with FF and then have numbers or letters are the codes we are after. A FFFFFFFF is a continuation code and the 0 on its own line is a read error.

Happy Hacking 🙂

Proocessing to Arduino commnication

The following code describes how processing to arduino serial communication can be done…processing to arduino communication is very helpful when kinect is used along with processing..

Processing code

import processing.serial.*;
Serial port;

void setup() {
size(256, 150);

println("Available serial ports:");
println(Serial.list());

port = new Serial(this, Serial.list()[0], 9600);

}

void draw() {
// draw a gradient from black to white
for (int i = 0; i < 256; i++) {
stroke(i);
line(i, 0, i, 150);
}

// write the current X-position of the mouse to the serial port as
// a single byte
port.write(mouseX);
}

Serial.list()[0] uses the first port in this list (number 0) and aud used is 9600 if you know the port you can give it directly..

Arduino code

const int ledPin = 12;

void setup()
{

Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}

void loop() {
byte brightness;

if (Serial.available()) {

brightness = Serial.read();
if(brightness > 100){

digitalWrite(ledPin,HIGH);
}
else{
digitalWrite(ledPin,LOW);
}
}
}

First upload the arduino code connect an led to pin no 12 then run the processing code a window will open with black and white gradient..if you move the cursor to white or above 100 then the led becomes high..

Happy Hacking 🙂

Fixing arduino stk500_recv(): programmer is not responding error

Screenshot from 2012-12-13 12:19:59

avrdude: stk500_recv(): programmer is not responding

In Debian squeeze and Ubuntu you may get an error like this while trying to upload your program…..To fix this error

First install arduino software with all its dependencies from the package manager

sudo apt-get install arduino arduino-core

Next, we’ll get a compatible (2.2pre2-3 or newer) version of librxrt-java to allow Java to handle the I/O (rx/rt);

you can check the files at this link

http://ftp.debian.org/debian/pool/main/r/rxtx/

Now download the file

wget http://ftp.debian.org/debian/pool/main/r/rxtx/librxtx-java_2.2pre2-11_i386.deb
sudo  dpkg  -i  librxtx-java_2.2pre2-11_i386.deb

Now add yourself to the ‘dialout’ group:

sudo adduser `whoami` dialout

and log out and log back in, or reboot.  This is necessary for access to the serial (USB) port.

download the Arduino software, with it’s recent 1.0 release, from the Arduino.cc website.

We extract that software, enter the folder, and run the software:

tar -xvzf  arduino-1.0-linux.tgz
cd arduino-1.0/
./arduino

Plug in your Arduino board via USB to your computer, wait a few seconds to register the new device, and again launch the Arduino software:

 ./arduino

Go to the Tools menu, Board submenu, and select whatever your board is
Finally, again click the Tools menu, Serial Port submenu, and select correct device.

Now try uploading….. 🙂
Happy Hacking 🙂