Simple ADC with Raspberry Pi using MCP3008

Hello!

So for my own benefit, here’s the steps you need to take to get analog inputs working with a Raspberry Pi.

I’m grabbing most of this from: http://scruss.com/blog/2013/02/02/simple-adc-with-the-raspberry-pi/

The first thing you’ll need is an MCP3008. Using jumper wires, hook it up to your pi using this diagram.

Power your RPi up and run the following commands to get it all set up.

First thing’s first, you’ll need to enable SPI in the kernel so:

sudo vi /etc/modprobe.d/raspi-blacklist.conf

Comment out the spi-bcm2708 line so it looks like this:

#blacklist spi-bcm2708

Then run this to make it more permanent.

sudo modprobe spi-bcm2708

Now for the real meat of it. You’ll need these packages for SPI and the WiringPi library makes things a whole lot easier for us.

sudo apt-get install python-imaging python-imaging-tk python-pip python-dev git
sudo pip install spidev
sudo pip install wiringpi

Now everything should be good to go, now for the python.

You can debug this any way you like, but my favorite way to do it is using the program geany. I like to start up a VNC server with root so I don’t get into any trouble with the GPIO permissions.

But here’s the program.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import spidev
import time

spi = spidev.SpiDev()
spi.open(0, 0)
count = 0

def readadc(adcnum):
# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1, 8 + adcnum << 4, 0])
    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout

while True:
    tmp1 = int(round(readadc(0)/10.24))
    print "in1:",tmp1
    count = count +1
    time.sleep(0.2)

And that’s pretty much it, the result should look something like this:

There you go!

Plane | Working handshake code demo

First off, here’s a video:

If you’re a long time follower of the blog, than you may notice that it looks like I’m backtracking here. Let me go over the differences between the two systems I’ve developed.

The one I “finished” a few months ago can be found here. While the code is “good” and it works well for what it does, there are a few inherent problems with it. The first being that it has to have a computer to be used. The second being that the computer running the intermediate program has to be extremely fast, so it’s not totally feasible for field use. It would also be very hard for it to go wireless, but I had built that groundwork in so it could happen.

The one I’m working on now doesn’t require a computer as an intermediate, and is going to be totally wireless as from the start.

This morning I finished the handshake data exchange over xbee. Right now it’s just dimming a few LED’s but if you take a peek at the following code, it’s very expandable.

Here’s the working code:

 

#include <SoftwareSerial.h>
SoftwareSerial xbee_serial(2, 3); 
#include <string.h> // we'll need this for subString
#define MAX_STRING_LEN 20 // like 3 lines above, change as needed. 

int in_LED = 10;
int out_LED = 11;

int input = 2;

int sendval;


//serial stuff
const char EOPmarker = '.';  //This is the end of packet marker
char serialbuf[32]; //This gives the incoming serial some room. Change it if you want a longer incoming.

void setup(){
  pinMode(in_LED, OUTPUT);
  pinMode(out_LED, OUTPUT);
  pinMode(input, INPUT);
  
  Serial.begin(9600);
  xbee_serial.begin(9600);
  
  xbee_serial.print("0,0,0."); // this is very important as it starts of the loop because it makes "xbee_serial.avalible() > 0. 
}

void loop(){
  if (xbee_serial.available() > 0) { 
    static int bufpos = 0;
    char inchar = xbee_serial.read();
      if (inchar != EOPmarker) { 
        serialbuf[bufpos] = inchar; 
        bufpos++; 
      }
      else {
        serialbuf[bufpos] = 0; //restart the buff
        bufpos = 0; //restart the position of the buff

        Serial.println(atoi(subStr(serialbuf, "," , 1)));
        analogWrite(in_LED, atoi(subStr(serialbuf, "," , 1)));
        
         sendval = map(analogRead(input), 0, 1023, 0, 255);
         xbee_serial.print(sendval); // Value that it sends over the serial
         xbee_serial.print(",");
         xbee_serial.print("100"); //This second byte is for the purpose of the program, it is not being used. 
         xbee_serial.print("."); //EOP marker
         analogWrite(out_LED , sendval);
        
    }
  }
  
  //delay(10);
}

char* subStr (char* input_string, char *separator, int segment_number) {
 char *act, *sub, *ptr;
 static char copy[MAX_STRING_LEN];
 int i;
 
 strcpy(copy, input_string);
 
for (i = 1, act = copy; i <= segment_number; i++, act = NULL) {
 
 sub = strtok_r(act, separator, &ptr);
 if (sub == NULL) break;
 }
 return sub;
}

