Removing Crackle from Guitar

guitar pot

Got a cheap fender-like guitar I’ve had a while and it doesn’t always work, I plug it and then it crackles and cuts out frequently and if I turn the dials it also crackles. A friend wanted to use it so I’ve got motivated and I’ve gotten round to fixing it.

These steps apply to most modern guitars – if it’s a vintage you may not want to follow the steps.

It’s very simple to fix the electrics for the average guitar nothing really that concerning and removing the crackle from the pots/ dials is as easy as just buying some cleaner. It really is that easy.

Testing the jack with a mini amp

To test the connections/ circuitry as well as a multimeter I found it really useful to use a mini amp and headphones so I could listen for changes and improvements as I reproduced the fault.

First things first start with the jack and remove this from the guitar to inspect the connections. Should be a couple of screws holding the jack plate in and you’ll need to remove this and then unscrew the jack from the plate – there should be a couple of nuts holding it in place.

Faulty jack - half the problem...

Next have a look for something obvious – in my case the joint just wasn’t soldered properly. I cut the wires, stripped the ends, then resoldered the connections after removing the previous solder (or lack of in this case).

Cut wires from jack and strip wire down

Repaired jack

Moving the jack with the amp and headphones connected, listening now I can see the connection is fixed but turning the pots/ dials I hear the crackling still. The jack is the first place to start for a loose connection but if the problem is not the jack or still persists with an intermittent connection  after you’ve fixed the jack then you have a loose connection elsewhere. Next obvious place to check is the grounding/ earth wire – normally attached in the back of the guitar, there is a plate to remove to access this and the truss rod. Basically you’re looking for a wire that is connected to the guitar itself by way of a plate or something similar.

Check all the connections

If that connection looks fine, next check the connections on each pickup, in cheap guitars these joints can be poorly soldered so check and repair. Lastly check the connections on the switches the wiring isn’t too tricky to check just be methodical.

Hopefully you’ve found your loose connection(s) and fixed them, if not you’ll need to go through each connection with the multimeter. If however you’re now left with a crackle/ static sound anytime you turn a dial or use the pickup selector switch read on.

Removing the crackle
So to remove the crackle when turning the dials etc… Just take the pickguard off, if you haven’t already, by removing the screws around the outside. You’ll need some electrical contact cleaner in a spray can with a straw. You need to have a cleaner that is solvent based but also include lubricant since potentiometers and switches should be greased and not left dry as that will make things worse. I found a can down in my local motor store and any decent electronics store should sell it. Again make sure the spray is a lubricant!

Spray contact cleaner into pots and switches

On each switch or pot spray the cleaner  between the back of the pickgaurd and the dial. Keep you face away as it’s likely to spray back a bit and you dont want this in your eyes! You don’t need much spray just a couple of squirts, when done turn the dials back and forth to work in the cleaner, you should feel an improvement and the dial should feel smoother to turn. Repeat for each pot/ dial. For the pickup selector switch spray into the top of the switch from the front of the pickguard and work the cleaner in by flicking the switch back and forth.

Testing electrics

So now plug in the amp and headphones and listen for the crackle – it should be gone now – good way to test as put a string on the guitar and play it.

Hopefully that’s fixed your issues.

Tenacious D: Classico on the Bass Guitar

Classico on bass

Not so sure I’ve tabbed this 100% but it’s a start, Tenacious D’s Classico for the Bass guitar. Video at the bottom showing it being played.

It’s essentially parts from Bachs Bouree in E Minor, Beethovens Fur Elise and Mozarts Eine Kleine Nachtmusik. I’ve translated the notes as best I can on the bass but let me know if I’ve got it wrong, I’ve also done this in power tab as well here. Click the image below to see it a bit bigger and better quality.

I do apologise for the sound quality in the video below but through decent speakers you can actually hear the bass, shame about the hissing but its a good enough start.

XS750: The Death Machine Cometh

XS750 first run

Wooo! Well after our work with cleaning the carbs and fixing the 2nd gear we got the bike started and it sounds awesome – it also seems to be running fine. As well as clean and refurbish the carburetors we fitted new sparkplugs and a new battery, the old plugs being burnt black and the old battery  was 2 amps under the needed capacity for the bike – that and it was leaking.

It was pretty easy putting the carbs back together and on the bike, most of our day was spent sitting around waiting for the battery to charge and then spending an hour or so trying to get the bike to start – checking the spark, each chamber, the carbs, the timing plate etc… and just dogged peserverance with the belief that it would start eventually.

Anyway thought I would share a video on here of its first time running since we got it 🙂 It sounds amazing… my neighbours will really hate me now.

Still needs some work doing to it though:

The carbs idle settings need to be adjusted, even after warm the bike will stall with the choke fully in. But its good to see that it’s not hunting revs. although the fuel/air mix its drawing may also need looking at since the old spark plugs were black.

The clutch currently has a mind of its own too so it’ll either be a new cable or attempting to fix the current one to make it more responsive.

Brakes work but the fronts a bit too stiff and the rear is a spongy.

Lights currently not working – could be time for the multimeter I think.

Exhaust seals need looking at.

But these are all minor things to fix so hopefully this will get taxed and MoT’d in the next few weeks. After this we can begin looking at customising the bike and refitting the original front wheel and dual discs, new handle bars and moving the pegs further back.

Cleaning and Refurbishing Carburetors (XS750)

XS750 carbs

I guess this works pretty much for all motorcycle carburetors. Take them off and give them a good clean.

The problem with the XS750 is that the previous rider mentioned that when the engine ran it felt a bit lumpy which he suspected the carburetors were causing the issue. Its an old bike and since we were having issues starting the bike it seemed logical that we’d need to check the carbs anyway whilst we waited for parts to arrive.

I’ve moved this to Bikearama.com read it here

Arduino: Controlling the Robot Arm

arduino processing robot arm pt2

So the arm is wired into Arduino as per the previous post, Arduino: Modifying a Robot Arm and hopefully this has worked. In this next part I alter the Arduino sketch slightly and write the first Processing sketch to test control of the arm – video at the bottom.

To control the robot arm we’ll be sending a byte value over the serial port and then reading that in the Arduino code. Depending upon the value sent different motors will be activated.

For the processing sketch I’ve made a few buttons for each motor and also coded the use of the keyboard for another control method. Using either arbitrarily moves the arms motors.

This sketch is the basis for all the further work as well as testing the arm, from this I will move to inverse kinematics as well as programming repeat actions for the arm to perform. Ultimately leading to the arm responding to sensors and other stimuli – eventually! (I have a lot to write up).

For a basic example of working with controlling Arduino using Processing please read my tutorial “Using Processing to Send Values to Arduino” which explains about sending data over the serial port.

The Arduino Sketch
Nothing much has changed from the sketch in the previous post, the main difference is that now you can see we’re reading values from the serial port and acting accordingly. All the logic happens in the Processing code.

