Using tabs in Arduino IDE

If you plan to write a moderate to long program in Arduino IDE, you should learn to use tabs to keep your codes organized. Let’s talk about this issue in some details.

First, you should have a plan, what kind of problem you are trying to solve with your program, how you will solve it. But most of the time we only had a rough idea what we are going to do and as we are doing it our programs grow bigger and messier. OK, if you follow my suggestions on how to use tabs (i.e. separate your one giant file into several smaller files), you will survive:

You should try to cut your program into smaller pieces, so that each piece represents a specific set of functions. Say you have a sonic ranger in your setup. Then you will likely have sonic ranger reading functions, displaying distance from reading, displaying speed from distance readings. These functions are better off separated from those that read and display value from a temperature sensor.

You can keep all these pieces in your main program file but soon your main program becomes too long and you find yourself scrolling the side bar up and down, looking for one bit of program to modify.

Here is how to separate your program into several pieces, each having its own file name.

  1. Press this button to drop down a menu, then select new tab.
  2. On the bottom of the arduino IDE window, type a name descriptive enough, like measure for all your sensor measurement functions.
  3. Cut your sensor measurement functions from your main program, and paste them in the newly created file, which is now a tab inside arduino IDE.
  4. To make matter even more clear, add several lines of comment describing what these functions do. This also helps you organize your functions.

Here is an explanation of what you have just done: if you write codes in separate .pde files, you need not worry anything regarding whether one function in one file knows the other functions defined in other files as all .pde files are concatenated into one file before arduino IDE compiles everything so it the same as writing all those lines of code in one file, just more organized.

Essentially, you should only keep all variable definitions, setup() and loop() in your main .pde file, and disperse all your functions into their separate .pde files, like this one in picture.

Starting here, you will have to seriously programmed for quite some time to hit another road block to need my following help:

Say you have succeeded in creating many hundred lines of code. You have also come to understand the importance of using #define and PROGMEM. The head of your main .pde becomes annoyingly long like this but only more lines:

#ifdef stand-alone
// Stand-alone photogate setting
#define button1_pin 11 //enter
#define button2_pin 13 //down pause
#define button3_pin 12 //up unpause
#define button4_pin 10 //Escape
#define gate0_pin 15
#define gate1_pin 14
#define gate2_pin 17
#define gate3_pin 16
#endif

#ifdef shield
// Photogate shield setting
#define button1_pin 12
#define button2_pin 11
#define button3_pin 10
#define gate0_pin 3
#define gate1_pin 2
#endif

#define pulley_spokes 10 //16 spokes are evenly laid on the pulley.
#define storage_size 100
#define rotation_update_time 1000000
#define two_pi 6.2831853
//#define vol_a_val (10.0000/1024.0000) // This maps -5V to +5V into 0-5V with a bipolar to unipolar converter.
//#define vol_b_val (-5.0000)
#define vol_a_val (5.0000/1024.0000) // This is the default mapping for internal AD converter.
#define vol_b_val (0.0000)

Now you are contemplating on adding just another tab, called includes.pde

In that tab you type : #define haha 7

In your main program you have int data=haha;

You compile, and an error pops up:

What the ?$%^& You defined haha but the IDE fails to recognize it? You quit coding and go on and forget arduino all together. Maybe you should read on for the source of the error instead:

First do int data=7; so you can complete the compile. Then take a look at the temporary file arduino IDE generated under:

C:\Users\owner\AppData\Local\Temp\

Under a folder called build1555865782840320506.tmp or like, you can find all the files generated by arduino IDE while compiling.

You can find more about these files on this blog post: http://smileymicros.com/blog/2011/02/10/where-is-the-arduino-hex-file/

Open that .cpp file that is named the same name as your main .pde file and look in the very end you will find the answer:

#include “WProgram.h”
void setup();
void loop();
int clock = 6; // Define encoder pin A
int data = 7; // Define encoder pin B
int count = 0; // pre-init the count to zero
int c = LOW; // pre-init the state of pin A low
int cLast = LOW; // and make its last val the same – ie no change
int d = LOW; // and make the data val low as well

void setup() {
pinMode (clock,INPUT); // setup the pins as inputs
pinMode (data,INPUT);
Serial.begin (9600); // and give some serial debugging
}