Plane | Working Handshake Code

This works so I want to write it down:

 

#include <SoftwareSerial.h>
SoftwareSerial xbee_serial(2, 3); 
#include <string.h> // we'll need this for subString
#define MAX_STRING_LEN 20 // like 3 lines above, change as needed. 

int in_LED = 10;
int out_LED = 11;

int input = 2;

int sendval;


//serial stuff
const char EOPmarker = '.';  //This is the end of packet marker
char serialbuf[32]; //This gives the incoming serial some room. Change it if you want a longer incoming.

void setup(){
  pinMode(in_LED, OUTPUT);
  pinMode(out_LED, OUTPUT);
  pinMode(input, INPUT);
  
  Serial.begin(9600);
  xbee_serial.begin(9600);
  
  xbee_serial.print("0,0,0.");
}

void loop(){
  if (xbee_serial.available() > 0) { 
    static int bufpos = 0;
    char inchar = xbee_serial.read();
      if (inchar != EOPmarker) { 
        serialbuf[bufpos] = inchar; 
        bufpos++; 
      }
      else {
        serialbuf[bufpos] = 0; //restart the buff
        bufpos = 0; //restart the position of the buff

        Serial.println(atoi(subStr(serialbuf, "," , 1)));
        analogWrite(in_LED, atoi(subStr(serialbuf, "," , 1)));
        
         sendval = map(analogRead(input), 0, 1023, 0, 255);
         xbee_serial.print(sendval); // Value that it sends over the serial
         xbee_serial.print(",");
         xbee_serial.print("100"); //This second byte is for the purpose of the program, it is not being used. 
         xbee_serial.print("."); //EOP marker
         analogWrite(out_LED , sendval);
        
    }
  }
  
  delay(10);
}

char* subStr (char* input_string, char *separator, int segment_number) {
 char *act, *sub, *ptr;
 static char copy[MAX_STRING_LEN];
 int i;
 
 strcpy(copy, input_string);
 
for (i = 1, act = copy; i <= segment_number; i++, act = NULL) {
 
 sub = strtok_r(act, separator, &ptr);
 if (sub == NULL) break;
 }
 return sub;
}

Plane | Transmitting Analog Values with Xbee

I made some progress today, here’s a video:

Basically this is a proof of concept. The transmitter is sending a line of data very similar to the one that will be sent by the final controller (as seen in the controller code) the receiving end with be receiving in the same way the vehicle code does (same as above).
Here are a few pictures, this first one is a top down view of my prototyping area:
This second one shows all components involved:
This is the code running on the transmitter side, the side with the pot that’s transmitting it’s analog value:
</div>
<div>

#include <SoftwareSerial.h>
SoftwareSerial xbee_serial(2, 3);

int pot_1 = 0;
int LED_1 = 5; //this will serve as an LED to compare to
int sendval;

void setup(){
 pinMode(pot_1, INPUT);
 pinMode(LED_1, OUTPUT);
 Serial.begin(9600);
 xbee_serial.begin(9600);
}

void loop(){
 Serial.println(analogRead(pot_1));
 sendval = map(analogRead(pot_1), 0, 1023, 0, 255);
 xbee_serial.print(sendval); // Value that it sends over the serial
 xbee_serial.print(",");
 xbee_serial.print("100"); //This second byte is for the purpose of the program, it is not being used.
 xbee_serial.print("."); //EOP marker
 analogWrite(LED_1,sendval);
 //delay(100);
}

This second half is on the receiving end. It may seem way overkill for what it does, but it’s all expandable to a pretty much infinite amount of data to be transmitted. For an example of what it’s capable of see this video:
</div>
<div>

#include <SoftwareSerial.h>
SoftwareSerial xbee_serial(2, 3);
#include <string.h> // we'll need this for subString
#define MAX_STRING_LEN 20 // like 3 lines above, change as needed.

int LED_1 = 5;

int led_val;

//serial stuff
const char EOPmarker = '.'; //This is the end of packet marker
char serialbuf[32]; //This gives the incoming serial some room. Change it if you want a longer incoming.

void setup(){
 pinMode(LED_1, OUTPUT);
 Serial.begin(9600);
 xbee_serial.begin(9600);
}