/* controls each motor in an Edge Robotic Arm using data sent from 
    a Processing Sketch
    luckylarry.co.uk
 
*/
// set the output pins
// 14-18 are actually analog pins 0-4
int baseMotorEnablePin = 2;
int baseMotorPin1 = 3;                             
int baseMotorPin2 = 4;                           
int shoulderMotorEnablePin = 14;
int shoulderMotorPin1 = 15;                             
int shoulderMotorPin2 = 16; 
int elbowMotorEnablePin = 8;
int elbowMotorPin1 = 9;                             
int elbowMotorPin2 = 10;                           
int wristMotorEnablePin = 5;
int wristMotorPin1 = 6;                             
int wristMotorPin2 = 7; 
int handMotorEnablePin = 11;
int handMotorPin1 = 17;                             
int handMotorPin2 = 18; 
// set a variable to store the byte sent from the serial port
int incomingByte;

void setup() {
  // set the SN754410 pins as outputs:
  pinMode(baseMotorPin1, OUTPUT);
  pinMode(baseMotorPin2, OUTPUT);
  pinMode(baseMotorEnablePin, OUTPUT);
  digitalWrite(baseMotorEnablePin, HIGH);
  pinMode(shoulderMotorPin1, OUTPUT);
  pinMode(shoulderMotorPin2, OUTPUT);
  pinMode(shoulderMotorEnablePin, OUTPUT);
  digitalWrite(shoulderMotorEnablePin, HIGH);
  pinMode(elbowMotorPin1, OUTPUT);
  pinMode(elbowMotorPin2, OUTPUT);
  pinMode(elbowMotorEnablePin, OUTPUT);
  digitalWrite(elbowMotorEnablePin, HIGH);
  pinMode(wristMotorPin1, OUTPUT);
  pinMode(wristMotorPin2, OUTPUT);
  pinMode(wristMotorEnablePin, OUTPUT);
  digitalWrite(wristMotorEnablePin, HIGH);
  pinMode(handMotorPin1, OUTPUT);
  pinMode(handMotorPin2, OUTPUT);
  pinMode(handMotorEnablePin, OUTPUT);
  digitalWrite(handMotorEnablePin, HIGH);
  // start sending data at 9600 baud rate
  Serial.begin(9600);
}

void loop() {
  // check that there's something in the serial buffer
  if (Serial.available() > 0) {
    // read the byte and store it in our variable 
    // the byte sent is actually an ascii value
    incomingByte = Serial.read();
    // note the upper casing of each letter!
    // each letter turns a motor different way.
    if (incomingByte == 'Q') {
    digitalWrite(baseMotorPin1, LOW);   
    digitalWrite(baseMotorPin2, HIGH);  
    } 
    if (incomingByte == 'W') {
    digitalWrite(baseMotorPin1, HIGH);   
    digitalWrite(baseMotorPin2, LOW);  
    }
    if (incomingByte == 'E') {
    digitalWrite(shoulderMotorPin1, LOW);   
    digitalWrite(shoulderMotorPin2, HIGH);  
    } 
    if (incomingByte == 'R') {
    digitalWrite(shoulderMotorPin1, HIGH);   
    digitalWrite(shoulderMotorPin2, LOW);  
    }
    if (incomingByte == 'A') {
    digitalWrite(elbowMotorPin1, LOW);   
    digitalWrite(elbowMotorPin2, HIGH);  
    } 
    if (incomingByte == 'S') {
    digitalWrite(elbowMotorPin1, HIGH);   
    digitalWrite(elbowMotorPin2, LOW);  
    }
    if (incomingByte == 'D') {
    digitalWrite(wristMotorPin1, LOW);   
    digitalWrite(wristMotorPin2, HIGH);  
    } 
    if (incomingByte == 'F') {
    digitalWrite(wristMotorPin1, HIGH);   
    digitalWrite(wristMotorPin2, LOW);  
    }
    if (incomingByte == 'Z') {
    digitalWrite(handMotorPin1, LOW);   
    digitalWrite(handMotorPin2, HIGH);  
    } 
    if (incomingByte == 'X') {
    digitalWrite(handMotorPin1, HIGH);   
    digitalWrite(handMotorPin2, LOW);  
    }
    // if a O is sent make sure the motors are turned off
    if (incomingByte == 'O') {
    digitalWrite(baseMotorPin1, LOW);   
    digitalWrite(baseMotorPin2, LOW);  
    digitalWrite(shoulderMotorPin1, LOW);   
    digitalWrite(shoulderMotorPin2, LOW); 
    digitalWrite(elbowMotorPin1, LOW);   
    digitalWrite(elbowMotorPin2, LOW);  
    digitalWrite(wristMotorPin1, LOW);   
    digitalWrite(wristMotorPin2, LOW); 
    digitalWrite(handMotorPin1, LOW);   
    digitalWrite(handMotorPin2, LOW); 
    }
  }
}