void loop() {
c = digitalRead(clock); // read pin A as clock
d = digitalRead(data); // read pin B as data

if (c != cLast) { // clock pin has changed value… now we can do stuff
d = c^d; // work out direction using an XOR
if ( d ) {
count–; // non-zero is Anti-clockwise
}else{
count++; // zero is therefore anti-clockwise
}
Serial.print (“Jog:: count:”);
Serial.println(count);
cLast = c; // store current clock state for next pass
}
}

#define haha 7

Aha! The content of your includes.pde is concatenated to the END of your main .pde file! Have you heard of “define before use”?

This is what arduino IDE does, it concatenates all .pde files, starting with the main .pde then in alphabetic order. So if you define something in a .pde file or tab, then the definition appears after the main .pde and the defined entity CANNOT be used in main .pde or any other .pde file that is alphabetically ahead of the file that has the definition. DARN IT!

How do you fix that?! Maybe return all the #define lines to the main .pde and curse the arduino IDE and get over with it?! You should simply choose to read on.

To really think out of box, we need to separate those pesky #define lines from our beautiful main .pde, and we need those #define lines to be compiled AHEAD of the main .pde! That is right, AHEAD of the main .pde. You are thinking in the correct direction. To redirect the order in which the compiler compiles, you can use a HEADER file! Have you not programmed in the old-fashioned C? Always have “#include <stdio.h>”? Don’t worry, we’ll get there.

Now let’s change that includes.pde into includes.h

Then in the beginning of your main program, add the following magical line: #include “includes.h”

Then modify your code so again you have int data=haha;

Compile, succeed!

Here is the temporary output file:

#include “includes.h”
#include “WProgram.h”
void setup();
void loop();
int clock = 6; // Define encoder pin A
int data = haha; // Define encoder pin B
int count = 0; // pre-init the count to zero
int c = LOW; // pre-init the state of pin A low
int cLast = LOW; // and make its last val the same – ie no change
int d = LOW; // and make the data val low as well

void setup() {
pinMode (clock,INPUT); // setup the pins as inputs
pinMode (data,INPUT);
Serial.begin (9600); // and give some serial debugging
}

void loop() {
c = digitalRead(clock); // read pin A as clock
d = digitalRead(data); // read pin B as data

if (c != cLast) { // clock pin has changed value… now we can do stuff
d = c^d; // work out direction using an XOR
if ( d ) {
count–; // non-zero is Anti-clockwise
}else{
count++; // zero is therefore anti-clockwise
}
Serial.print (“Jog:: count:”);
Serial.println(count);
cLast = c; // store current clock state for next pass
}
}

Notice the “#define haha 7” line is gone from the end of the temp file. But a line #include “includes.h” appears in the beginning of the file. The function of this include line is to insert the content of the included file i.e. “includes.h” right where the #include line appears in the file. This way, anything you write in the includes.h file appears magically before the main content of your main program, when it compiles.

We call #include a pre-compiler command or directive. It tells the compiler where to locate a file and insert its content at the spots of this very #include command. So if you have

Dear Sir and Madam,

#include <declaration of independence>

Thank you for your attention!

then the entire content of the declaration of independence appears in your speech, whether it’s relevant or not.

Now that you’ve spent so much time reading this post and learned a trick or two, you may want to read on to learn all the tricks.

With #include, we can put all the #define lines in our “includes.h” files, then add #include “includes.h” in the beginning of the main program, tada!

Maybe now you get a bit over confident and start to move variable definitions into includes.h

Sorry to tell you, that won’t work.

This post is already too long and we are wandering off topic. So to continue on the solution to your problem, please read on how I use different files to organize my project. See you on another post!

My project became featured project on instructables.com

Just between last night and today, as of noon, as many as 300 visitors read my project on the car reverse obstacle sensors on instructables.com, making it a featured project!

Now I know the secret ingredient to more visits: arduino + car! I happen to have a similar taste to lots of people online.

Here is the instructables.com post:

http://www.instructables.com/id/Arduino-reverse-obstacle-sensor-for-cars/

I will add some more details to it later today.

Here is my blog post:

http://liudresllc.com/2011/02/12/arduino-parking-sensor/

