Friday, May 16, 2014

Getting started with Arduino - Simple Outputs

I'm going to start a small Arduino introduction series. I think it's important that people understand what's happening exactly when they create their first blinky program. The three things that I'm going to cover in this post is:
1. Turning an LED on
2. Blinking an LED on and off
3. Fading an LED for loop
We're also going to talk about how to use the IDE briefly, just so you can follow along better.

These three tasks are relatively simple, but understanding these will let you control thousands of other devices, not just LEDs!

To create a new sketch, all you do is open up the IDE, which can be downloaded at Arduino.cc. Once opened there should be nothing except for an empty area. Every Arduino program needs two functions to compile. Those functions are void setup() and void loop(). Those can be seen in the picture below.

1
2
3
4
5
6
7
8
9
void setup() {


}

void loop() {


}

The setup() function only runs once on the Arduino. It's often used to set pin modes as either inputs or outputs, and can be used to initialize variables at startup.

The loop() function runs forever, until your board loses power, or you program a stopping point. It runs very very fast, and a majority of your code goes in here. 

Now I want to explain what the pinMode() command does. pinMode() tells the Arduino what to set each pin as, either an input or output. pinMode has two parameters. The first parameter tells the Arduino which pin you're talking to, and the second parameter defines it as an input or output. Look at the picture below to see it being used. The pinMode() is also usually found in the setup() function.

1
2
3
4
5
6
7
8
9
void setup() {
  pinMode(3, OUTPUT); //Setting pin 3 as an output on the Arduino
  pinMode(8, INPUT); //Setting pin 8 as an input on the Arduino
}

void loop() {


}

digitalWrite() is how we set an OUTPUT pin high or low, meaning 5 volts or 0 volts. digitalWrite() has two parameters. The first one is which Arduino pin you're talking to, and the second is HIGH or LOW. To blink an LED at a steady pace it would be done like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
void setup() {
  pinMode(, OUTPUT); //Setting pin 3 as an output on the Arduino
}

void loop() {
 digitalWrite(3, HIGH);
 delay(500);
 digitalWrite(3, LOW);
 delay(500);
 
}

Above I use a delay() function. It only has one paramter, and it's in integer value in milliseconds. If you were to type
delay(500); 
The Arduino would pause what it was doing for 500 milliseconds and keep doing the command above it until the 500 milliseconds has passed.        

Another incredibly useful command would be analogWrite(). analogWrite() lets your vary the brightness of an LED or the speed of a motor. It uses something called pulse width modulation which does exactly what the name is. It varies the width of the HIGH LOW transitions to make it appear the voltage is changing, when in reality we're only changing the time that the pin is HIGH or LOW really fast. The parameters for analogWrite are the pin number, and a value between 0-255. 255 is a duty cycle of 100%, 127 would be 50%, and 0 would be 0%. It is very important to use a pin on the Arduino that is compatible with PWM. Look up the specs for your Arduino and use one of the pins that is useable with PWM.

To set an LED at half brightness it would look something like this:

1
2
3
4
5
6
7
void setup() {
  pinMode(3, OUTPUT);
}

void loop() {
  analogWrite(3, 127);
}


Now to fade an LED we would use a for loop. The for loop would need to control a variable to go from 0 - 255. When doing the the LED's brightness would ramp up, and with use of a second for loop, we can ramp it back down. The two loops would look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
void setup() {
  pinMode(3, OUTPUT); //Setting pin 3 as an output on the Arduino
}

void loop() {
 for(int i = 0; i <= 255; i++) {
   analogWrite(3, i);
   delay(10);
 }
 for(int j = 255; j >= 0; j--) {
   analogWrite(3, j);
   delay(10);
 }
}
The reason we use a 10 millisecond delay in the LED fading is so it doesn't happen so fast, and it looks better to the eyes!