[ad#Google Ad in content]

The Processing Sketch
I’ve drawn some fancy arrows for my buttons in this sketch but otherwise the code is pretty simple – if I press Q or q on the keyboard or if I press an arrow button then send the ascii value of Q (note the uppercase) over the serial port for the Arduino to pick up and turn the motor on. There is nothing here really complicated just a fair few lines of code for the user interface.

/* 
   Processing sketch that send a ascii byte character to Arduino which
   then subsquentally controls a motor
   luckylarry.co.uk
 
*/

// load the serial library for Processing
import processing.serial.*; 
// instance of the serial class
Serial port;
// values to store X, Y for each button
int M1LX, M1RX, M2LX, M2RX, M3LX, M3RX, M4LX, M4RX, M5LX, M5RX;
int M1LY, M1RY, M2LY, M2RY, M3LY, M3RY, M4LY, M4RY, M5LY, M5RY;
// stores the width/height of the box
int boxSize = 64;
// 2 new instances of my arrow class
// also set an array of coordinates for each arrow
arrow myRightArrow;
int[]rightArrowxpoints={30,54,30,30,0,0,30}; 
int[]rightArrowypoints={0,27,54,40,40,15,15};
arrow myLeftArrow;
int[]leftArrowxpoints={0,24,24,54,54,24,24}; 
int[]leftArrowypoints={27,0,15,15,40,40,54};
// set the font
PFont myFont;

void setup()  {
  // screen size of the program
  size(145, 455);
  // set the coordinates of each button box
  // base motor M1LX = Motor 1 Left X  etc..
  M1LX = 5;
  M1LY = 25;
  M1RX = 75;
  M1RY = 25;  
  // shoulder motor
  M2LX = 5;
  M2LY = 115;
  M2RX = 75;
  M2RY = 115;
  // elbow motor
  M3LX = 5;
  M3LY = 205;
  M3RX = 75;
  M3RY = 205;
  // wrist motor
  M4LX = 5;
  M4LY = 295;
  M4RX = 75;
  M4RY = 295;
  // hand motor
  M5LX = 5;
  M5LY = 385;
  M5RX = 75;
  M5RY = 385;
  
  // List all the available serial ports in the output pane. 
  // You will need to choose the port that the Arduino board is 
  // connected to from this list. The first port in the list is 
  // port #0 and the third port in the list is port #2. 
  println(Serial.list()); 
  // set the font to use
  myFont = createFont("verdana", 12);
  textFont(myFont);
  // Open the port that the Arduino board is connected to (in this case #0) 
  // Make sure to open the port at the same speed Arduino is using (9600bps)
  port = new Serial(this, Serial.list()[1], 9600); 
  // create the base arrow
  myRightArrow = new arrow(rightArrowxpoints,rightArrowypoints,7);
  myLeftArrow = new arrow(leftArrowxpoints,leftArrowypoints,7);
}

void draw() 
{ 
  background(0);
  noStroke();
  fill(150);
  // draw each box/ button with a label above each    
  text("Base Motor (Q/W)", 5, 5, 200, 75); 
  text("Shoulder Motor (E/R)", 5, 95, 200, 75);
  text("Elbow Motor (A/S)", 5, 185, 200, 75);
  text("Wrist Motor (D/F)", 5, 275, 200, 75);     
  text("Hand Motor (Z/X)", 5, 365, 200, 75);

  // start looking to see whats pressed and send a value
  // over the serial port
  if(keyPressed) {
    if (key == 'q' || key == 'Q') {
      port.write('Q');
    }
    if (key == 'w' || key == 'W') {
      port.write('W');
    }
    if (key == 'e' || key == 'E') {
      port.write('E');
    }
    if (key == 'r' || key == 'R') {
      port.write('R');
    }
    if (key == 'a' || key == 'A') {
      port.write('A');
    }
    if (key == 's' || key == 'S') {
      port.write('S');
    }
    if (key == 'd' || key == 'D') {
      port.write('D');
    }
    if (key == 'f' || key == 'F') {
      port.write('F');
    }
    if (key == 'z' || key == 'Z') {
      port.write('Z');
    }
    if (key == 'x' || key == 'X') {
      port.write('X');
    }
  } 
  // if no key is pressed check to see if the mouse button is pressed
  else if (mousePressed == true) {
    // check to see if the mouse is inside each box/ button if so send the value
    if (mouseX > M1LX-boxSize && mouseX < M1LX+boxSize && 
      mouseY > M1LY-boxSize && mouseY < M1LY+boxSize) {
        port.write('Q'); 
    } 
    else if(mouseX > M1RX-boxSize && mouseX < M1RX+boxSize && 
      mouseY > M1RY-boxSize && mouseY < M1RY+boxSize) {
        port.write('W'); 
    } 
    else if(mouseX > M2LX-boxSize && mouseX < M2LX+boxSize && 
      mouseY > M2LY-boxSize && mouseY < M2LY+boxSize) {
        port.write('E'); 
    } 
    else if(mouseX > M2RX-boxSize && mouseX < M2RX+boxSize && 
      mouseY > M2RY-boxSize && mouseY < M2RY+boxSize) {
        port.write('R'); 
    } 
    else if(mouseX > M3LX-boxSize && mouseX < M3LX+boxSize && 
      mouseY > M3LY-boxSize && mouseY < M3LY+boxSize) {
        port.write('A');   
    } 
    else if(mouseX > M3RX-boxSize && mouseX < M3RX+boxSize && 
      mouseY > M3RY-boxSize && mouseY < M3RY+boxSize) {
        fill(200);
        port.write('S');     
    }
    else if (mouseX > M4LX-boxSize && mouseX < M4LX+boxSize && 
      mouseY > M4LY-boxSize && mouseY < M4LY+boxSize) {
        port.write('D');     
    } 
    else if(mouseX > M4RX-boxSize && mouseX < M4RX+boxSize && 
      mouseY > M4RY-boxSize && mouseY < M4RY+boxSize) {
        port.write('F');  
    } 
    else if (mouseX > M5LX-boxSize && mouseX < M5LX+boxSize && 
      mouseY > M5LY-boxSize && mouseY < M5LY+boxSize) {
        port.write('Z'); 
    }
    else if(mouseX > M5RX-boxSize && mouseX < M5RX+boxSize && 
      mouseY > M5RY-boxSize && mouseY < M5RY+boxSize) {
        port.write('X');    
    }
    else {
      // if the mouse is pressed but not with in a box make sure nothings moving
      port.write('O');   
    } 
  } else {
    // no key or mouse press then make sure nothings moving.
    port.write('O');   
  } 
  
  // draw the buttons
  myRightArrow.drawArrow(80,30);
  myRightArrow.drawArrow(80,120);
  myRightArrow.drawArrow(80,210);
  myRightArrow.drawArrow(80,300);
  myRightArrow.drawArrow(80,390);
  myLeftArrow.drawArrow(10,30);
  myLeftArrow.drawArrow(10,120);
  myLeftArrow.drawArrow(10,210);
  myLeftArrow.drawArrow(10,300);
  myLeftArrow.drawArrow(10,390);
}

class arrow extends java.awt.Polygon { 
  /* our class is basically an instance of java.awt.Polygons and this class expects and array of X points, Y points and the number of 
     points in our shape. The variable names also have to be direct references to what this class expects, so xpoints, ypoints and npoints are all
     set/defined in the java class.
  */
  public arrow(int[] xpoints,int[] ypoints, int npoints) {
    // super invokes the java.awt.Polygon class
    super(xpoints,ypoints,npoints);
    
  } 
    // supply offsets to draw the arrow, means I don't need to set points for each one
    void drawArrow(int xOffset, int yOffset){
    fill(150);
    rect(xOffset-5, yOffset-5, boxSize, boxSize);
    fill(255);
    beginShape();
    for(int i=0;i

[ad#Google Ad in content]

Does it work?
Hopefully the sketch is working and you can control the arm via your computer. If not then first check that all motors are wired in properly and your batteries are not flat. If you arrow moves the arm the wrong way then you can either switch the motor pins on the circuit or change the Arduino sketch to alter the motors direction.

Calibrating the arm
We need to set start positions for the arm and note the positions and counts in order to later calculate the positions for the next parts of this work. This is where we'll look to more benefits of Arduino and possibly PID (Proportional, Integral, Derivative) control, PWM or someother way to get accurate positions for the motor. The only catch is each motor is in a gearbox so using an encoder or other device to measure motor rotations is not an option. But for now we can control our arm from the computer at least - check out the video below.


Arduino: Modifying a Robot Arm: How to wire up the robot arm to Arduino.

Arduino – Modifying a Robot Arm

Arduino robot arm

Essentially another tutorial involving controlling DC motors. In this post I’m going to first alter a robot arm I had built previously from a beginners kit so that it can be controlled from Arduino. Then I’m going to write a series of posts on different ways to control the robot arm using Processing and other things. You should be able to use all of what I write for work with other toys and motors.

To start with have a look at the robot arm, it’s an ‘Edge Robotic Arm Kit‘:

The kit is a basic construction one and costs about £30 which you can find in most gadget shops and web stores. You assemble a gear box for each motor/ joint in the arm, doesn’t take long to build (about an hour) and is controlled by a set of switches on a control box. The only thing to note here is we’re dealing with motors, not servos or stepper motors just bog standard DC motors. This means calculating positions isn’t going to be straightforward later on. The kit has 5 motors and 4 ‘D’ series batteries to power them and can lift about 100 grammes.

So this version has a controller attached that lets you move each motor by pressing a switch, the electrics are pretty basic and don’t allow much control or further input. I have seen other versions that allow you to plug it in to a computer via USB but you pretty much have the same controls.

In order for us to build our own controls/ interfaces and software we need to modify the arm to allow us to interface our microcontroller – in this case an Arduino board. The best way I think do this, since we want to control a motor going backwards and forward, is to use H-bridge chips – the L293D and SN754410 and wire each motor into a chip and then alter the power circuit to run these chips. Arduino can then digitally control the H-bridge chip to turn the motor on/off and change its direction.

You can see some other work I’ve done with motor DC motor control and I’ll be covering the same info throughout these posts.

Arduino Robot Arm Parts

3 H-bridge chips – I heavily recommend using the sn754410 chip but you can probably get away with the L293 series. Each chip can control 2 motors – 5 motors = 3 chips.
Arduino Deumilanova w/ ATMEGA328
Breadboard/ Prototyping board
Jumper/ Connector wires
Wire cutters/ strippers

Hacking the Robot Arm

I hope you’re not too precious about wanting to use the control unit again, thats the first thing to go! I did look at working with this but it doesn’t give the level of control that I want. Also I’ll be cutting and stripping the wires and removing the control circuit from the arm. The only permanent damage is done to the wires – basically cutting the plugs off of the wires, so you could always get new plugs if you wanted to revert it, although once I’ve shown you what can be done I don’t think you’ll mind.

Step 1
First we need to create our breadboard layout so we can plug in all the wires, we’re going to be using alot of pins on the Arduino, in fact I think I use pretty much all of them. You could reduce this using shift registers but for now its not an issue, although please follow the wiring diagrams as this layout gives the least hassle. Some pins e.g. digital pin 13 will make the motors move when the board is powering up so we want to avoid this.

First of all we need to put our H-Bridge chips on the breadboard. Make sure to put them in the center like illustrated. This means the 2 sides of the chip are isolated – it will not work otherwise!

Next using the above image and the following wiring diagram for the chip connect the ground and power for each chip leaving space for the motors and Arduino pins. Note that the red wires are connecting the rails together so the power will flow around the whole board! These chips will be using the battery power that runs the motors in the arm – the power will be plugged into the board, the Arduino pins are there to switch the chips on/ off etc… I’ve also got a table of outputs I’ve done for each pin on the H-Bridge chip, it’s the same for either the L293 series or SN754410, pin configuration diagram below. The numbers 1-16 also correspond to the numbers on the images of the circuit.

H-Bridge Pin Configuration

1 to pin on Arduino board
2 to pin on Arduino board
3 to motor1 (either + or -) it wont matter as its DC
4 to the gnd (-) rail on the breadboard
5 to the gnd (-) rail on the breadboard
6 to motor1
7 to pin Arduino
8 to power (+) rail.
9 to pin Arduino
10 to pin Arduino
11 to motor2
12 to GND (-) rail
13 to GND (-) rail
14 to motor2
15 to pin Arduino
16 to power (+) rail.

So you should have 3 chips on the board and be ready to add the motors and connections to Arduino.

Step 2
Now the circuit layout is complete we can start stripping down the arm. First remove the control unit and unscrew the panel above the battery pack – this should have all the motors plugged in to it. We’re going to systematically disconnect each motor plug, remove the plug, strip the wires a little bit and wire it on to the breadboard. When stripping the wires, remember to twist the exposed wires to prevent them becoming stranded – or solder pins to the wires.

Here’s the first motor in on the first chip:

Its important to remember which motor you’re plugging in to which chip but it’s not too much of an issue as with the software we’ll be writing later on we can work around this with our code, just so long as each motor is wired into a chip as above. Below is a list of my Arduino pins used.

Shoulder motor
chip 1, pin 1 to Arduino pin 14 (Analog pin o)
chip 1, pin 2 to Arduino pin 15 (Analog pin 1)
chip 1, pin 7 to Arduino pin 16 (Analog pin 2)
Base motor
chip 1, pin 9 to Arduino pin 2
chip 1, pin 10 to Arduino pin 3
chip 1, pin 15 to Arduino pin 4
Elbow motor
chip 2, pin 1 to Arduino pin 8
chip 2, pin 2 to Arduino pin 9
chip 2, pin 7 to Arduino pin 10
Wrist motor
chip 2, pin 9 to Arduino pin 5
chip 2, pin 10 to Arduino pin 6
chip 2, pin 15 to Arduino pin 7
Hand motor
chip 3, pin 9 to Arduino pin 11
chip 3, pin 10 to Arduino pin 17 (Analog pin 3)
chip 4, pin 15 to Arduino pin 18 (Analog pin 4)

You’ll notice that rather than refer to the motors as M1, M2, M3 as the kit does, I’m calling them something more meaningful as I think it makes them easier to identify – you should be able to figure out which motor is which from my description I would hope!

Second motor in:

You can see the battery power has been added. If you have any problems you can always connect one motor at a time and use a quick sketch to test the circuit is working and below is some simple codeto help you do that. For later tutorials this isn’t going to change much.

[ad#Google Ad in content]

int baseMotorEnablePin = 2;
int baseMotorPin1 = 3;
int baseMotorPin2 = 4;
int shoulderMotorEnablePin = 14;
int shoulderMotorPin1 = 15;
int shoulderMotorPin2 = 16;
int elbowMotorEnablePin = 8;
int elbowMotorPin1 = 9;
int elbowMotorPin2 = 10;
int wristMotorEnablePin = 5;
int wristMotorPin1 = 6;
int wristMotorPin2 = 7;
int handMotorEnablePin = 11
int handMotorPin1 = 17;
int handMotorPin2 = 18; 

void setup() {
  // set the motor pins as outputs:
  // set all chips to enabled state
  pinMode(baseMotorPin1, OUTPUT);
  pinMode(baseMotorPin2, OUTPUT);
  pinMode(baseMotorEnablePin, OUTPUT);
  digitalWrite(baseMotorEnablePin, HIGH);
  pinMode(shoulderMotorPin1, OUTPUT);
  pinMode(shoulderMotorPin2, OUTPUT);
  pinMode(shoulderMotorEnablePin, OUTPUT);
  digitalWrite(shoulderMotorEnablePin, HIGH);
  pinMode(elbowMotorPin1, OUTPUT);
  pinMode(elbowMotorPin2, OUTPUT);
  pinMode(elbowMotorEnablePin, OUTPUT);
  digitalWrite(elbowMotorEnablePin, HIGH);
  pinMode(wristMotorPin1, OUTPUT);
  pinMode(wristMotorPin2, OUTPUT);
  pinMode(wristMotorEnablePin, OUTPUT);
  digitalWrite(wristMotorEnablePin, HIGH);

}

void loop() {
    /*
    // SET either one to HIGH to turn the motor on.
    // e.g.
    digitalWrite(baseMotorPin1, LOW);
    digitalWrite(baseMotorPin2, HIGH);
    */
    digitalWrite(baseMotorPin1, LOW);
    digitalWrite(baseMotorPin2, LOW);
    /*
    // more motors here added.
    digitalWrite(shoulderMotorPin1, LOW);
    digitalWrite(shoulderMotorPin2, LOW);
    digitalWrite(elbowMotorPin1, LOW);
    digitalWrite(elbowMotorPin2, LOW);
    digitalWrite(wristMotorPin1, LOW);
    digitalWrite(wristMotorPin2, LOW);
    */

}

[ad#Google Ad in content]
Step 3
So now you should have all the motors wired to chips on the breadboard, now we just add the power to the board and we’re done – this is the power from the robot arm batteries, it can connect on either side of the breadboard as long as its connected to the power rails. Also remember to connect a wire from the GND rail on the breadboard to a GND pin on Arduino – there must be a common ground connection between Arduino and the H-bridge chips for this to work. Lastly Find a way to secure the Arduino and breadboard to the arm to minimise the risk of wires disconnecting, I just used some blu-tak (modelling clay etc..).

And here’s the final thing:

If you want to avoid the breadboard and make a more permanent circuit you should be able ot follow this, just make sure that the pins on each side of the H-Bridge are completely isolated from each other.

Onwards…
So thats it, the arm is ready to go – you can add your own switches and inputs to control this but we’re going  to have some fun writing software to control this arm in the next part to move each motor AND after that we’re going to be looking at using Inverse Kinematics and trigonometry to do some cool controlling of all the motors of the arm and to maybe start program tasks.

Oh, Inverse Kinematics basically means we can program the arm to go after a target moving all the motors in combination to do this – trust me it is very cool!

Arduino – Controlling the Robot Arm with Processing: Using Processing and my laptop to control the arm

Using Processing to Send Values using the Serial Port to Arduino

LEDs

In this write-up, I’ll show how to create a value in Processing and then send this value over the serial port to the Arduino. In the example I’m setting values of LEDs making them brighter or dimmed but this example can be extended to control other items – which I plan to do later!

Basically I’m going to set a value between 0 and 255 and then send this value to Arduino which will then use the analogWrite() function to alter the brightness of the LED using PWM (Pulse Width Modulation). I’ve already done a bit of work with LEDs and PWM.

For the communication between Processing and Arduino I’ll be using the serial port – in other work previously I’ve sent information from Arduino to Processing so this is how to do it the other way around. There are a couple of things to note though. Firstly when using Arduino to read a string from the serial port we have to look at it at a byte level, in my example it’s just easier to ignore using strings and send 1 character at a time and then store it in an array. Secondly when debugging your code you can’t read the serial values in Arduinos serial monitor as you’ll already be using the port in Processing so sometimes this can be trial and error although you can at least preview the values your sending in Processing.

Of course you can also extend this code to write values from Arduino back to Processing. There are already plenty of examples online of how to do serial port communication between Arduino and Processing and vice versa and setting an LED to on or off but I’ve done a few extra things to show some basic work with interaction and user interfaces to set the LEDs.

We’re going to set 3 LED’s – Red, Green and Blue and rather than just on or off we’ll be setting the PWM/ levels of brightness. Also the sketches deal with setting an RGB LED (RGBL) with the combined values.

I’ve written 2 visualisations to achive the above.

The first is a set of sliders like a mixing desk – when sliding a slider it will set the value of the LED it’s assigned to and the combined value will set the RGB LED. The second is a triangle shape that you can move around to create the colours, so where ever you drag each point of the triangle it will set the brightness of the LED accordingly.

The Arduino circuit and sketch is very simple and remains the same no matter which visualisation is used. So starting with the circuit…

Arduino Serial Parts

Arduino Deumilanova w/ ATMEGA328
Breadboard/ Prototyping board
Jumper/ Connector wires
3x LED (Red, Green, Blue)
1x RGB LED
6x 270 Ohm resistors

Arduino Serial Circuit

Very simple: 3 LEDs each with a common ground back to the Arduino board, the positive pins (the longer pin) has a 270 Ohm resistor between it and a connection to a digital pin. The RGB LED has 4 pins – 1 is for the power supply – some RGB LEDs instead may connect to GND so check before doing so. The other 3 pins each connect to a digital pin on the Arduino board.

LEDs

Arduino Serial Code – Receiving Values from Processing

The Arduino code is very simple as well – we set the the digital pins all as outputs, we setup the serial port we wish to use and then we read the values from the serial port and store them in an array, each item in the array corresponds to a value for an LED. There is a small catch however – it seems my RGB LED sees the value 255 as off and 0 as on so I have had to write some code to take this into account.

/* Sets LED values based on values sent on the serial port from Processing application.
   luckylarry.co.uk

*/

// create an array of LED pins - need to be the PWM digital pins
int ledPin[] = {9,10,11};
// an array to store the pins for the RGB LED
int RGBLpins[] = {3,5,6};
// array to store the 3 values from the serial port
int incomingByte[3]; 

void setup() {
  // initialize serial communication - make sure its the same as expected in the processing code
  Serial.begin(9600);
  // loop through and set the pins as outputs
  for (int i=0; i<3; i++) {
    pinMode(ledPin[i], OUTPUT);
    pinMode(RGBLpins[i], OUTPUT);
  }
}

/*  3 pins are stored in an array, 3 values from the serial buffer
are stored in an array, by looping through both we can light up the LEDs
using the values sent from the Processing sketch. NOTE: the values sent over
the serial port didn't seem to be in order, rather than RGB I got GBR so it
looks like it misses the first byte - so its just trial and error matching
the correct pin to the correct value.
*/

void loop() {
  // check to make sure there's 3 bytes of data waiting
  if (Serial.available() >= 3) {
    // read the oldest byte in the serial buffer:
    for (int i=0; i<3; i++) {
      // read each byte
      incomingByte[i] = Serial.read();
      // pass the value to each pin
      // analogWrite is used to write a value between 0 and 255 to the PWM pin.
      // lightup the separate LED's
      analogWrite(ledPin[i], incomingByte[i]);
      // seems that my RGB LED sees the values differently - it sees 255 as nothing and 0 as full colour!
      int val = 255 - int(incomingByte[i]);
      analogWrite(RGBLpins[i], val);
    }
  }

}

[ad#Google Ad in content]

Processing Sketch to Send Values via Serial Port to Arduino

Whilst both sketches visually look different they use pretty much the same methods. The main thing is that for each point, shape or item we wish to click and drag we rely on detecting where the mouse is, if its been clicked and if we're dragging the mouse. We can use Processings inbuilt functions mousePressed() and mouseDragged() but we still need to write conditional statements depending on where the mouse is.

To do this we can get the X and Y co-ordinates of the mouse using mouseX and mouseY and to compare these values we need to store the X and Y co-ordinates of any shape as variables - the easiest way is to use the PVector variable type which in its simplest use is an array that stores an X and Y value. Now we can mathematically compare the values and limit the movement of our shapes only moving when the mouse is in the correct area.

In the second sketch, the RGB triangle, I also wanted to test to make sure that the triangles points/vertices we're dragging remain inside a triangular area, to do this there is no Processing code as such its much easier to extend a class and use Javas polygon class (java.awt.Polygon) which will do all the work for us. In order to set the values we have to work out the distance we are from the original points, for which we can use the dist() method which allows us to draw a radius from a point and check to see how far our second point is from the original - we can also use this to create a circular detection area.

When getting the X, Y values from the mouse position we need to make sure these are converted to integers, for which we first use the round() method to convert our float to 1 decimal place and then use the int() method to cast the value as an integer. We also need integer values as it makes it much easier to send ints over the serial port as the libraries allow for these values.

The rest of the processing code is fairly straight forward we use text(), rect(), ellipse(), line(), fill() and stroke() functions to create our visualisation.

The only other thing to note is that in draw() method we always write the values to the serial port.

Visualisation One: RGB Sliders/ Mixing Desk
We have 3 sliders which each can set a value between 0 and 255, the Processing sketch writes each value separately to the serial port and displays the current mixed colour along with each slider value. You can download the sketch You can download the sketch here and try out the application below here and try out the application below. If you download the code please quickly do a find and replace to change //myPort to myPort - it's done just so you can see the app running in this webpage.

/*
    Code by Lucky Larry: www.luckylarry.co.uk

    RGB visualisation to control LED's by dragging sliders to define colour
    Copyright (C) 2009 Pete Dainty aka 'Lucky Larry'

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Also makes use of gradient drawing code found at: http://processing.org/learning/basics/lineargradient.html

*/

// import the serial library to allow us to send data via the serial ports (USB in this case)
import processing.serial.*;
// create a new instance of the serial classes and assign it to 'myPort'
Serial myPort;
// create set of variables to store vector infomation (X nd Y co-oordinates)
PVector redSlider,greenSlider,blueSlider,whichSlider,lockSliders;
// create an arry to store the vectors of each slider
PVector sliders[];
// boolean value (true or false) to store if lock sliders button has been clicked
boolean locked;
// values needed for gradient code
int Y_AXIS = 1;
int X_AXIS = 2;
// setup our font
PFont myFont;

void setup() {
  // screen size
  size(300,315);
  // setup my font type and size
  myFont = createFont("verdana", 10);
  textFont(myFont);
  // specifiy the co-ordinates for each slider, the lock sliders button
  redSlider = new PVector(50,150);
  greenSlider = new PVector(110,150);
  blueSlider = new PVector(170,150);
  lockSliders = new PVector(12,27);
  // setup an array to store the values of each slider
  sliders = new PVector[] {redSlider,greenSlider,blueSlider};
  // smooth shapes
  smooth();
    /* define which port to use mine is COM10 and is 2nd in the array list.
       you can print out to the screen which ports are accessible by using this code line below
       set the baud rate to the same as in your Arduino code so mine is 9600
    */
    // println(Serial.list());
    myPort = new Serial(this, Serial.list()[1], 9600);
} // end setup

void draw() {
  // set background colour to grey in case the setGradient code fails
  background(50);
  // set outlines of shapes to be black
  stroke(0);
  /* creates a rectangle shape based up on X and Y co-ords,
     width and height, 2 RGB values to the colours to mix and which
     axis to apply the gradient.
  */
  color b1 = color(130, 130, 130);
  color b2 = color(70, 70, 70);
  setGradient(0, 0, width, height, b1, b2, Y_AXIS);
  // set the backgrounds of our slider columns
  color sliderGrad1 = color(120, 120, 120);
  color sliderGrad2 = color(50, 50, 50);
  setGradient(25, 20, 50, 275, sliderGrad1, sliderGrad2, Y_AXIS);
  setGradient(85, 20, 50, 275, sliderGrad1, sliderGrad2, Y_AXIS);
  setGradient(145, 20, 50, 275, sliderGrad1, sliderGrad2, Y_AXIS);
  noFill();
  rectMode(CENTER);
  // draw the outlines of each column and a guide line in the center
  rect(50,160,50,275);
  rect(110,160,50,275);
  rect(170,160,50,275);
  line(50,30,50,285);
  line(110,30,110,285);
  line(170,30,170,285);
  // loop through 25 times to produce 25 measurement lines and measurements
  for (int i=0; i<=25; i++) {
    stroke(30);
    // first column
    line(46,30+(i*10),54,30+(i*10));
    // second column
    line(106,30+(i*10),114,30+(i*10));
    // third column
    line(166,30+(i*10),174,30+(i*10));
    // right hand gauge and measurement numbers
    fill(40);
    stroke(40);
    line(196,30+(i*10),201,30+(i*10));
    text(Integer.toString(i*10),216,35+(i*10),25,25);
  }
  // draw the sliders - one for each item in the sliders array
  for (int i=0; i< mouseX &&
            sliders[i].x+20 > mouseX &&
            sliders[i].y-10 < mouseY &&
            sliders[i].y+10 > mouseY) {
              whichSlider = sliders[i];
            }
    }
    // check to see if the mouse is clicked inside the lock sliders button
    if (lockSliders.x-5 < mouseX &&
        lockSliders.x+5 > mouseX &&
        lockSliders.y-5 < mouseY &&
        lockSliders.y+5 > mouseY) {
          // if so then check the current state and set our boolean to the opposite value
          if(locked) {
          locked = false;
          } else {
          locked = true;
          }
       }
}

/* If the mouse is pressed and the value of whichSlider is not null - it will be null if the mouse is outside the slider area.
   Then look to see if the mouseY is in range, so we dont want it to exceed a scale of 255
   Then look to see if the sliders are locked, if they are then set all sliders to the mouse Y
*/
void mouseDragged() {
    if (whichSlider != null)
    {
        if(mouseY > 30 && mouseY < 287 ) {
          // set the Y value of the slider
          if(!locked) {
            whichSlider.y = mouseY;
          } else {
            for(int i=0; i<3; i++) {
              sliders[i].y = mouseY;
            }
          }
        }
    }
}

/* following gradient code taken from:
   http://processing.org/learning/basics/lineargradient.html
*/

void setGradient(int x, int y, float w, float h, color c1, color c2, int axis ){
  // calculate differences between color components
  float deltaR = red(c2)-red(c1);
  float deltaG = green(c2)-green(c1);
  float deltaB = blue(c2)-blue(c1);

  // choose axis
  if(axis == Y_AXIS){
    /*nested for loops set pixels
     in a basic table structure */
    // column
    for (int i=x; i<=(x+w); i++){
      // row
      for (int j = y; j<=(y+h); j++){
        color c = color(
        (red(c1)+(j-y)*(deltaR/h)),
        (green(c1)+(j-y)*(deltaG/h)),
        (blue(c1)+(j-y)*(deltaB/h))
          );
        set(i, j, c);
      }
    }
  }
  else if(axis == X_AXIS){
    // column
    for (int i=y; i<=(y+h); i++){
      // row
      for (int j = x; j<=(x+w); j++){
        color c = color(
        (red(c1)+(j-x)*(deltaR/h)),
        (green(c1)+(j-x)*(deltaG/h)),
        (blue(c1)+(j-x)*(deltaB/h))
          );
        set(j, i, c);
      }
    }
  }
}

[ad#Google Ad in content]

Visualisation Two: RGB Triangle
A bit more complex we have triangle this time to control the mixing of colours/ setting of values - it works the same way pretty much as the first one. The only real difference is how the mouse is detected and movement is limited to a triangle. You can download the sketch here and try out the application below. Like the previous sketch the downloadable version has the serial port code commented out so it will work in this webpage. Do a find and replace to change //myPort to myPort and that should sort it out.

/*
    Code by Lucky Larry: www.luckylarry.co.uk

    RGB visualisation to control LED's by dragging shapes to define colour
    Copyright (C) 2009 Pete Dainty aka 'Lucky Larry'

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .
*/

// import the serial library to allow us to send data via the serial ports (USB in this case)
import processing.serial.*;
// create a new instance of the serial classes and assign it to 'myPort'
Serial myPort;
// create set of variables to store vector infomation (X nd Y co-oordinates)
PVector areaPointA,areaPointB,areaPointC,pointA,pointB,pointC,pointDrag;
// create an arry to store the vectors of each point of our shape in this case a triangle
PVector[] rgbTriangle;
/* the next 3 lines uses a custom class at the bottom of this code.
   the class extends java.awt.polygon which means I can use this to create a triangle to test if the
   mouse is in side the shape. */
// new instance of our class
DragArea area;
// these lines specify the X value and Y value for each point of our triangle {xpoint1, xpoint2, xpoint3} etc..
int[]xpoints={152,23,284};
int[]ypoints={23,248,248};
// set 3 variables to store the colour values.
int R, G, B;
// setup our font
PFont myFont;
/* setup our background and variables */
void setup () {
    // screen size
    size(305,271);
    // setup my font type and size
    myFont = createFont("verdana", 12);
    textFont(myFont);
    // define our new instance of the custom class. (X points, Y points, Number of points in the shape) more info below by the class
    area = new DragArea(xpoints,ypoints,3);
    // define the area vectors - we use these to see how far our point is from its original source, needed to calculate the value between 0 and 255
    areaPointA = new PVector(152,25);
    areaPointB = new PVector(25,246);
    areaPointC = new PVector(280,246);
    // specifiy the starting co-ordinates for the triangle that we can move
    pointA = new PVector(152,40);
    pointB = new PVector(40,230);
    pointC = new PVector(265,230);
    // set the array with the new points.
    rgbTriangle = new PVector[]{pointA,pointB,pointC};
    // center our shapes
    ellipseMode(CENTER);
    rectMode(CENTER);
    // set smoothing for our shapes edges
    smooth();
    /* define which port to use mine is COM10 and is 2nd in the array list.
       you can print out to the screen which ports are accessible by using this code line below
       set the baud rate to the same as in your Arduino code so mine is 9600
    */
    // println(Serial.list());
    myPort = new Serial(this, Serial.list()[1], 9600);
} // end setup

/* begin our animation/ interaction */
void draw () {
    // set background to black
    background(50);
    // set the colours and positions of the large colour circles to indentify where red is 100% etc...
    // fill(R, G, B);
    fill(255,0,0);
    // ellipse(X co-ordinate, Y co-ordinate,width, height)
    ellipse(areaPointA.x, areaPointA.y, 15,15);
    fill(0,255,0);
    ellipse(areaPointB.x, areaPointB.y, 15,15);
    fill(0,0,255);
    ellipse(areaPointC.x, areaPointC.y, 15,15);
    // create our background triangle to show the area in which we can move.
    fill(100);
    beginShape(TRIANGLES);
      vertex(areaPointA.x,areaPointA.y);
      vertex(areaPointB.x,areaPointB.y);
      vertex(areaPointC.x,areaPointC.y);
    endShape();
    /* set the fill of our coloured triangle we work out the values by
       getting the current points co-ordinates and working out the distance
       from the original point. These distances are actually calculated on a
       circular area so it draws an elliptical area from the origin point from
       the 2 adjacent sides of the triangle. First set the values to our variables
       R, G, B and round them so that they'll be integers and parse them using the int() method
    */
    R = int(round(255-dist(areaPointA.x,areaPointA.y,pointA.x,pointA.y)));
    G = int(round(255-dist(areaPointB.x,areaPointB.y,pointB.x,pointB.y)));
    B = int(round(255-dist(areaPointC.x,areaPointC.y,pointC.x,pointC.y)));
    fill(R,G,B);
    /* we need to send this fill value to the Arduino to light up the LED's accordingly
       we do this by writing a value to the serial port.
       You can write values to the serial port using bytes, integers and chars.
       I'm going to send the 3 values separately and store them in an array on the Arduino
    */
    myPort.write(R);
    myPort.write(G);
    myPort.write(B);
    // create our RGB triangle from the draggable points
    beginShape(TRIANGLES);
      vertex(pointA.x,pointA.y);
      vertex(pointB.x,pointB.y);
      vertex(pointC.x,pointC.y);
    endShape();
    // create the drag handles for each point in the draggable shape.
    for (int i=0; i< mouseX &&
            rgbTriangle[i].x+5 > mouseX &&
            rgbTriangle[i].y-5 < mouseY &&
            rgbTriangle[i].y+5 > mouseY) {
              pointDrag = rgbTriangle[i];
            }
    }
} 

/* If the mouse is pressed and the value of pointDrag is not null - it will be null if the mouse is outside the handle area.
   We then do another check to see if our mouse pointer is inside our polygon area. In Processing we can use the .contains() method
   that we get from the custom class at the bottom to check if an XY value is inside the polygons area.
*/
void mouseDragged() {
    if ( pointDrag != null )
    {
      if(area.contains(mouseX,mouseY) ) {
        // set the XY values of the point we're dragging to the values of the mouse
        pointDrag.x = mouseX;
        pointDrag.y = mouseY;
      }
    }
} 

/* This doesnt look like much code but what we're doing is extending a class with another class.
   By extending our class with java.awt.Polygon we then inherit that classes methods to use as our own.
   Since Processing is based upon Java there are many classes that we can import to extend Processing.
   The functions of java.awt.Polygon can be found here: http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Polygon.html
   This makes it much easier to do collision detection with shapes - Processing can handle rectangles and circles fine
   but for triangles this saves alot of effort.
*/
class DragArea extends java.awt.Polygon {
  /* our DragArea class is basically an instance of java.awt.Polygons and this class expects and array of X points, Y points and the number of
     points in our shape. The variable names also have to be direct references to what this class expects, so xpoints, ypoints and npoints are all
     set/defined in the java class.
  */
  public DragArea(int[] xpoints,int[] ypoints, int npoints) {
    // super invokes the java.awt.Polygon class
    super(xpoints,ypoints,npoints);
  }
}

[ad#Google Ad in content]

Arduino + Processing – 3D Sensor Data Visualisation

Arduino 3D scan

So following on from my previous posts about visualising sensor data in Processing, I’m now looking at drawing 3D representations of the data recorded from the Sharp IR sensor – although can be any kind of range finder.

I started by rigging 2 servos, one to pan left to right, the other up to down. The latter is limited to only 60 degrees of movement. I’m going to represent each servo position in a grid to start with, so a grid 180 wide (x) by 60 tall (y). The distance measured from the sensor will form the z index position so how far/ close a point will appear.

The setup is pretty much the same, Arduino records and sends the sensor data to the serial port buffer along with the X and Y position of the servos. Processing then picks this up and populates an array. Now this time I’m using multi-dimensional arrays, that is one array that stores other arrays. I could make just one array of 10800 items (180 * 60) but its far more efficient to make an array of 180 items, each item being another array of 60 items to store the distance measured. So for every 1 degree I move left to right, I record the 60 positions of the up/ down servo and the reading taken.

To visualise this I started drawing squares using the QUAD_STRIP shape to produce a grid layout (image at the top of the post). Of course because I’m actually using polar co-ordinates (degrees) instead of cartesian (x, y) then what the sensor is reading can’t really be translated to a flat grid. Because when it measures something vertical the measurements will all be different and when translated to my flat grid, it would make anything vertical look slanted. Trouble is now we’re trying to view something in 3D space so it doesn’t look all that great – so I’ve added in some animation to rotate the object slightly, looks fine when you zoom in close enough to one section but otherwise it’s just a random shape.

There are 2 ways around this, firstly we can convert our co-ordinates to cartesian. Or we can alter the grid used to display our data, the shape needed is basically a 60 degree arc thats lathed 180 degrees – so it kind of looks like a tyre wall. The radius used to draw our 60 degree arc is calculated by the distance taken from the sensor.

Arduino 3D Sensor Data Parts

SRF05 Ultrasonic range finder or Sharp GP2Y0A02 IR sensor (basically any kind of distance sensor)
Arduino Deumilanove w/ ATMEGA328
Breadboard / Prototyping board
Jumper/ Connector wires
2x Servos (has to need no more than 5v supply)
C shaped Servo brackets (If anyone can make these cheap enough let me know!)

Arduino 3D Plotter Circuit

Using the below posts you should be able to figure out how to wire the sensor and how to use the servos. I use digital pins 9 and 10 for the servos and analog pin 1 for the sensor reading.

Arduino SRF-05 Tutorials
Arduino Servo Tutorials
How to use the Sharp IR range finder

Arduino Sketch

We use the servo libary and a couple of FOR loops to control 2 servos, for every degree panned we tilt the other servo through 60 degrees taking a series of sensor readings for each position and averaging them. We output these values with the X and Y position in degrees to the serial port buffer. At the end of each loop we reset the servo position. If the sensor reading is outside the range of operation of the servo we also handle this.

/*
luckylarry.co.uk
3D Scan Visualisation for Sharp GP2Y0A02 IR range finder
Sends sensor readings for every degree moved by the servo
values sent to serial port to be picked up by Processing
*/
#include             // include the standard servo library
Servo leftRightServo;         // set a variable to map the servo
Servo upDownServo;
int leftRightPos = 0;         // set a variable to store the servo position
int upDownPos = 0;
const int numReadings = 10;   // set a variable for the number of readings to take
int index = 0;                // the index of the current reading
float total = 0;              // the total of all readings must be a float to allow totaling of float values
int average = 0;              // the average
int IRpin = 1;                // analog pin for reading the IR sensor

/* setup the pins, servo and serial port */
void setup() {
  leftRightServo.attach(9);
  upDownServo.attach(10);
  // initialize the serial port:
  Serial.begin(9600);
} 

/* begin rotating the servo and getting sensor values */
void loop() {
 for(leftRightPos = 0; leftRightPos < 180; leftRightPos++)
  {
    leftRightServo.write(leftRightPos);             

  for(upDownPos = 60; upDownPos < 120; upDownPos++)
  {
    upDownServo.write(upDownPos);  

      for (index = 0; index<=numReadings;index++) {            // take x number of readings from the sensor and average them
        float volts = analogRead(IRpin)*0.0048828125;   // value from sensor * (5/1024) - if running 3.3.volts then change 5 to 3.3
        float distance = 65*pow(volts, -1.10);          // worked out from graph 65 = theretical distance / (1/Volts)S - luckylarry.co.uk
        total = total + distance;                              // update total
        delayMicroseconds(20);
      }
    average = (int) total/numReadings;                               // create average reading
        if (average < 20) {
         average = 20;
        }
        if (average > 150) {
         average = 150;
        }
        //average = 0 - average;
    if (index >= numReadings)  {                               // reset the counts when at the last item of the array
      index = 0;
      total = 0;
    }       

Serial.print("Y");
Serial.print(upDownPos-60);
Serial.print("X");
Serial.print(leftRightPos);
Serial.print("Z");
Serial.println(average);

  }
    upDownServo.write(60);
  }

    leftRightServo.write(0);              

}

[ad#Google Ad in content]

Processing Sketch

We now listen to the serial port and each time there is an event we take the values and populate an array based on the X and Y values sent from the Arduino code. We add this value on to the existing value and then for each complete mapping we work out the average value – so the longer it runs for the more normalised the results should appear.

Using some basic trigonometry we have a class that makes an arc. Our draw() method calls this arc and translates/ rotates it for each of the 180 degrees. The arc itself is calculated from using the distance reading from the sensor as its radius.

If using a grid instead of this shape then we just say at point X,Y set the Z value instead of worrying about radius’s etc…

/*
luckylarry.co.uk
3D Scan Visualisation for Sharp GP2Y0A02
Maps out an area of what the GP2Y0A02 sees into a 3D view
*/
import processing.serial.*;     // import serial library
Serial myPort;                  // declare a serial port
int x, y, z;                     // variable to store x and y co-ordinates for vertices
int value = 0;                  // value from sensor
int[][][] data = new int[181][61][1];  // create an array to store each new sensor value for each servo position
int count;
int average = 1;
PFont myFont;                   // setup fonts in Processing
int numberOfSegments = 179;
createArc Arc;                  // create an instance of the Arc class
float radius = 150;
float angle = 0;

void setup(){
  size(640, 360, P3D);
  Arc = new createArc();        // assign the Arc classes to an object
  myFont = createFont("verdana", 12);
  textFont(myFont);
  // setup the serial port and buffer
  myPort = new Serial(this, Serial.list()[1], 9600);
  myPort.bufferUntil('\n');

}

void draw(){
  background(255);
  float tempX = 0, tempY = 1, tempZ = 0;
  fill(200);
  lights();
  translate(width/2, 200, 110);
  angle = 180.0 / numberOfSegments;
  rotateY(count * PI/10800);
  for (int j = 0; j < numberOfSegments; j++){
      tempZ = cos(radians(angle))*radius;
      tempX = sin(radians(angle))*radius;
      pushMatrix();
      translate(tempX, tempY, tempZ); // move each instance we create of the arc object to a slightly new position and rotation
      rotateY(radians(angle));
      Arc.create(j);
      popMatrix();
      angle += 180.0/numberOfSegments;
  }

}
// creates an arc object using QUAD_STRIP
class createArc {
// pass values to create method to know which array to load 1 to 180...
  void create(int degree){
    pushMatrix();
    rotateY(radians(135));
    beginShape(QUAD_STRIP);
    for(int a=60; a < 120;a++) {
      float x1 = cos(radians(((90+a))))*(data[degree][a-60][0]/average);
      float y1 = sin(radians(((90+a))))*(data[degree][a-60][0]/average);
      float x2 = cos(radians(((90+a))))*(data[degree+1][a-60][0]/average);
      float y2 = sin(radians(((90+a))))*(data[degree+1][a-60][0]/average);
      vertex(x1,y1,100);
      vertex(x2,y2,105);
    }
    endShape();
    popMatrix();
  }
} 

/* get values from serial port */

void serialEvent (Serial myPort) {
  String xString = myPort.readStringUntil('\n');  // read the serial port until a new line
    if (xString != null) {  // if theres data in between the new lines
    	xString = trim(xString); // get rid of any whitespace just in case
    	String getY = xString.substring(1, xString.indexOf("X")); // get the value of the servo position
        String getX = xString.substring(xString.indexOf("X")+1, xString.indexOf("Z")); // get the value of the sensor reading
        String getZ = xString.substring(xString.indexOf("Z")+1, xString.length()); // get the value of the sensor reading
    	x = Integer.parseInt(getX); // set the values to variables
    	y = Integer.parseInt(getY);
        z = Integer.parseInt(getZ);
        data[x][y][0] += z;
        //println(z); // for debugging
        count++;
        if (count > 10800) {
          count = 0;
          average++;
        }
  }
}

[ad#Google Ad in content]

So here’s a quick screen grab of the 3D object that represents what the sensor sees, looks pretty confusing but if you zoom in and take a small section of it then it’s a bit better. Other than that its just a random shape!

3D-scan02