GETTING TO KNOW ARDUINO
As software geeks, you might sometimes feel that hardware seems esoteric. For most people, electronics is always a bit of a mystery. They use it every day, but never really get the hang of how it actually works. This black box creates awe and that leads to the primordial fear of the unknown. But those of us who have been involved with electronics beginning at a younger age cannot help but revere that most interesting time in our lives, when our young minds were full of curiosity and we never feared to tinker with anything we got our hands on! It’s time to go down memory lane and get our hands dirty all over again. I recently ordered my own Arduino Uno online and got it the next day. I would love to share my thoughts about this electronic gizmo. The timing was also in sync with the Malcon 2012 conference, which had electronic warfare as the theme for this year. There was a workshop held the day before the main event for Arduino fanatics and I got a free invite, so…
This time around, you will get a tour of the miniature circuit that has made waves in the hobbyist and artistic circles recently. It’s the Arduino, translated as “dear friend/valuable friend/brave friend” in Italian (with Old Germanic origins). It is indeed your best friend as it holds your hand and guides you and motivates you to explore the world of electronics hardware, software, embedded programming, and interaction design. Arduino started as a way for Massimo Banzi to teach prototype designing at the Ivrea Institute by making software and hardware talk to each other seamlessly, thus making real world objects interact with the computer code. The innovator argues that this approach makes interaction design much more accessible to the more creative types, rather than just to niche groups of techno-wizards that speak Romulan. Unleashing the potential for an unlimited creative platform immediately made it a hit among all and sundry, literally. When I opened the box, I was a little surprised, as it’s about the size of a pack of cigarettes. Arduino is in reality a small PCB (printed circuit board) containing a controller from one of the Atmel AVR microcontroller chip families (ATMega) and supporting electronic components, along with USB serial output ports with various peripheral and connectivity options that come in the form of “shields” (additional modules). This is an open source project that incorporates the hardware–the Arduino–and the software IDE for programming the microcontroller. It’s very interesting what can be done with extending the domain of interactivity within the confines of a computer to the outside world.
For those of you who have long forgotten your semiconductor physics classes, a brief primer is on its way. Before we start, I suggest you look up some other related disciplines of tinkering that have also contributed to the whole phenomenon of “messing around with things till you find something interesting.” For example, you should Google “circuit bending.” That’s a movement started by Reed Ghazala in the 1960s that essentially never gets into electronics the way engineers and academics might like, but the results are very promising nonetheless. What happens here is that existing electronic circuits, from toys to microwave ovens and Casio keyboards to speak-and-spell devices, are taken apart and recombined in a myriad of ways just by “short circuiting” the various points in the circuits thus exposed, using two alligator cables or pin leads (just two wires, really). Essentially, once such random points of interest are found out, they are made a little more repeatable by soldering the connections that are actually short circuits and putting some sort of trigger switch between them. Using a simple pushbutton switch might result in an on-off cycle of electronic jumble resulting in a somewhat controllable mechanism that resembles an archaic sort of musical instrumentation. Similarly, using an LDR (light-dependent resistor) might trigger the sounds through proximity of the hand over the LDR (blocking light and thus varying resistance in the LDR), making it respond to hand movements much like the Theremin (an instrument that works by radio and magnetic field manipulation).
Most electronic circuits use a very familiar set of components that are combined to form a maze of logic. The most essential components are: 1) Diode 2) Capacitor 3) Resistor 4) Transistor. Other components such as solenoids, inductors and transformers, etc., have their own specific uses. Of particular interest are the diodes that come in various colors and types (single color LED, mixed color LED, laser diodes, zener diodes, etc.). Diodes are semiconductor devices, meaning that they conduct electricity in one direction only, and only after a special procedure called doping [an agent or added impurity added that creates regions called holes (+ve terminals) and electrons (–ve terminals)]. Current always flows from the +ve to the –ve terminal. This difference in potential is called the emf (electromotive force) or potential difference. LEDs (light emitting diodes) emit lights of different wavelengths, mainly in the primary colors, red, green, and blue (RGB). Diodes are used for AC rectification or conversion from AC to DC current, among other tasks. Zener diodes allow flow in the reverse direction as well after a breakdown voltage has been crossed.
Capacitors are used to store potential energy temporarily and discharge it slowly. They are very useful for cleaning a current by removing noise or disturbances from the signal. They mainly consist of dielectric materials that are kept at a very close distance, providing the bed for static charges to develop within the plates when the potential difference is applied between the poles of the capacitor.
Resistors are components that provide resistance. They come in various values that are color coded. The codes are read from left to right, with the 1st color giving the 1st digit, the second color giving the 2nd digit and the 3rd digit giving the number of zeroes. Further a tolerance value or the reliability of the resistor is also indicated in a band. Gold is the best, indicating 5 % tolerance.
Transistors are semiconductor devices that have three pairs of such semiconductors giving three junctions of the sandwich, coming in two possible combinations, the npn and the pnp types, where p stands for positive and n for negative. The collector, base, and emitter are the three main components of the transistor that are shifted according to the type. Transistors are very useful for voltage regulation and amplification and also can be arranged to act as automatic switches.
The current, voltage, and resistance are related as follows:
I=V/R or V=IR or R=V/I
Here, current is the amount of electricity flowing through a unit cross section of wire in unit time. Resistance is the measure of opposition to the flow of current. Voltage is the same as the potential difference. It follows from the above equation that current and resistance are inversely proportional, and thus, with increasing resistance, the flow of current decreases and vice versa. Compare the scenario to a water pump and a pipe with a tap. The tap would control the flow of water, so that would be the resistance; the pipe facilitates the flow of water or the amount of water flowing, which would be the analogy for the current, and the pump creates the work done that is transformed from centrifugal forces generated by the pump in the closed path simulating the circuit. If you increase the tap closure, you increase the resistance, thus letting less water flow out of the pipe.
Any electronic circuit can be connected in two fundamental ways, series or parallel. Series means one after the other like a daisy chain. Parallel means the path is divided between the components, and then recombined at the output. Parallel components draw less current while having the same voltage. In series, the current remains the same, but the voltage may drop over long paths.
The thing to remember is that, to calculate the resistances in series, simply add them together. In parallel, you sum the reciprocals of the same, and inverse that to get the final resistance value. Again, this differs for resistors and capacitors. For resistors, the calculation is as above. For capacitors, the process is the reverse. For a series, you take the sum of the reciprocals for the parallels, you take the direct sums.
Resistors are measured in ohms. The ohm is the unit of resistance. Capacitors have their capacitance measured in farads, most commonly in microfarads or picofarads. 1 farad is a very large unit (charging 1 ampere of current) and is not really used in the Arduino. Current is measured in amperes. Voltages are measured in volts. Most of the SI units are named for the discovering or theorizing scientists.
Enough of electronics theory! The bottom line is that there are electronic components that manipulate the flow of electrons and associated properties in ways that might produce a desirable phenomenon, which in turn can be exploited for our use.
My box contained the Arduino board, a set of stickers, and a user manual. Very slick and environment friendly. Let’s take a closer look at the various components of the Arduino board.
The main parts are the USB port and power jack, the automatic jumper chip, the ICSP (in-circuit serial programmer), the ATMega328P microcontroller, 13 digital pins, 6 analog pins (pins are also called headers or ports), the Rx and Tx pins (receiving and transmitting bytes), AREF (analog reference) pins, a reset switch, PWR ON LED, and another LED connected to pin 13 and GND (ground) for testing purposes. The operating voltage in the circuit is approximately 5 volts. That was the brief overview tour of the board.
The fun starts when you connect the board to your computer with the USB cable provided (USB A-B cables, B is the small square end).
Installation of the Arduino driver will be an issue if you depend on plug and play all the time. The solution is to make windows search the FTDI/USB drivers provided with the Arduino software, in the drivers folder. (For all information and faqs head to www.arduino.cc.) In Windows 7, go to the Device Manager and update the driver that is displayed as a failed port install. Manually search by choosing the option to browse to the folder and select the drivers directory in the Arduino package. It will install, then open the IDE; choose the type of board from the menu ToolsàBoardà[Board Types]. Further, check the COM port assigned by Windows to Arduino and set it accordingly in the Serial Portà[COM XX] menu. Optionally, a dialog box appears, giving the option to choose on the first install.
The power-on LED lights up, indicating that the board is working. Next up, we need to install the Arduino IDE that uses the Processing language. The IDE is the development environment of programs or”sketches” in ‘duino parlance. Here, the borders of software programming, embedded programming, and hardware controlling become blurred. You are using an interface that enables you to write simple logic statements in an intuitive language, that is compiled to intermediate states like object files àELF binaries and finally to INTEL format *.Hex files that are just plain byte codes for the microcontroller in textual format. A bunch of libraries and glue code do the bulk of the work to make the process so seamless. You essentially do two steps in the IDE: program the code, then press the upload button which verifies, compiles, and uploads the resulting hex file to the Atmel chip in the board via USB. Serial ports are named so because the transactions are done bit by bit in a serial one-after-the-other fashion. It’s slow (speeds are in bauds) but very stable. Once the sketch is uploaded, the Arduino runs the code repeatedly until reset or plugged out.
From left to right, the Compile and Verify button, the Upload button, the New, Open, and Save buttons.
The output console display at the bottom of the IDE.
Each Arduino sketch consists of two main parts, the setup() and the loop() functions.
The body of the program looks like…
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
For the newcomers, a function is logical grouping of a set of instructions that may expect an input for a corresponding output and is essentially self-contained. It can be called as many times as required just by referencing the function name. Here the functions don’t return a value but rather bound the activities going on within and process the instructions accordingly as per the language design. Here the setup() function initializes required parameters and is run only once. This function enables you to configure the boards prior to passing control to the next function. The loop() function infinitely loops over the set of instruction statements contained within its scope.
Let us write a simple program that is self-sufficient and does not require any additional components while demonstrating that Arduino indeed understand what you want it to do.
Type the following code in the IDE or simply navigate to the FileàExamplesà01BasicsàBlink. The source code is written for you.
Simply press Upload and watch the board reset itself (the set of LEDs near the pin 13 LED blink rapidly). Now the pin 13 LED blinks with the given speed as set in the delay parameter in milliseconds. Try changing the value to other values, lower or higher, to see if the board does what you expect it to.
What this program does is set up the pin 13 to OUTPUT mode using the function provided by the language in the IDE, the pinMode() function. This function takes two parameters, the pin number and the output/INPUT mode constant string. Next in the loop(), the digitalWrite() function takes the pinNumber and the voltage level–HIGH or LOW. This makes the pin either +5V (HIGH) or 0V (LOW) at the specific intervals after the delay() function/s parameter of 1000 milliseconds or 1 second. So effectively you see a 1-second blink of on-off. After the last delay, the control returns to the beginning of the loop() function, resulting in repetition. All sketches are programmed in a similar fashion. Post compilation, you will see a string in the output console of the IDE which displays the size of the compiled sketch in bytes and the total maximum size of the bytes supported by the microcontroller.
The next steps are to use a breadboard and jumper wires, a set of pushbutton switches, a stepper motor, a servo motor, a Darlington pair (a pair of transistors that regulate the voltage), IR receiver and IR transmitters, LDRs, a bunch of resistors with ranges from 10 ohms to 10,000 ohms, capacitors ranging from 100 micro farads to 600 microfarads, voltage regulators, and LCD displays among others. These components can be bought at any electronics store or you can get them prepackaged from Arduino vendors worldwide.
A brief and easy to understand description of the contents above:
The breadboard is actually an arrangement of wires that simplifies circuit prototyping and precludes the use of soldering (flux burns, anyone?) The most common breadboards have two sets of rows, on the left side and the right side of the board, that are used to provide power connection from the Arduino board or any other power source, such as batteries. The two rows are connected in any one of the holes, each vertical row for one terminal, the positive or the negative, and likewise for the other row. Within these two set of rows is another set of rows which is divided in the middle to accommodate microchips. Each division consists of five vertical columns repeated by the number of rows provided by the breadboard. Each horizontal row consisting of the five columns is connected by a metal strip. Think of a fish-bone-like structure, with every fin bone representing one metal strip. Every wire connection made in one of these strips can be shared by another component on the same strip. The other end has similar configuration.
Pushbutton switches are used to toggle between on and off modes. IR stands for Infrared, i.e., a wavelength longer than red, hence lower frequency, and both the receivers and the transmitters can be used to build useful projects, such as a simple security system that triggers if anyone crosses a trip wire made of infrared light. Stepper motors move in steps (angular displacement) and can be made to pause at a precise angle. Servo motors provide force feedback in reverse for every force applied forward. LCD stands for liquid crystal display, which uses polarization of light to display sequences using quartz crystals.
Further, the use of sensors in electronics has made devices really smart. A sensor is a device which can translate real world data into a set of voltages. This set of voltages can in turn be converted to digital numbers after normalizing the upper and lower ranges. This set of numbers can be calibrated and heuristics can be applied to detect anomalies and pattern changes that deviate from the statistical standards. Thus, at the end you have a sensitive and reliable indicator that simulates the real world. Very useful indeed. Computers are all about encoding and sensors help getting the data in a format that is friendly to the encoding process. Sensors can be pressure sensors, smoke sensors, chemical sensors, light sensors, humidity sensors, sweat level sensors, and the like. If any property can be measured, you can usually find a sensor for it.
A property of electronic devices, called bouncing, is caused by complicated laws of contact physics (more due to momentum and elastic properties of the contacts in a switch, a limitation of both design and material); simply put, it causes random and rapid fluctuations in the voltage levels prior to the actual activity required, thus causing a delay as well as false triggers and synchronization issues. This is like the Heisenberg principle for electronics. It is most noticeable in our arduino excursions while routing a pushbutton switch through our new circuits made in the breadboard. Here, the switching activity required by the pushbutton switch will not work in sync with the toggling code, without some debouncing code to compensate for the false triggers and random voltages. What is done in the code is that a specific range or a threshold is checked for before making the final transitions to on/off so that the random fluctuations are eliminated and only the real toggles made by full contact of the switch are taken into account. This is good use of software to solve a hardware problem; of course, it can be done in hardware as well, since the checking logic can be implemented along with other failsafes, but seven lines of code is better than three hours of circuit work any day of the week, especially for troubleshooting. A good set of debouncing libraries is provided in the Arduino software.
PWM (Pulse Width Modulation) is an activity performed by making use of percentages as in, any current passing through the circuit board is essentially a pulse of energy. That pulse of energy will stay active for a period of time. For every full voltage cycle, if the amount of time taken to reach full cycle (always on) is manipulated, what you have is a percentage of the full cycle, which effectively creates a phenomenon called pulse width modulation. Modulation means variation. Thus, we try to vary the pulse width so it can be visualized in a linear Cartesian graph as a set of square waves reaching full voltage and dropping to 0. The digital realm can simulate the analog using this trick. Dimming of LEDs, among other uses, can be demonstrated using PWM, where in 25%, 50% and 75%, cycles are alternated to give the intended effect. It is almost like an optical illusion of sorts, as the speed of modulation must be done fast enough that the brightness of the LED seems to be an average of the high and low voltages. Also, in this case the analog pins are used, as they translate the voltages over larger value ranges from 0 to 255 values, more like an 8-bit range and thus simulating analog. For the same, the analogWrite() function is used in the IDE code. Look for the code in File->Sketchbook->Examples->Analog samples.
We have discussed quite a few of the essentials for beginning your Arduino adventure. Believe it or not, you already have all the fundamentals you need to build your next super gizmo, at least on the electronic front. If you work on the code constructs and make infallible logic for your chips and breadboards, you have conquered this platform as well, and you’ve just got started! Browse arduino.cc and other sites, such as instructables.com. to see what can be created with this nifty little package.