In the for loop I have a counter 'i'. It starts at 0, and every 10 milliseconds it increments by 1 (that's what the i++ does). It then writes the value of 'i' to the second parameter of analogWrite and the LED then shows that brightness. Once the first for loop is completed, it moves on to the second one, which is just the opposite. It starts the LED off at full brightness, and brings it back down.

Another really cool and important topic is the use of variables. Variables make code much more readable and easier to debug when you're having problems. All you need to do is create a variable, set a value to it, and use it in your program instead of hardcoding in the pin numbers. An example is below. 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
int led = 3;

void setup() {
  pinMode(led, OUTPUT); //Setting pin 3 as an output on the Arduino
}

void loop() {
 for(int i = 0; i <= 255; i++) {
   analogWrite(led, i);
   delay(10);
 }
 for(int j = 255; j >= 0; j--) {
   analogWrite(led, j);
   delay(10);
 }
}


Notice how I removed the '3' in the analogWrite functions and replaced them with led. It makes the program look a little bit nicer I think.

Thanks everyone for reading! Next time we'll go over input devices, like switches, potentiometers, and LDR's (light dependent resistors).



Thursday, May 1, 2014

How to Create an Audio Amplifier with the LM386 OP AMP

This post isn't really anything Arduino related, but still a really cool project. I created an audio amplifier that you can connect to your iPod or whatever else you play music with and listen to it on a speaker.

In it's current state it's mono, but by adding a second speaker and second operational amplifier you can easily turn this into a stereo sound system.

I would highly recommend looking at the data sheet before building this. It shows you typical applications and other notes you would need if you were to design this from scratch. LM386 Datasheet

The parts needed for this are:
LM386 OP AMP x1
100uF Capacitor x1 [C2]
10uF Capacitor x1 [C1]
10 Ohm resistor x1 [R2]
1K Ohm resistor x1 [R1]
9 Volt Battery x1
10K ohm Potentiometer x1 [R6]
Speaker x1 (for mono)
9 Volt Battery snap x1
Audio Jack x1


The schematic for this is pretty simple, and fun to make. I think it's kinda nice making something that doesn't involve programming or micro controllers. I created the schematic using Eagle.


You can change the gain by adding a capacitor between pins 1 and 8. You can make the gain variable if you put a resistor in series with it. You can see that I did this at labels C1 and R1. I would reccomend you add a potentiometer instead of the resistor R1 so you can change the gain on the spot. If you don't put anything between pins 1 and 8, the built in 1.35K ohm resistor would set a gain of 20dB.

Capacitor C2 is used to help reduce noise to the speaker. It helps to remove constant DC voltage and only allows the audio waves to pass through.

If you wanted to make this stereo, you would need to repeat the circuit to be the same, except you would share the potentiometer that controls the gain between the two, and connect their grounds together. Inside of an audio cable there are 3 wires. Black for Ground, and the two other colors are for each audio channel. Connect one channel to one of the OP AMPS, and the other channel to the second one.

The next step is to solder this onto perfboard and put it in a nice enclosure. 

Here are some pictures of the one I made breadboarded up. 






Now here's some pictures of it being used with an oscilloscope so you can actually see the gain. 
It's hard to see the original signal a little bit but it's the bright small wave in the very center. The outside wave is actually the smaller signal amplified. Looks like it's amplifying very well! The gain might be set a little too high though, you can see in some spots how instead of a nice sinusoidal wave we get flatness at the top. That's because it's amplifying too much and is exceeding the OP AMPS power limits. This could be solved by using a 12 volt battery or greater compared to our 9 volt battery.

And here's just another view.

I hope you guys enjoyed this little project! My next couple of posts are going to be Intro to Arduino tutorials that I'm going to use for a school club I'm teaching. Those should be done fairly soon!

Wednesday, April 16, 2014

How to use the Arduino Motor Shield

Hey guys, I was recently on a small team that had to create a robot for something called a "Robotics Triathlon". We had three different tasks we had to accomplish. 1) Follow a line, 2) Ascend and descend a hill at an unknown angle and display the angle at the end, 3) Go over a "boulder field" without getting stuck. The boulder field was by far the easier part, because our robot chassis had treads. I'll post videos of the competition on the bottom of this post.

The main point of this post is to show how to use the Arduino Motor Shield. Our robot design was based around using this shield and it's definitely a great shield to have if you plan on making any small robots with DC motors.

For this example we'll need just a few things:
Arduino Uno
Arduino Motor Shield
DC Motor
9 Volt Battery (Optional) with snap connector. You can use power directly from USB if you wanted.




For now, connect the battery snap to the Vin and GND screw terminal. And connect the positive and negative lead of the motor to the + and - of the A channel.



If you look on the digital pins on the motor shield, it says which pins are used for what. For example, Pin 12 is used to control the direction of Channel A and Pin 3 is used to control the speed of Channel A. Pin 9 is used as a brake for Channel A, but we won't be using that too much today. If you look you can see the other pins for Channel B, but I'm only using one motor for this demonstration.




Below is some example code I wrote.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const int dir = 12; //Declare a variable name for pin 12 (direction of Channel A)
const int pwm = 3; //Declare a variable name for pin 3 (speed of Channel A)
const int brake = 9; //Declare a variable name for pin 9 (brake of Channel A)

