Sunday, February 15, 2015

#6 - Bi-Directional Motor Control (HBridge and Relays) and Arduino: Inputs/Outputs Galore

Bi-Directional Motor Control

In the previous section, we learned how to work with motors. Now, we will learn how to make that motor rotate in not one, but both directions. One such way is through the use of a DPDT (double-pole double-throw) relay. This relay switches the direction of current flow through the motor, thus switching the direction it spins when it does so. *Remember to use the TIP 120 Transistor!

Below, I have constructed a circuit using the TIP 120 and a relay. 
A DPDT relay controlling a Motor.

The motors spins clockwise depending on the orientation of power/ground. Reverse them, and the rotation reverses.

The H Bridge

Another way to control motors is through the use of an H Bridge. It is called the H Bridge because of the way the components are oriented in an H. It has 4 switching elements: called high side left, high side right, low side left, and low side right. The H Bridge operates by switching on opposite corners of the H bridge together, with the other 2 off. So the High side left and the Low side right would turn on together, while the Hide side right and Low side left turn on together. One of those two combinations causes the motor to spin clockwise, while the other spins it counterclockwise. Do remember that the motor only runs on 1.5V (any more will cause damage to the motors). Attach the 1.5V across the top and the bottom of the H bridge, and attach the microcontroller pins 12 (to ground), and 13 (to power). If you want to reverse the direction of the pins, reverse the pins 12 and 13. 
The H Bridge rotating clockwise using a 5V power supply.


An overview of the circuit.

Now, we will use the arduino to control the motors!


Setting A High and B Low rotates it in one direction, while setting B High and A Low turns it in the other direction. Setting A and B equal makes the motor stop.

Arduino: Input & Output Devices

Now we will learn of several Input and Output devices that we can interface with the Arduino. But first, let's introduce a new function that can be helpful to us in the future: the for statement. The for statement is used for actions that must be repeated multiple times. The for statement is as follows:
for(initialization; condition; increment)  
{
//Statements
}
The initialization is the initial starting variable, while the condition is the limit to which the for statement is repeated, and the increment is the level that the variable is raised by after the loop has been run. Now, let's make an LED blink on/off with increasing frequency using this new statement! 

Digital Inputs

Digital input are inputs that have 2 states: on or off. Some examples include micro switches, push switches, reed switches, and more. We will create a circuit where the Arduino will not supply power to the LED unless the switch is pressed.
The Circuit in its off state.

The circuit in its on state.

The code for the digital switch.


Light Dependent Resistors (LDR)

Another type of input that we can use is the LDR. This resistor changes value based on the amount of light that it sees. Using this, we can use a range of values to set different reactions based off of the amount of light.
An example code for using the LDR to control 2 LEDs.

Depending on how far my hands were, the LDR turned on a different combination of LEDs.

Thermistors

Just as there is a resistor to change value based on light, there are also resistors that change based on heat. Below is a circuit that uses the thermistor to tell the motor to turn on or off based off of how warm or cool it was. 


Buzzers and Potentiometers

Similar to previous sections, the potentiometer is a variable resistor that changes value based on the rotation of the knob. We can use this to turn on the buzzer based on how much it has been turned.

The code for the buzzer.

The potentiometer acts as an input, which then goes through the Arduino, which turns on the buzzer, the output.



#7 - Advanced Arduino: Making Music, Using the Serial Port, and Toy-Hacking

Advanced Programming

We've been able to play around with the Arduino for a while, and have learned how to execute some basic functions. Now we will learn some new, more advanced functions, such as: using arrays, creating/accessing libraries, and using the serial port. Later, we will use some of our learned knowledge to hack into a toy, and have our Arduino control portions of its operation. But first...

Making Music

We will be using a piezo sounder (that we used previously as a buzzer) to assist us in learning how to use arrays, and how to create/access libraries.

The Piezo Sounder As A Theramin

We've learned how to setup the sounder in the previous labs, and now, we will practice our programming skills and create a makeshift theramin. For those who don't know, a Theramin is a type of electronic musical instrument, that creates music based off of sensors that detect the spacing and the movement of your hands. What we will use as our sensor is the LDR (light-dependent-resistor), and will program our Arduino as a Theramin that works based off of the apparent light that the LDR detects. Let's try it out!
The circuit setup for the LDR.

Here we see the LDR Theramin in action. As I move my hand further and closer away (thus providing more or less light), the frequency emitted by the sounder will change, thus creating a different pitch of sound.

Using Arrays and Libraries

Now, we will delve even deeper. To play music, we must learn how to use arrays and external libraries. So, first we must define these terms. An array is a user-created set of variables that can be accessed using an index number. There are a few ways to create an array, some of which include these:
int myInts [6];   //Declares an arrays without initializing it as int myInts.
int myPins[] = {1, 3, 2, 5, 7};   //Declares an array without specifically choosing a size.
*Don't forget the semicolon!

To access the array, just enter myPins[somenumber 1 less than the maximum number of entries in the array, since arrays are zero-indexed (start counting at 0)].