New project codes

Starting from my most recent project – car backing/reverse obstacle sensor with a sonic ranger, I am offering two versions of the project code, a full version, so you get all the interactive features, adjustable parameters, and make changes if you’re good at programming. I also offer a nutshell version, where only bare minimal code is included to run the sensors for beginners to easily digest and modify.

I will find some time to re-do my previous project codes so they will have two versions for both beginners and advanced users.

Plus, if I find more time, I will re-do the interactive interfaces to standardize them so you can load up the code and wallah you have your menu, all keys work as they should on a menu and you have a list of adjustable parameters to start your project with. It is essentially a shell of functions so you can focus on your project’s function and let the shell handle all interactive features including menus, refresh displays, and key presses. This is like the Liudr look and feel (as compared with Java look and feel).

Arduino parking sensor

(This project is also posted on instructables http://www.instructables.com/id/Arduino-reverse-obstacle-sensor-for-cars/)

My wife has told me about a reverse/backing parking sensor her friend has on their car. It helps someone parallel park in a tight spot. We normally don’t need one but I can see sometimes having one will really help. So I set out to make her one tonight.

As a physicist, I have to lecture on the principle of the sonic ranger a bit. It is a rather simple device, the small cousin of the police speed gun! The sonic ranger sends a few pulses of supersonic waves and waits for the waves to bounce back from an object in front of it. Once it detects the reflected sound, it knows how much time it took the waves to travel a round trip from the ranger to the obstacle and back. With speed of sound at around 340m/s, you can calculate the distance to an object. You can also find velocity if you measure distance at two consecutive times and do distance change over time. Bats use their sonic ranger to fly in pitch black caves or catch food! Mr. English also tried the same technique with no apparent training and failed miserably. One episode of Stan Lee’s super heroes also featured a blind person using his tongue clicks to tell what’s around! That’s it for sonic ranger intro!

Diagram from Parallax

After some coding, wiring, swearing, I’ve got a working prototype. It has the following functions:

  1. Displays distance to an obstacle in feet/inch and mm.
  2. Display analog distance as bar graph
  3. Audio alert of distance as frequency of beeps, like a radioactive sensor (Geiger Muller counter) so that the beeps become more frequent as the car approaches the obstacle closer.
  4. Adjustable audio alert beep frequency so she can pick an appropriate parameter just for her.

I’ve listed the parts here:

  1. One arduino Duemilanove or UNO (many vendors sell this)
  2. One Phi-1 shield kit for arduino (dipmicro.com) I designed this shield. Here is documentation. They also sell this on ebay.
  3. One RJ11 jack and breakout board. I made some breakout boards myself and used the RJ11 jack from the Phi-1 kit. But you can buy from sparkfun: Rj11 jack and RJ11 breakout board. You have to observe which pin is which with a multimeter.
  4. One four-wire phone cable. Just go to a dollar store and make sure you’re not getting two-wire cables.
  5. One Ping or other ultrasonic sensor from parallax. Alternatively you can also buy this one from sparkfun.  You will have to make sure you’re connecting the PWM pins to arduino. I don’t have this.
  6. One 1uF capacitor. You can get it anywhere you but the other parts.
  7. Either a car power adapter that outputs center-positive 9V to 12V or a 9V battery with a connector from here http://dipmicro.com/store/BH9V

First, assemble your Phi-1 kit. Make sure you solder on the buzzer on top right corner, and one RJ11 jack on the bottom right corner, like in this picture:

Next, test it with the test code found on the Phi-1 shield home page to make sure it works.

Assembling hardware is easy:

  1. Solder the RJ11 jack on its breakout board.
  2. Connect phone cord between the shield and the RJ11 jack with breakout board. Determine which pin on the breakout board goes where on the shield

  1. You will need a cable or solder three wires to the sonic ranger. I found this connector in my drawer but if you don’t have one, go to a surplus store. Old CD-roms also have these wires. Make sure you get the right pin to the sonic ranger. Test with mulitmeter. I used my own breakout board so all signals are marked. Since the cable is only 3-pin, I had to feed 5V on the X pin on my shield. I jumped the x pin to 5V. If you have a cdrom cable you have 4 pins and can switch out pin orders easily with a small jeweler’s screw driver. The output of the sonic ranger should go to arduino channel 2 Y, which is connected to analog 3.
  2. Stick a 1uF capacitor between 5V and GND to filter out noise. Trust me, this is not optional! Observe polarity of your cap.
  3. Run my program and use it!

I have made two versions of the program, a fully interactive one with menu and adjustable parameters. Another version is a nutshell, if you’re interested in learning how things work quick.

Full version

Nutshell version

Phi-menu version (see my phi-menu page)

Testing:

First I tested it indoors with my wife. Everything works fine (first two videos).

Since it’s warm today (by our local standard) so I got out and installed the sensor with my wife. It worked! (next four videos).

12FT 4-wire phone cord, about 10 pieces of wide tape and some masking tape later, the sensor is on my rear bumper sticker. I had it on my trunk first but it is angled and too high. It couldn’t detect a car but a garage door was fine. So I moved it to the middle of the rear bumper cover.

Here are some pictures I took in a parking lot after backing towards some other dude’s car seriously close (more than I am comfortable without the sensor).

Problem:

Since there is only one sensor, backing straight is most accurate but backing while turning is not. I need at least two sensors one on each side to cover both sides. Since I’ve got this thing working, I’ve become more observant and saw many newer cars have small attachments on their rear bumper covers, two or four. I suppose they’re either the sonic rangers or empty spots for installation. Will save money for a second sensor 🙂

If you are copying this project, make sure you get two rangers. Phi-1 shield can pass two signals on one 4-wire phone cord. Also make sure you get sensors built for wider angular response so you’re not just testing obstacles right behind but on the side as well. Mine is built for precise measurement so it only detects object more or less right in its line of sight.

Updated housing and mounting options:

I’ve made a small plastic sheet housing out of some 3X5 card holder with my blade half way and fold into a box, then attach some cardboard behind the sensor to prevent it from sliding, nice! Now attaching some 3M command pads with “velcro” I can attach my sensor on my car and easily remove it when it rains outside.

I will mount the sensor next weekend.

More updates today: I turned on the sensor in my electronics class to show my students how it works but to my surprise it’s not working! I then realized we have acoustic ceiling panels that absorb sounds! So I instead pointed it to the floor. Not working either. Nor did the white board. I just got random numbers around 500mm+-300mm. I tried and tried. Then I thought maybe my new housing is interfering  with the sound or my capacitor was not well connected. The I tried it in an electronics lab with the same results, the floor is not accurately sensed beyond 400mm.

Then I went back to my office and thought I had to rip the nice housing open. Before I decided to do it, I gave it a last try in my office. Well, it worked again! I guess very plainer materials like floor tiles and white boards reflect most sound just as they do light, mirror reflection so it’s very hard to make the sound reflect exactly back to the source to be detected. But I have carpet in my office, perfect scatterer, so it scatters in all directions. Although scattering reduces reflected intensity very largely, it makes the reflection a wide-angle source so the reflection (although weak) makes it back to the source to get amplified and detected. The number is stable again and physics work! Hahaha!

Here’s the videos:

Run 1 video:

Run 2 video:

Pulling away from garage door:

Driving towards garage door:

In parking lot very close to another car:

Display:

Measure temperature

There are many ways to measure temperature with an Arduino. We will discuss how to use a thermistor and a temperature IC.

Here is a picture of a 10K thermistor:

Here is a picture of a temperature IC, LM35:

The principle behind a thermistor (or the sensing component of a temperature IC) is the physics of semiconductors. A thermistor is a heavily-doped semiconductor. A semiconductor is conducting weakly compared with a conductor like copper but much more conductive compared with insulators like rubber.

The ability to conduct depends on a few factors. Among them, the amount of conducting charges in the material is quite important, which is directly proportional to the conductivity of the material. Insulators have very little conducting charges but conductors have a lot. The amount of charges in these two types of material don’t change much near room temperature. Semiconductors on the other hand, have moderate amount of conducting charges, whose quantity changes very largely as temperature changes. At high temperature, a semiconductor releases more conduction charges, it is less resistive. At low temperature, it releases less conduction charges and is thus more resistive. If you dope a semiconductor, the change of resistance becomes more pronounced for easy measurement.

So to sum it up, a thermistor is a resistor, whose resistance value decreases with increasing temperature, the therm- and -istor. This is like transistor is trans- and -istor. To measure temperature, we measure the resistance of a thermistor with a voltage divider. Let’s build a voltage divider and measure some temperatures.

First, purchase some 10KOhm thermistors for any electronics vendor. They should provide you the temperature vs. resistance data or formula to calculate temperature from resistance.

Then build a voltage divider and put a 10KOhm resistor in series with the thermistor. Connect 5V to the resistor and GND to the thermistor.

Now the voltage at the junction between the resistor and thermistor will change when ther thermistor changes resistance at a change of temperature. The more resistive, the higher the voltage.

Connect an analog channel to the junction. You can then sense the voltage and output to PC or display on an LCD screen.

Test the above parts with a multimeter before attempting to program Arduino to display temperature.

To display temperature, you may copy down the resistance of your 10KOhm thermistor at all different temperatures into an array.

Then read the voltage, convert voltage into resistance from simple circuit calculations.

R=V/(5-V)*10KOhm

If you care about error bar, read my Resistor sorter theoretical error.

Every time you read in a voltage, convert it into resistance, then look up the table for two values that are closest to your reading, use interpolation to find a more exact temperature value. You can also use the formula provided to you by the manufacturer to estimate the temperature like this one:

Formula 1 (complete expression).

or a simplified version:

Formula 2 (Simplified formula that gives resistance at temperature T(k))

You need to invert the function obviously to get temperature:

Formula 3 (Simplified formula that gives temperature T(k) at certain resistance R(ohm))

The values of T1, R1, and B should be given to you in the spec sheet, such as T1=298K (ie. 25DegC), R1=10K (the resistance of the thermistor at T1 temperature, so a “10K” thermistor will have R1=10K at 25DegC), B=4050K. The calculated result is in Kelvin. After subtracting 273 you will get DegC.

If this is too much math for you, I have good news, the temperature IC makes it easier to read temperature:

You may also use a temperature IC. Most common temperature ICs are either calibrated for degree C or F, like the LM35 is calibrated to degree C. They output a voltage proportional to these temperatures, both positive and negative, say 10mV/C or 10mV/F. Connect the output of the IC to Arduino analog input and you are good to go. Arduino can’t measure negative voltages so you either have to limit your measurement above 0DegC or 0DegF, or you can find one that reports Kelvin, which never reaches zero. Another way to measure negative voltage is to shift it to positive voltage with a bipolar to unipolar converter circuit. You will need a few things to construct a converter, which I can cover in a different post.

Notes:

If you are measuring temperature near where your arduino is, the LM35 gives the easiest way to achieve that. On the other hand, if you measure temperature at a distance and have to run a long wire between arduino and the temperature sensor, you should use a thermistor to reduce noise. You can always pick the best serial resistor for your thermistor so the output voltage is neither too high nor too low.

More on discrete thermistors:

You need to choose the right fixed resistor for optimal accuracy. First determine your range of temperature you measure first, then find the middle of that range, and pick a fixed resistor that has the same resistance as the thermistor if it were at the middle of the temperature range. IE. if your temperature measurement is around 25DegC and you are using a 10Kohm thermistor, you need a 10Kohm fixed resistor in series to the thermistor. If you use a say 200Kohm thermistor with R1=200Kohm and B=4022K (use formula 2 and 3), and your temperature range is -30DegC to 50DegC, so center is 10DegC, then you need a fixed resistor that matches the thermistor resistance at 10DegC, which is 409Kohm according to formula 2. So you either use 390Kohm or 430Kohm as both are standard values easy to obtain.

There exist applications of heating up thermistors with large current. If you want to tell liquid level, you can use the liquid as heat sink and apply larger current on the thermistors so only those ones in the liquid will stay cool and have large resistance. The ones outside liquid are hot and less resistive.

Some simple code for 10Kohm thermistor sensing:

void setup()

{

Serial.begin(9600);

}

void loop()

{

float resistance, voltage, r_fixed, T0, T, R0,B;
T0 = 298.15;//initial temperature for calibration
R0 = 10000;//initial resistance for calibration
r_fixed = 10972;//known resistance
B = 4050;//B for normalization
Serial.println(“Temperature”);

while(1)
{
voltage = analogRead(sensor_a)*5.0/1024;// Renormalizing from 0 to 5 volts.
resistance = voltage*r_fixed/(5.00-voltage);//find unknown resistance
T = 1/(log(resistance/r_fixed)/B+1/T0)-273.14;//find temperature from unknown ressistance
delay(500);
Serial.println(T);

}
}

Hall effect switches

Sometimes you find a non-contact switch is very useful in sensing presence and speed. Take car speedometer for example, you need to know how many turns the wheel makes per second to find the car’s speed. You could use a mechanical system to find out the speed of the wheel but a mechanical system is prone to failure. You need a non-contact measurement of the rotation of the wheel. In quantum physics, there exists no way that would measure something without changing the one being measured so no real non-contact measurement exists. But when everyday measurement is concerned, lots of ways constitute non-contact measurement. One can use a photo gate to tell speed. On the other hand, mud can also get into the system and prevents a photo sensor from working properly. An alternative is to use magnets and magnetic sensors. If you attach a magnet to the moving part of your wheel, then attach a magnetic sensor to a non-moving part of your car, close to the moving magnet, you can detect the presence of the magnet every time the wheel brings the magnet close to the sensor. If you keep your count and work out the relation between counts and angular speed, then angular speed and linear speed, you can display it on the speedometer.

So the sensor that we are going to use is a Hall effect switch, which is a digital element that outputs HIGH and LOW under different conditions. Here is the principle:

From physics, magnetic field affects charged particles. Inside a semiconductor, the charge carriers can be either positive or negative. Say you pass positive charge from left to right at a constant rate (current is constant). Then the magnetic field will affect the charge carriers and deflect them towards the side. The deflected charges are deposited on the side of the semiconductor, which set up an electric field. The electric field does just the opposite what the magnetic field does, deflecting the charges the other way around. Once there are enough deflected charges, the electric field will exert enough force to the moving charges to completely cancel the force from the magnetic field. At this point, the deflection stops and charge carriers flow through in a straight line. The stronger the magnetic field, the more charges need to be deposited and the greater the electric field. You can measure the field in terms of voltages, and deduce the amount of magnetic field strength, which is proportional to the voltage.

Here is a Hall effect switch:

There are three pins, 5V, ground, and signal.

For this particular one, bringing in North pole to it will result it to switch to HIGH. Then removing the north pole will not return the switch to LOW until the south pole is brought close to it. It will output LOW. A switch that retains its state until a different condition is met is called a latch. When north pole is brought near, the switch latches to HIGH, until when a south pole is brought in and the switch is latched to LOW.

Another type of sensor is not latched so if it senses north pole, it will switch to HIGH, then if north pole switch is removed, it switches to LOW. To find the switch that fits you, you should read the spec sheets on the logic behaviors.

Here is the link to the latching switch sold at sparkfun.com

Here is the link to the non-latching switch sold at adafruit.com

With the non-latching switch as trigger, I was able to create a persistence of vision display. Come back and read more about my persistence of vision display when I post it!

Power your arduino

When you prototype your project, you are powering your arduino with the USB power. Once you’re ready for some field test, say the arduino controls your room temperature, you no longer want to tether your arduino on your computer, rather you need to power it either with a battery or an AC adapter

1. AC adapter

Arduino starting from Duemilanove has an automatic voltage selection chip that will switch to AC adapter or USB as needed so there is no need for jumpers or else. The arduino should be powered by an AC adapter that outputs DC. Some adapters outputs AC so read the description adapter. The barrel should accept 2.1mm center pin on the arduino power jack. Lots of adapters can fit but fails to secure so you will have power losses when the adapter plug is slightly twisted or turned. The best way to buy an adapter is to test it out. Here are the required specs:

Input: 110VAC or your local power grid voltage

Output: suggest 9V to 12V although you can go as low as 7V or as high as maybe 16V. 9V and 12V are most commonly found

Current limit: at least 200mA but hopefully no more than 1000mA or 1A. Unless you’re driving motors or powering large bright LEDs, choose a smaller current limit so if you short something, the adapter gives you an additional layer to avoid damage. If you choose a current limit that is too small, then the voltage will drop when excessive current is drawn until the protection circuit in the adapter trips and turns it off.

Polarity: This is very important. It has to be center-positive. A symbol for center-positive adapter is a “c” and a dot at the center of the c, with a line leading to the opening of the “c” and a positive sign next to it, indicating the center is positive. Here is a picture from wiki: we need the left one.

Where to buy: the best place to shop for an adapter is a surplus store. You can try out any one of them if you want and you pay only $2 for one. Elsewhere it’s wasting money and postage. When shopping for an adapter, try to pick one that is light-weight. The heavier ones are old-fashion transformers while the lighter ones are newer and use switching technology that saves energy.

2. Battery

To conveniently power your arduino with a battery, you can use a rechargeable 9V battery with an adapter like the following one:

http://dipmicro.com/store/TEB-10003

You will need this clip:

http://dipmicro.com/store/BH9V

Once you get the battery and clip, feed the red to Vin on the bottom of arduino and black to one of the two ground  pins near Vin. I once soldered two male pins on the end of the wires so it’s better than two bare wires that could touch each other any time.

The 9V battery, especially a rechargeable one won’t last very long. You may want to power your project with Lithium batteries. I have no experience on this topic. Maybe I will add something once I learn about it.

How to optimize your Arduino memory usage

If you are unfortunately hitting the memory limit on your arduino, let me first take the moment to congratulate you! You have already become a master of arduino and programming. Otherwise you would not have come up with so many lines of code to fill your arduino up!

Go through the typical practice I go through and trim some fat from your program so you will squeeze more onto your arduino.

First, you should know what content goes to what memory: program and variable initial values go to Flash, variables and their initial values go to SRAM. Yes, initial values go in both places. Read this if you want more understanding on what ram is what.

Now if Arduino IDE tells you your sketch is too long, it is complaining your sketch is bigger than the Flash. You should do the following things to reduce that usage:

1) Have you been using function calls instead of repeating your codes?