void loop(){
 if (xbee_serial.available() > 0) {
 static int bufpos = 0;
 char inchar = xbee_serial.read();
 if (inchar != EOPmarker) {
 serialbuf[bufpos] = inchar;
 bufpos++;
 }
 else {
 serialbuf[bufpos] = 0; //restart the buff
 bufpos = 0; //restart the position of the buff

Serial.println(atoi(subStr(serialbuf, "," , 1)));
 analogWrite(LED_1, atoi(subStr(serialbuf, "," , 1)));
 }
 }
}

char* subStr (char* input_string, char *separator, int segment_number) {
 char *act, *sub, *ptr;
 static char copy[MAX_STRING_LEN];
 int i;

 strcpy(copy, input_string);

for (i = 1, act = copy; i <= segment_number; i++, act = NULL) {

 sub = strtok_r(act, separator, &ptr);
 if (sub == NULL) break;
 }
 return sub;

}

Plane | First Functioning Xbee test

So the first round of parts have come in for the plane, including the Xbees and the UartSBee V4s. My life is going to be very scattered over the next 4 or 5 months, so I’m going to be making frequent rudimentary posts for my own benefit.

Here’s a video:

First thing’s first I want to outline how everything’s connected.

The first xbee is connected to the first UartSBee which is connected to an Ardunio Uno which is connected to the first computer which has the console open and is looking at the serial stream at 9600 baud. The xbee is connected to the uno via Software Serial which is detailed in the code below. Here’s a picture:

 

The second setup is identical, except i’m using an Ardunio nano.

Here’s the code, I’m using the SoftwareSerial library to accomplish this. Both Arduinos are running the same thing.

</p>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
 // Open serial communications and wait for port to open:
 Serial.begin(9600);
 while (!Serial) {
 ; // wait for serial port to connect. Needed for Leonardo only
 }
 Serial.println("Goodnight moon!");

// set the data rate for the SoftwareSerial port
 mySerial.begin(9600);
 mySerial.println("Hello, world?");
}

void loop() // run over and over
{
 if (mySerial.available())
 Serial.write(mySerial.read());
 if (Serial.available())
 mySerial.write(Serial.read());
}
<p style="text-align: left;">

Here are a few pictures of the X-TCU setup. The baud is at 9600 and the pan ID is 115. The UartSbee itself is running at 115200 baud connected to the computer.

Thanks for reading!

Raspberry Pi Media Server | Mounting Hard Drive & Better Minidlna Config

Please note that this is more for my sake. To mount a hard drive in raspbian do the following: Make sure you have ntfs-3g installed by running:

sudo apt-get install ntfs-3g

Then mount the drive read/write with the following command:

sudo mkdir /media/USBHDD
sudo mount -t ntfs-3g /dev/sda1/ /media/USBHDD/

And it shout be mounted. /dev/sda1 is the location of your hard drive. Now to configuring minidlna. Location of minidlna.conf file and access command:

sudo vi /etc/minidlna.conf

This is the file I’m running right now. As I type this i’m successfully streaming to my Kindle Fire HD (the reason why I’ve decided to really make this thing work) but I’m not sure if it’s stable. It’s also able to stream to VLC as of now.

Raspberry Pi Media Server | Moving Backwards to go Forwards

It’s time to face facts, minidlna and XBMC won’t run at the same time in Raspbmc. The basic UPNP included in Raspbmc won’t work consistently and Raspmc and is not nearly as stable as minidlna. OpenELEC is fast enough, but does not have the expandability of a full linux OS. I need to restart this project.

 

First thing’s first I’m going to straight up speed this thing up as much as I can. At the base level, this begins with the SD card. I’m going to go from a junk 4gb standard speed SD card to a 8gb SanDisk Ultra 30mb/s SDHC. On this I’m going to install the latest version of Raspian and overclock it to the maximum 1GHz.

 

I’ll keep you posted on how I progress.

Plane | Corrective Balancing Mechanism

First of all, here’s a video of this device in action.

So things are really starting to take shape with the plane (still unnamed…) and I’ve got a really solid framework for an auto-balancing system. Basically the program below maps the x value given from the ADXL335 to a value from 1-180 on the servo. A lot of this code is for debug, but that portion can be switched off.

</pre>
#include <Servo.h>

Servo myservo;

int raw_val;
int ref_val;
int mid_val = 336;

int left_tilt = 260;
int rght_tilt = 405;

int min_switch = 2;
int max_switch = 3;
int mid_switch = 5;
int mode_switch = 4;