To access outside libraries, we will use #include to include outside libraries (which will have been created previously, labeled as a filename.h type function).
Now, to use these to create music! There is  pitches.h file already created on the arduino website. Copy and paste it, access it and add it to your compiler/code! Use arrays to label and choose which notes are played and for how long. Then, use LEDs to light up in sync with the music. This is demonstrated below.

Using The Serial Port

Another important tool to learn to use is the Serial Monitor/Serial Port. The Serial Monitor is a window that relays and debugs information. To setup the serial monitor, use the following code:
Serial.begin(9600);   //This initializes the serial port with a BAUD rate of 9600. Baud refers to the number of bits transferred per second over the serial communications line.
To have the serial monitor return information back to you, use variations of the following code:
Serial.print(sensorValue);   or   Serial.println(sensorValue);    //These tell the serial monitor to type and send the values read from the sensor into the monitor. The 'ln' at the end of print returns the displayed characters on a new line of data (much like pressing Enter in a word processor).
Now that we know how to use it, we can program this serial port/monitor to turn on or turn off an LED whenever we type in either a "0" for LOW/off, or a "1" for HIGH/on.
Typing "0" in the serial monitor turns off the LED...

While typing "1" turns the LED on.
Example of the code used.

Hack-a-Toy

Using the skills we've practiced, now it is time to see whether or not we can get a pre-programmed toy to do certain actions that we want it to do. Let's begin!

First, remove the batteries so that we can gain access to the screws.

We had to cut off some of the skin in order to access all of the screws.


Here is how the inside of the toy works. It contains motors to dance, and buzzers/sounders to play music.

For now, we will try to access the motors and tell it to activate upon our Arduino's request.
Here we see the toy moving due to the Arduino choosing when to supply power.

Putting the cover back on.

And here we see the monkey dancing according to our program! By using a PWM signal, we can alternate when the motors will activate, and where they will spin.

#8 - Sensors, Sensors, Sensors: Arduino Interfacing With Sonar and Infrared Sensors

Sensors and Arduino

Now that we've become more familiarized with programming the Arduino and an assortment of input/output devices, we can delve into more complex sensors and interfacing, and will even be able to build our own sensors to assist us with our robot in the future.

The Ultrasonic Sensor

In this lab, we will be working with the HC-SR04 ultrasonic range finder module. In other words, we will be working with a type of Sonar sensor, and will be using it to detect objects, or, in the case of our VEX robot, we will use it to avoid contact with walls and other objects in a future competition. Aside from this particular use, there are also many things that sensors such as this one can be used for, such as: parking sensors, motion/tracking devices, and more. This module has four pins: a power pin (Vcc +5V), a "trigger" pin, an "echo" pin, and a grounding pin. The power pin and ground pin are used for supplying power to the module (remember to observe correct polarity when connecting them); while the trigger and echo pins both act as signaling pins. The Trigger pin works by emitting a 10 microsecond long pulse, this way the transmitter knows when to begin sending out eight 40kHz pulses, which will be used to calculate the distance of whatever object rebounds the signal. In other words, the Trigger pin is what sends out the sonar frequency signal, waits for it to hit an object and return, and then calculates the distances based off of that. The Echo pin will then output a Pulse-Width Modulation wave that is proportional in ON/HIGH time to the distance traveled. So now, let's try getting this to work!

Some new commands here are the "return" commands, which tells the arduino to return a value whenever it runs a specific loop. Use this to return a value in the serial monitor based off of the distance measured by the sonar sensor. 
The Ultrasonic Sensor (sonar) setup on the breadboard.


Here, we see the sonar sensor detecting my hand. Whenever I move my hand within a certain distance of the sensor, the LED will turn on, and a message in the serial monitor displayed, saying that my hand was "Too Close" to the sensor.

Infrared Sensors

Other types of sensors include the Flame Sensor and the Line Follower. These are both very similar, especially in construction, as they both use a component called the phototransistor. A phototransistor works very similarly to the regular transistors. However, the longer lead no longer represents the positive end, but rather represents the negative end now. In addition, this transistor has only 2 pins, as the Base signal will be determined by the lighting of the room (hence the prefix 'photo'). 

The Flame Sensor