Eg. repeating code to blink LED:

void setup()

{}

void loop()

{

digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);

digitalWrite(2,HIGH);
delay(300);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(300);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(300);
digitalWrite(2,LOW);
delay(25);

digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);
digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);

}

This is very long and detailed. It offers no hint of what you’re doing but instead tells you all the details you don’t want to know and takes too much space. You should do the following:

Define a function to do the blink and call the function every time you want to blink:

void blink_long()

{

digitalWrite(2,HIGH); // This blinks the LED for 300ms
delay(300);
digitalWrite(2,LOW);
delay(25);
}
void blink_short()// This blinks the LED for 100ms
{
digitalWrite(2,HIGH);
delay(100);
digitalWrite(2,LOW);
delay(25);
}

void setup()
{}

void loop()
{
blink_short();
blink_short();
blink_short();

blink_long();
blink_long();
blink_long();

blink_short();
blink_short();
blink_short();

}
Aha! You were sending the Morse code of SOS for help! Now it is super clear. You have also saved precious memory on your arduino Flash. From my test with Duemilanove, compile size is 1136 bytes for the long and tedious version but only 896 bytes for the short and tidy version. Have in mind that the 448 bytes were used as overhead. The actual size of your sketch’s function is 688 bytes for the long version and 448 bytes for the short version. This doesn’t sound like much but version long costs you 76 bytes memory per beep while version short costs you 50 bytes memory per beep. This all adds up. Just think about more complicated functions.