int debug_switch = 6;

int bounds_LED = 10;
int mid_LED = 11;

int debug_LED = 7;
int normal_LED = 8;

void setup(){

 pinMode(min_switch, INPUT);
 pinMode(max_switch, INPUT);
 pinMode(mid_switch, INPUT);
 pinMode(debug_switch, INPUT);

 pinMode(mode_switch, INPUT);

 pinMode(bounds_LED, OUTPUT);
 pinMode(mid_LED, OUTPUT);

 pinMode(debug_LED, OUTPUT);
 pinMode(normal_LED, OUTPUT);

 Serial.begin(9600);
 myservo.attach(9);
}

void loop(){
 if (digitalRead(debug_switch) == HIGH) {

 digitalWrite(debug_LED, HIGH);
 digitalWrite(normal_LED, LOW);

 raw_val = analogRead(0);

 if (digitalRead(mode_switch) == HIGH) {

 digitalWrite(bounds_LED, HIGH);
 digitalWrite(mid_LED, LOW);

 Serial.print("BOUNDS MODE: ");

 ref_val = map(raw_val, left_tilt, rght_tilt, 0, 180);

 myservo.write(ref_val);

 if (digitalRead(min_switch) == HIGH){
 Serial.print("LEFT HGH");
 left_tilt = raw_val;
 }

 if (digitalRead(min_switch) == LOW){
 Serial.print("LEFT LOW");
 }

 Serial.print(" , ");

 if (digitalRead(max_switch) == HIGH){
 Serial.print("RGHT HGH");
 rght_tilt = raw_val;
 }

 if (digitalRead(max_switch) == LOW){
 Serial.print("RHGT LOW");
 }

 Serial.print(" , ");

 Serial.print("Left Tilt: ");
 Serial.print(left_tilt);

 Serial.print("Rght Tilt: ");
 Serial.print(rght_tilt);

 }

 if (digitalRead(mode_switch) == LOW) {

 Serial.print("MID MODE:");

 if (digitalRead(mid_switch) == HIGH){
 mid_val = raw_val;
 }

 int MLeft_val = mid_val - 75;
 int MRght_val = mid_val + 75;

 ref_val = map(raw_val, MLeft_val, MRght_val, 0, 180);
 myservo.write(ref_val);

 digitalWrite(bounds_LED, LOW);
 digitalWrite(mid_LED, HIGH);

 Serial.print(" , ");
 Serial.print("Left Most Value: ");
 Serial.print(MLeft_val);
 Serial.print(" , ");
 Serial.print("Rght Most Value: ");
 Serial.print(MRght_val);
 Serial.print(" , ");
 Serial.print(mid_val);

 }
 Serial.print(" , ");
 Serial.print("Raw Value: ");
 Serial.print(raw_val);
 Serial.print(" , ");
 Serial.print("Current Servo Value: ");
 Serial.print(ref_val);

 Serial.println("");
}

 if (digitalRead(debug_switch) == LOW) {

 digitalWrite(debug_LED, LOW);
 digitalWrite(normal_LED, HIGH);

 raw_val = analogRead(0);
 if (digitalRead(mode_switch) == HIGH) {
 digitalWrite(bounds_LED, HIGH);
 digitalWrite(mid_LED, LOW);
 ref_val = map(raw_val, left_tilt, rght_tilt, 0, 180);
 myservo.write(ref_val);
 if (digitalRead(min_switch) == HIGH){
 left_tilt = raw_val;
 }
 if (digitalRead(max_switch) == HIGH){
 rght_tilt = raw_val;
 }
 }

 if (digitalRead(mode_switch) == LOW) {
 if (digitalRead(mid_switch) == HIGH){
 mid_val = raw_val;
 }<a href="https://esologic.com/wp-content/uploads/2012/12/2012-12-27_14-20-51_644.jpg">
</a>
 int MLeft_val = mid_val - 75;
 int MRght_val = mid_val + 75;
 ref_val = map(raw_val, MLeft_val, MRght_val, 0, 180);
 myservo.write(ref_val);
 digitalWrite(bounds_LED, LOW);
 digitalWrite(mid_LED, HIGH);
 }
 }
}

Sorry for the lack of comments in this code, it’s pretty intuitive though, at it’s core its all about the map command.

Here’s a picture of what my desk looks like:


Here’s a picture of the fritzing document, which can be found: here

Thanks for reading!