The flame sensor is a very simple utilization of the phototransistor. It only requires one phototransistor in series with a resistor (don't forget the correct polarity!), and has the signal pin in-between those two components. The circuit will work as a flame sensor, as it will give Voltage values at the signal pin based off of how close a flame (or any other light of similar wavelength). We will create one to locate a flame for the Firefighting Competition. 
A simple flame sensor.

The Infrared Sensor as a Line Follower

Another simple sensor is the Line Follower. It is very similar in construction to the flame detector, except now we must use an infrared (IR) emitter along with the phototransistor. We must keep the two close together, as the sensor works by having the IR emitter emit pulses of infrared light that will bounce off of an object. The light that bounces back from the object will have refracted/changed (as some light will not be rebounded), and as such, there will be various values for the phototransistor to receive, all based off of the color the object was. By using this theory of operation and adjusting the limitations of values in our programming, we can set the sensor to follow a black line, or to perform specific functions once it reaches the black line.
The Line Follower Prototype.

Thursday, February 12, 2015

#9 - Bringing It All Together: VEX Robotics

The Final Stretch: VEX 

Cumulative Overview

We're in the final stages of this course, and now it is time to put all of our knowledge of circuit building and programming together! The final aim of this section is to implement the tools and functions needed to bring us to our final goal: The Firefighting Robot Competition, in which a robot must autonomously (on its own) navigate through a maze, locate a randomly placed fire, and extinguish it. BONUS: Returning to the starting position reduces the time total by a set amount (which is good!).
USB to serial port connector used for downloading our programs into our robot.

Now that we know how to program, let us jump right in! We began with a right turn about the robot's edge. We did this by only setting the left motor to move forward, while the right motor remained still.


Robot receiving commands.
Next, lets try moving forward! Setting both motors to an equal value should cause the robot to proceed forward. However, not all motors were created equal, so you might need to adjust values in order that the robot doesn't veer too far to the left or right! IMPORTANT NOTE: The motors are mirrored, thus, they will rotate in opposite directions if you set both values equal. An easy solution is to set the mirrored motor to " bMotorReflected[port #] = true; " so that it will move forward rather than just rotate your robot around.

Awaiting its turn to attempt the maze.
Using somewhat accurate measurements, we could set the motors to move for a certain amount of time (based on what we tell it), and thus we were able to navigate through a practice maze. However, there is a more accurate, simpler way...


That way includes the use of encoders! Encoders attach to the axles of the wheels, and measure the degrees of rotation that the wheel has gone through. By calculating the circumference of the wheel, we can determine a near exact distance of travel by programming the robot to only move a certain number of revolutions, allowing for much more precise movements through the maze.

The robot, version 2! Now with encoders. 

Now the robot shall navigate the maze, not based on timing, but based on accurate distance measurements. 


Next up: Robot version 2.1! Now with ultrasonic (whale-calling) capabilities! Please refer to previous blogs for how sonar sensors work. The man difference here, is that one of the sets of pins of the sonar sensor must be placed in a low number interrupt port. The other must go the the Analog/Digital ports. Don't forget to set up your sensor in the motors and sensors setup menu (select the correct port and interrupt, and choose SONAR)! 
How the beginning of your code should look after setting up sensors.


Now we see that the robot is avoiding contact with objects that it detects with its sonar (from a certain distance). The sonar can be particularly useful in avoiding walls in the Firefighting competition.

LINE FOLLOWER: An infrared LED and a phototransistor allow for the robot to detect differences in color on the ground. By changing values, we can set it to stop and perform certain functions whenever it meets a black line.
Above we see a version of the line follower, adjusted to now detect flames. The phototransistor detects certain wavelengths, and thus it is perfect for sensing and finding where our flame could be located, and once found, we can set the robot to extinguish the flame.

Robot version 3! We decided not to use the ultrasonic (sonar) sensor. But we did opt in for using the flame sensor and line follower!

Robot Version 4. Now with flame extinguishing power. Time for some test runs to seek, and exterminate the flame.
Good luck to all on the Firefighting Competition, and thank you to Professor Denny for teaching the Elec 10: Mechatronics course this winter; and a thank you to Tommy for assisting us! Greatly appreciated for your time and effort!

#4 - Introduction to Switches, Relays, and VEX Robotics (Inventory and Construction)

Switches and Relays

Now lets cover some key components for the course (and electronics in general): switches and relays. We will begin with switches as relays are a more advanced version of a switch. Switches are basically components used for toggling on/off portions of the circuit, by closing (or opening, depending on the switch) the circuit when pressed, and doing the opposite when released. There are many forms of switches: SPST (single-pole-single-throw), SPDT (single-pole-double-throw), DPDT (double-pole-double-throw), etc. A relay is a more advanced type of switch that uses a component called an inductor along with a type of switch mentioned above. When current flows through the inductor, it creates a magnetic field, which in turn attracts the switch, thus pulling it into a new position, toggling the state of the switch as long as the current holds. Below are pictures of a relay in use (the orange box).
When the switch is not pressed, the top LED lights up.

However, when pressed, the switch causes current to flow, thus creating a magnetic field in the inductor, and toggling the state of the relay. Now the bottom LED is lit.


Now for a variant. By adding a capacitor, we can make a oscillator.



Relay Oscillator: A variant of the previous circuit. When the switch is pressed, the magnetic field's induced voltage in tandem with the capacitor causes the state of the relay to oscillate-meaning that it toggles states at high frequency; thus alternating between which LED is lit quite frequently. One of the LEDs appears brighter because it is turning on more often than the other.

VEX

What this course will work up towards is the use of robotics. VEX is a brand of robotics products that aims at teaching the basics and advanced skills. Before we can begin building however, we needed to stop and first inventory a large portion of the parts (just to make sure we know what we're working with).

Inside the box was a removable tray with many screws/bolts, and various other parts.
We see wheels and frame parts for the robot.
Above we see the antennae for the robot, some push-button sensors, and limit switches. 
No moving robot is complete without sensors...
Or a large book to keep track of it all.


After much time and effort, our first version of the robot is complete! We will come back to these later, after we learn another important tool to robotics: programming!