2) Have you been too verbose in your messages?

Say you do Serial.print(“Haha, you know what, the resistance is just as we expected, 100 Ohm, right on my man!”);

You should be doing this instead Serial.print(resistance);

Output the bare essential to not waste your storage space on arduino.

Also, if you have several places where you output essentially the same messages, make them exactly same. Arduino IDE will optimize and only keep one copy of the message so you save Flash.

Eg.

Serial.print(“This egg is bad, it is green!”);

Serial.print(“This egg is also bad, it is pretty green!”);

Serial.print(“This is a bad egg waiter, it is green!”);

You should output “Bad egg! It’s green!” instead so similar messages don’t get stored in three different ways on the Flash.

3) Have you been using all the compiled functions?

Say you have Serial.begin() in you setup and a few Serial.print() functions spread out in your code, initially for debugging. Now you’re fully confident with your code, you should remove them or comment them out. Otherwise if a function appears in your code, it will be stored in the Flash. If you shed the libraries you don’t need, you will save considerable amount of space. Arduino IDE does a good job on this but you can always help by removing junks.

4) Have you avoided function overloads? This is an advanced topic and should only be attempted by the experienced.

Say you want to print a few numbers to your serial monitor, you do this;

int a=10;
float b=1.57;
void setup()
{
Serial.begin(115200);
}