void setup() {
     pinMode(dir, OUTPUT); //All of these controls for Channel A are outputs
     pinMode(pwm, OUTPUT);
     pinMode(brake, OUTPUT);
}

void loop() {
     digitalWrite(brake, LOW); //Disable the brake
     analogWrite(pwm, 125); //Set motor speed to about 50% (0-255)
     digitalWrite(dir, HIGH); //Sets the motor forward, if it was
     //'LOW' the motor would spin reverse
}

At the top of the program I'm declaring variable names for the pins I'm using just to make it have more readability. In the setup() I'm telling the Arduino that the three control pins are all outputs. And in the loop() I'm telling the Arduino what to do with each pin.

The reason we do digitalWrite(brake, LOW) is because we want to tell the Arduino to disable the brake, that way the motor will be able to spin.

Next is analogWrite(pwm, 125). We use analogWrite because the Arduino is expecting a PWM signal that will change the duty cycle on the output. That way we can control the speed of the motor. When using analogWrite your second parameter is going to be a value between 0 and 255. With 0 being the slowest (off) and 255 being full speed.

When we use digitalWrite(dir, HIGH) what's basically happening is that we're telling what direction we want the motor to spin. Depending on your motor and how you have it wired, setting it HIGH will turn it one direction, and setting it LOW will turn in the opposite direction. This is useful for turning your robot, or so you can have different functions for forward and reverse.

You can find code for this post on my GitHub at github.com/jacobantoun. I'll have more examples in there, and code from previous projects I've done. I show an example of using a function to make it a little easier to control the motor on my GitHub also.

Now here's a video of the motor running at 25% speed, then jumping up to 50%, then 75%, then full speed. I didn't pick a very good color of tape to see the different speeds spinning, but you can definitely hear it!




Tuesday, March 25, 2014

Line Following Robot

Arduino Line Following Robot.

For now I'll just post a quick demo video, but after the competition I'll be sure to share the code.

Friday, January 24, 2014

How to use an NPN transistor as a switch with your Arduino

If you've ever wanted to control devices that use higher voltages or require more current than your Arduino can provide, you should try using a transistor! By using a transistor, you can use an external power supply to power up whatever it is you're trying to do. For example, if you wanted to light up 50 leds with an Arduino, you probably couldn't do that because it can't source enough current to be able to allow them to light up. If we used a transistor, we could use a separate power supply that can source enough current for our leds, and be able to control it just like we would control any other Arduino pins. There are two main types of transistors. NPN and PNP. I'm using an NPN transistor called the 2N3904 for my project.

A project I did was create a simple light bar that fades in and out. I used 10 leds, and each led sources about 17mA. So ten leds would be 170mA, which an Arduino pin can't do. So I used a transistor to supply power to them using a 5V wall adapter, and Arduino to fade them in and out.
The code for it is super simple, and probably something you've used before.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#define tranPin 6 //Base is connected to pin 6
void setup() {
  pinMode(tranPin, OUTPUT);
}
void loop() {
  for (int i=0; i<255; i++) {
    analogWrite(tranPin, i);
    delay(15);
}
  delay(50);
  for (int i=255; i>0; i--) {
    analogWrite(tranPin, i);
    delay(15);
}
  delay(50);
}




There are three pins on an NPN transistor. Emitter, Base, and Collector. When holding a transistor with the flat side facing you, it goes (from left to right) Emitter Base Collector. The Base pin is what decides if current will pass from the Collector to the Emitter. Since the transistor is a current controlled device, you MUST have a resistor with the Base. While I was wiring up this circuit before writing this post, I smelled smoke, and realized I had forgotten to put a resistor before the base, luckily I had just purchased 50 of them!

Another great use for transistors with an Arduino is for motors. Since motors can spit a current back out after you remove power from it, it can damage your Arduino. But if you use a transistor to connect to the motor instead of the motor being connected directly to your Arduino, it acts as a shield and won't damage your Arduino.

You can see how it's wired up and acts as a switch when you see it in the Fritzing image.
In the case of the Frtizing image. We're using a 5 volt Arduino, to control the flow of current from a 9 volt battery to the motor. Start your circuit like normal, connect your external power supply (9 volt battery) to your circuit, but connect the ground of the circuit to the Collector, and the Emitter to ground.

And here's the physical circuit. You can see than I'm using a power supply running off of 5 volts for the led, and the Arduino's Vout pin to use on the base to let current pass through the transistor at the base.



If you have any questions feel free to leave a comment below or reach out to me on Google+