void loop()
{
Serial.print(a);
Serial.print(b);
}
Compiled size is 3570 bytes.

Instead you should have never overloaded the Serial.print(float) function and stick to Serial.print(int) instead:

Serial.print(a);
Serial.print(int(b));
Serial.print(int(100*(b-int(b))));

Compiled size is only 3064 bytes. Although we increased the complexity of the code, we have avoided to overload the Serial.print(float), saving 500 bytes. In larger programs, you will always use Serial.print(char[]) method and possibly sprintf() to organize your output. In this case, stop using Serial.print(float) or even Serial.print(int) just because you’re lazy. Always use sprint() and Serial.print(char[]) so you save from not overloading two functions.

Now if you want to optimize your SRAM, you should watch out the above plus the following:

1) Have you used the appropriate variable types for the job?

If your variable can be stored in a short, don’t use long. If it is not float, use int. This is especially useful if you have arrays.

You should also think about your measurements. Say you want to store voltages from an analog input, you used float array to store 2.503V etc. Wrong! You should have used an int array to store the original reading, which is only between 0 and 1024. You save 50% space just by doing this. You can convert them later if you want.

2) Shorten your char [] sizes to appropriate sizes.

If you are using a 16X2 LCD, define char msg[17];

You don’t need too much more than 16 characters as message buffer.

3) Have you used too many string literals? This is again for advanced programmers.

If you have many strings in your program, you should use PROGMEM to store them in the Flash and access them only when needed. I have a whole other topic on this issue so it’s not detailed here.

In retrospect, I have regretted taking my above suggestions a couple times so you want to know about this too. Aggressively reducing variable size can lead to overflow and memory corrupt. Make sure you’re not giving too little space for your variables and plan for future expansion.

Arduino memory

Add to FacebookAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to TwitterAdd to TechnoratiAdd to Yahoo BuzzAdd to Newsvine

Do you ever wonder how much memory your arduino has and should you worry about it running out? Here is the answer:

There are three types of memory on the arduino’s main chip, the ATMEGA328 chip:SRAM, flash RAM, and EEPROM. Here is what they do:

SRAM holds all the variables you define, including integers, floats, strings, objects, etc, as well as the stack, the space used in function calls. There are only 2KB or 2048 bytes of SRAM on board so one should make some effort to save this memory. This RAM is volatile meaning its content is wiped clean when power is removed.

Flash RAM holds the arduino bootloader and the entire compiled program. The total size is 32KB or 32768 bytes. The bootloader is typically 2KB or less, leaving about 30KB for your compiled program. This memory is checked by Arduino IDE and will not be run out without the IDE complaining to you first. From my experience, around 100 lines of C code will consume 1KB or flash RAM. The initial value of a variable is also stored in the Flash RAM. If you have char msg[]=”Hello”; in your program. First it shows up on the Flash RAM as initial value of msg being “Hello”, then when the program starts running, “Hello” will be copied to the SRAM so taking space in both flash and SRAM. This is unfortunate for variables like an integer but constant strings don’t change their values so they don’t need to reside in SRAM at all time. With a mechanism, you can keep them in flash until you need them. Then load them to SRAM, use the string, then dump it. Flash RAM is non-volatile meaning its content is retained in case power is removed.

EEPROM is electrically erasable programmable read-only memory. It is used to store parameters and small amount of data so that every time arduino starts up, it can load the parameters and data. Then you can change these parameters and save them to the EEPROM so your changes won’t be lost when you power off. There are 1KB or 1024 bytes of EEPROM on ATMEGA328, the chip that UNO and Duemilanove use. EEPROM is slow so it is not practical to store variable on EEPROM.

 

For suggestions on how to optimize your arduino memory, read this post.

%d