Using Modulus Arithmetic to Navigate a Circular List

I have to go thru my notes every so often to find the formula for navigating backwards, so I’ll post this stuff here in case anyone else finds it useful.

Modulus math is very handy for dealing with circular functions like time. In fact, I use this to blow the minds of kids (I’m always trying to pique their interest in math and other technical stuff).

I’ll say something like “When is 11 + 2 = 1”? They will insist it cannot be and I tell them they see that very computation on a regular basis. After I have them telling me there is ABSOLUTELY NO WAY 11+2 EQUALS 1, I ask them what they get when they add 2 hours to 11:00. 1 O’CLOCK!!

Anyway, when writing software it is really useful to use modulus math to solve these little problems. To get 1:00 in software, I’d write

x = (11 + 2) % 12

x will contain 1

If you aren’t familiar with the C % operator (a.k.a the mod operator in Pascal), in essence it returns the remainder.  A / B (assuming A and B are ints) returns the quotient. A % B returns the remainder.

int(11 / 2) is 5
11 % 2 is 1

In fact, long ago when I wrote COBOL code, if I needed to do a MOD operation it was actually part of the DIVIDE statement:

DIVIDE  < literal-1 / data-item-1 >   INTO  < literal-2 / data-item-2 >
             GIVING  data-item-3... REMAINDER data-item-4...

Besides doing time calculations, I find modulus math very handy for treating an array as a circular list.

Most recently I implemented a simple LCD menu using the array:

const int listLen = 5;
char * list[listLen] = {"A","B","C","D","E"};

int i = 0;

When the program starts, it prints the first string in the list. It then waits for either an up or down button to be pressed:

// C like psuedo code
while (!done) {
    if (!keyAvail()) {}
    key = getKey();
    if (key == keyUp)
        // compute new i where we go forward in the list
        i = i + 1;
    else if (key == keyDown)
        // compute new i where we go backward in the list
        i = i - 1;

This works OK until we get to the end of the list. We need to wrap around when the user presses the up or down key.

Formula 1: Going forward from the last element to the first
i = (i + 1) % listLen

If i is 4, pointing to the last element in the array, formula 1 will add 1, giving 5. Then 5 % 5 is computed which is 0. We are now pointing back to the beginning of the list.

To go the other way:

Forumla 2: going backwards from the first element to the last
i = (i + (listLen-1)) % listLen

If i is currently 0, we add 4 (listLen-1), and get 4. Then 4 % 5 is 4, so we are correctly point to the last element in the list.

Formula 1 is easy to remember. Formula 2 I can never seem to make stick and have to look it up every time.

Here is the entire program in C like psuedo-code:

while (!done) {
    if (!keyAvail()) {}
    key = getKey();
    if (key == keyUp)
        // compute new i where we go forward in the list
        i = (i + 1) % listLen;
    else if (key == keyDown)
        // compute new i where we go backward in the list
        i = (i + (listLen - 1)) % listLen;

and Pascal-like psuedo-code:

while (not done) do
    if (not keyAvail) {}
    key = getKey;
    if key = keyUp then
        // compute new i where we go forward in the list
        i := (i + 1) mod listLen
    else if key = keyDown then
        // compute new i where we go backward in the list
        i := (i + (listLen - 1)) mod listLen;
Posted in c-arduino, c-lazarus | Tagged | Leave a comment

Writing Code to Handle Arduino’s millis() Roll Over

The Arduino’s millis() function returns the number of milliseconds since the arduino started running. It returns an unsigned long, 32 bit, value.

A 32 bit unsigned word can contain 0 – 4,294,967,285 (2^32-1). When millis() gets to 4,294,967,285 milliseconds and adds 1, it ‘rolls over’ to zero. It will take 49.7 days (4294967286 / 1000 / 60 / 60 / 24) for this to occur.

If you want your Arduino project to run continuously for more than 49 days you will want to take this roll over into account.

Unsigned Subtraction

Getting around the roll over issue is handled by using the subtraction property of unsigned words.

I’m going most of my examples using 8 bit unsigned words (or bytes). These are declared as uint8_t and can have the values 0 – 255 (2^8 – 1).

You cannot have a negative number stored in an unsigned word. If you have an uint8_t and subtract a large enough number such that the result is negative what happens?

uint8_t      x;

x = 0 - 1;

In binary, we start with zero


and subtracting 1 gives


or 255 in decimal. S0 0 – 1 is 255 when using uint8_t.

Here is the general algorithm the CPU is going to use to subtract two unsigned words, x – y:

if (x - y) < 0 then
  z = x - y + 2^ws
  z = x - y;

If (x-y) is positive, nothing special happens. If it is negative, we must add 2^ws where ws is the word size (we are currently using 8 bits).

Using this general rule, if you want to subtract 0 – 1, the result is going to be negative, so calculate z as

z = 0 - 1 + 256
z = 255

That’s exactly what was expected.

w = 255;

To be clear, YOU do not have do the above algorithm. It is done for you when you subtract two unsigned words:

uint8_t        a,c,x;
a = 0;
b = 1;
x = a - b;

and x now contains 255 because were are using uint8_t

Examples of Roll Overs

Let’s watch how subtraction works as roll overs occur. Assume x is increasing and rolls over. Let’s subtract 10 from each value of x and see what happens before and after the roll over (again, this is using an 8 bit unsigned word):

  x       x-10      x-10+2^8     z
254        244           n/a   244
255        245           n/a   245
  0        -10           246   246
  1         -9           247   247

as x approaches roll over (254 & 255)  x-10 returns a positive value and nothing more needs to be done; however, once x rolls over, a negative value is calculated and so we must add 2^8 which gives us the correct answer thru the entire sequence: 244, 245, 246, 247.

Now let’s consider the same thing with a 32 bit unsigned word:

x            x-10         x-10+2^32    z
4294967294   4294967284   n/a          4294967284
4294967295   4294967285   n/a          4294967285
0            -10          4294967286   4294967286
1            -9           4294967287   4294967287

Now imagine x is the current value of millis() and the constant 10 was the initial value of millis().  millis() – oldMillis returns the next proper value when millis() rolls over.

You may be looking at the x-10 result which is also nearing 2^32-1, and thinking that’s about to roll over anyway – this didn’t buy anything. This is only because I selected such a low value of 10 for the subtraction to keep the example simple. In real life this most likely will not be an issue (see The Catch).

Using Unsigned Subtraction to Our Advantage

Now that you’ve seen how unsigned subtraction works during roll over, let’s take advantage of it in a program.

We need to track the initial value of millis() when we start the timer and we need to know how long the timer should last. I typically use the names xxxTimer and xxxTimeout for these variables and define them something like this:

const unsigned long keyTimeout = 1000UL; 

unsigned long keyTimer;

You start the timer by assigning the current value of millis() to it:

keyTimer = millis();

This is the important part: you must subtract the initial timer from the current millis() value and compare that to your timeout. As long as you do that, your program will handle a roll over just fine:

while (test) {
  if (millis() - keyTimer > keyTimeout){ 
    << code to handle the timeout >>
  << rest of the code >>

The Catch

Well, this isn’t really a catch as much as a usage consideration. The word size of  the return value of millis() limits the length of the timeout. You cannot have a timeout larger than 2^32-1 milliseconds (49.7 days) even if roll over does work properly.

In the 32 bit example above, I set the initial value of millis() of 10. When millis() rolls over, it will be just 10 msecs short of exceeding the maximum allowed timeout. So while the roll over works fine, the I’m about to exceed the maximum possible timeout.

Note on UL Constants

You may have noticed that I used UL on my constants to force their typing such as 1000UL. You may wonder why.

For simple assignments, this really buys nothing:

xxxTimeout = 1000UL;

However, I tend to use constant expressions so I can read the code a little easier. For example, if I want a timeout of an hour I will code it as:

xxxTimeout = 1UL * 60UL * 60UL * 1000UL;

(1 hour * 60 minutes * 60 seconds * 1000 msecs)

rather than

xxxTimeout = 3600000UL;

If I need to make a change I’ll see that expression and realize it is for 1 hour and if I need 2, I just change the first constant (since the expression is evaluated at compile time I loose nothing do this).

The problem I’ve had is the C++ compiler periodically will NOT compute the constant expression properly if I don’t typecast each constant. This has bit me enough times that I simply never leave UL off any constant (or really any other non-integer constant for that matter).

I cannot say what the exact circumstances are to cause this issue because in every case, by the time I figured out what was going wrong I was too irritated to research the root of the problem.

Posted in c-arduino | Tagged | Leave a comment

Obtaining a Local Phone Number for Google Voice

I’ve been through this process twice now, so I figured I’d document it if anyone else needs it.

I’ve created several Google Voice accounts in the past 5 years, and there are never any local phone numbers available. My city is medium-sized, but I guess all the numbers GV allocated have been taken.

On my first attempt 5 years ago, the nearest number was in a town 30 miles away. Not long distance, but I really wanted an in-town number. On my most recent attempt, the only numbers available were in the megatropolis 250 miles away.

The problem can be resolved by obtaining and porting a cell phone number. This isn’t free, but it will work.

  • Create a GV account. Let it assign whatever free number you can get for initial testing. If you’ve never used Google Voice, take some time to learn it. You might decide you don’t need a local number.
  • I’m going to assume you have an unlocked GSM cell phone available. Using locked phones or CDMA phones adds more twists to the process and I’ve not done it that way myself.
  • If you don’t have an unlocked GSM phone, you can probably find one dirt cheap on ebay or amazon. You are only going to need to use it for a day.
  • Purchase a pay-as-you SIM card which will be assigned its own phone number. I went to Walmart and picked up an AT&T GO phone SIM card for $10. I strongly suggest using a big name company like AT&T or T-mobile. You may have issues with the porting process for small companies (I tried using Consumer Cellular on my latest attempt but had some problems so I had to fall back to AT&T).
  • Follow the instructions to activate the SIM card.
  • When you register the SIM card, put in your address. Google will want ask for this for porting and I can’t tell you not using it will work.
  • I didn’t get any choice regarding the phone #, but it was tied to the zipcode entered, so it is a local number. In other words, those in my town won’t have to call long distance to reach me.
  • You will need to buy some air time. I used the unlimited usage for $2 / day plan and bought the bare minimum time which was another $10.
  • Make sure the phone is working and you can place/receive calls on the new SIM card.
  • You are going to need your account number and possibly the pin number. With AT&T, you cannot determine the account number yourself. I had to call AT&T customer service (611) and ask for my account #. The nice Indian chap (I’m not being sarcastic), asked me why I wanted it (he knows why I want it), but I gave him a vague “I’d like to have it for my records” kind of response. He didn’t say anything, but I have to wonder if he could see my account had been activated only 10 minutes prior. Never the less, he gave it to me without any additional questioning.
  • Now with the account #, pin #, and valid account info (name/addr), you have enough information to port the number.
  • Return to the Google Voice website and go to Settings | Phone. You will see your original phone number and a Change/Port link next to it.
  • Click on this link and enter the phone number of the cell phone which you want to port (assign) to your Google Voice Account.
  • You will be asked to confirm about 10 questions acknowledging you really want to do this). Once you click on them all, you will be in the porting request screen.
  • The porting request screen should properly identify your carrier and you can enter your account number and identification information. You may or may not need to enter your PIN.
  • Finally, you will be required to pay a $20 porting fee. If something fails during the port, this will be refunded.
  • Once you are done, the porting process starts and will take place in about 24 hours. During that time, the old numbers will continue to work right up until the port occurs.

Total cost to get a local phone number: $40. Not free, but not too much to have a number that is a local call for all my land-line friends.

Obihai users: The Google voice account I did this with had my Obihai VoIP box connected to it which had been configured and was running fine. When the new number was ported to GV, the Obihai continued to work just fine using the new number. I didn’t have to change anything in its configuration.

Posted in c-Misc | Tagged | Leave a comment

Preventing Peg Board Hooks from Coming Out of the Peg Board

Just a quick tip:

I grabbed a crescent wrench from its hook on the peg board and the hook fell back behind something for the 100th time. After swearing at the hook, I decided it was time to fix all of the loose hooks that constantly do this to me.

In the past I’ve tried hook locks like these with partial success:

It’s hit and miss if they will work on my old peg board and even if they do they eventually work loose and get lost.

At some time in the past year I saw what appeared to be a great tip – hot glue the hooks into place. You just need a hot glue gun. I don’t do much hot gluing, so I have a very cheap ($12) glue gun like this (actually mine isn’t even this nice):

I tried it on the hooks that cause me constant problems and so far it works great. When I’m in a rush (always), tools come off and the hooks stay on.

I simply pull the hook out, put plenty of glue in the one or two holes the hook will use, then get the hook back in place before the glue dries. Very simple.

The downside is the hook is now hard to remove. I mistakenly placed one in the wrong place and managed to rip the face of the peg board a bit getting it out. But, for me, this isn’t much of a disadvantage, I don’t reorganize my peg board. I just infill or add new.

That being said, I didn’t glue down everything. Just the one hole hooks and several hooks that use two holes. No sense in fixing something that isn’t really broke and maybe some day I will want to take out.

If this idea doesn’t pan out, I’ll come back and report the issue.


Posted in c-Misc | Tagged | Leave a comment

Project Box Graphics


After building my project’s box (see here), I wanted to create some decent graphics. I spent a fair amount of money on the guts, I did a nice job cutting holes, I expect the ‘customer’ will have this for several years, so it should look good.

Many months ago this problem had crossed my mind and it occurred to me to experiment with printing on adhesive vinyl such as this:

I did some test prints and let them sit around for months and was pretty happy with the color and durability.

Once my project box was done, I designed a graphic to cover  the top of the box using Adobe Illustrator for the basic box and photoshop to handle font effects. Photoshop, GIMP, or any such tool will work fine.

I printed the graphic on the adhesive vinyl. I figured I needed something to help protect the ink. I talked to an artist friend to find out what she puts on her paintings. I ended up spraying the vinyl with several coats of clear krylon with a matt finish.

I applied this to the box. This vinyl can be pulled back up a bit as you apply it so it is forgiving if mistakes are made.

I was super happy with the results. Best looking project box I’ve ever done. Finished assembling the box and continued testing now that all components were in the box.

During the week of testing I found that the ink was way too easy to scratch. Since the background of the graphic is a dark purple, scratches resulted in the underlying white showing thru and even tiny dings were noticeable.

So I went back to the drawing board trying to find a cheap but workable solution to producing graphics for my projects. I really didn’t find anything that looked promising but someone in some blog suggested the questioner go to a print shop and see what they could do for him.

That sounded like good advice so I went to a print shop who sent me to a sign shop. They had solutions but they were expensive – minimum job was $150. As I talked to them about their process, they said they would print to vinyl adhesive as well, but then they laminated it.

As I was driving home pondering this, I had considered laminate before but the only laminate I’m familiar with is the stuff you apply with a laminator and that wasn’t going to work so I forgot about it. When I got home I did a little research and found there is (obviously) single sided laminate.

I went to the local office supply store and came home with two types. Contact Clear Cover which has a mat finish:

and Fellows Single sided Laminating sheets (glossy finish):

I created test graphics with both. They both were reasonable and the gloss/mat finish was what one would expect.

I decided on the gloss finish (Fellowes) because the adhesive was much stronger and the material is much thicker.

Two tools useful for creating the final graphic are:

A rubber roller like this:

and a cutting mat like this (as well as a sharp razor):

I also have a steel ruler with a cork pad which is useful for holding the graphics tight while cutting.

OK, here is how I create the graphic:

  • Wash the box with rubbing alcohol.
  • Print the design on the adhesive vinyl (make sure you are printing on the correct side – it is hard to tell). Do make sure that you are using the correct printer settings based on the vinyl you choose. Mine requires using ‘other photo paper’ to get best result.
  • Trim the vinyl as necessary so there isn’t much extra material (I keep about 1/4″ material around the actual ink).
  • Cut down a piece of laminate such that it will be somewhat larger than the vinyl you just trimmed.
  • Using canned air, blow all dust off top of the vinyl graphic. When using canned air to clean like this, always apply it gently – you don’t want a blast of coolant coming out of the can and mucking up your work.
  • Layout the laminate with the sticky side up. Remove the backing from the laminate.
  • Now place the vinyl with the printed side down (against the sticky side of the laminate). There is no redoing this, so get it right the first time.
  • It seems I have luck by touching the bottom edge of the vinyl to the laminate, keeping it slightly bowed toward the laminate, then kind of ‘roll’ the vinyl down onto the laminate and pressing my finger down the center line as I do this. Once the vinyl is down then I smooth with my fingers.
  • Next I trim the laminate so there is very little over hanging.
  • Flip everything over and roll it out with the roller. Maybe I’m just lucky, but I didn’t have air pocket issues to begin with, so the roller didn’t need to press out air pockets, just make sure I had good adhesion.
  • Now it is just a matter of doing the final trim using a straight edge and razor.
  • Use canned air on the project boxto make sure it is clean – any bump is noticeable thru the glossy graphic.
  • Remove backing off vinyl, revealing the adhesive.
  • I applied the graphic onto the box in the same manner as the vinyl onto the laminate, starting at the bottom and rolling it into place. I used the roller again, here, to make sure I had the best adhesion possible.

Once the graphic was in place, I discovered one shortcoming I didn’t expect – you need to make sure that the graphic holes are such that they are a bit bigger than the box holes. When you insert components, if the vinyl flexes due to a component pushing it into the hole, you get kind of a lip.

I trimmed the excess with an exacto knife but the round holes still showed a bit of a ring.

Nevertheless, the final result looked really good.


I put the two test graphics in a spot where they will be constantly touched to see how well they hold up. I’ll try and remember to report back on the long term test.

Aug 2016 Update:

I ended up putting both sample graphics right below my keyboard so my hands rub across them constantly all day long. Neither have scratched, but the glossy laminated graphic finally separated from the constant rubbing.

In normal applications, where the graphic isn’t being touched constantly, I would guesstimate this graphic is going to last quite some time.

Dec 2016 Update:

An alternative to adhesive vinyl is adhesive photo paper. I’ve been experimenting with this:

LD Glossy Sticker Paper

Photo paper isn’t going to stand up to any kind of abuse/moisture, but laminating it as I did the vinyl will solve those issues.

Color Matching Issue

I’ve had the same issue with this paper as I have had with the adhesive vinyl which I didn’t discuss initially. Colors show up quite flat (black is more a gray). A deep purple I wanted to print ends up close to a dark gray on this paper.

If you want to get an idea of the difference between printing your decal on photo paper and an adhesive backed paper, print a reference image on both types of paper. This will allow you get an idea how the paper will perform. I have used this reference image for close to 2 decades now to determine if my printer/paper combo is going to be reasonable:

which is available here:

I wanted to print very specific colors (matching a business card) which required creating an ICC profile for my printer/paper combo. I bought Monaco Color management software back around 2003 which evidently been bought by x-rite or pantone. I imagine it is still quite expensive.

If you find you have the same problem and need colors to properly match, google ‘create icc profile’. I spent many long hours years ago banging my head against the wall trying to get colors to match perfectly (at least near). These days, typically printer manufacturers do a great job as long as you use their paper.

If you use the Inkpress Adhesive Vinyl I suggested, you can go to their website and download an ICC profile for their paper if you have one of their tested printers. This does require that you know how to use these profiles (another sink for time if you don’t). The LD adhesive photopaper has no profile.

I have a photographer friend who, rather than get the printer to match what he sees on the monitor, does the opposite – he prints a reference picture and then adjusts the monitor until it matches the picture. Then what he sees is what will print.



Posted in c-electronics | Tagged | Leave a comment

Cutting Holes in an ABS Plastic Project Box

Wrapping up a project and it is time for the case. I purchased a nice heavy duty case from Mouser to use. It needs several holes which are easy enough but it also needs a large rectangle cut out as well. In the past, cutting square holes has proven to be difficult for me.

Since you can find how to do anything on the web these days I went looking for help. Most of the procedures I saw seemed like the results were going to be rough or I simply didn’t have the necessary tools.

Then I found a tip at the end of this post:

His description was detailed and easy to follow, but I’ll toss in some pics as well.

  • I created an outline of the hole on the top of the box using a pencil and a combination square to make sure it was square.
  • I then applied masking tape leaving just the hole. In retrospect, I wish I had taped the entire box to protect it from any scratches during the cutting process. Next time…


  • Using a 1/16″ drill bit, I cut holes into each of the corners.
  • I then used a pencil to draw lines between the corners to find the center point of the hole.
  • With the center located, I drilled out a large enough hole in the center to allow a saw blade in.
  • Using an air saw, I cut from the center hole to each corner. This was the hardest part of the process – the plastic would melt and the blade would finally bind. I found that it worked better if I applied pressure for a couple of seconds, backed off, and tried again. The high speed of the saw blade probably made this worse.  Once I was done my box looked like this:


Had I used a saw or nippers, these rough cuts are what my holes normally look like which require a lot of filing and are still rough. That’s what I like about this process, the final lines are going to look way better.

  • In the picture above I have already clamped down a straight edge. I use this straight edge to run a box cutter from each end to the middle (that way the box cutter never slips and cuts the outside edge of the hole. This box is roughly 3mm thick and I probably ran the box cutter over the line 20 times to get a deep enough score cut for the next step.
  • With the outside edge of the triangle deeply scored, I then slowly bended the triangle down until it snapped off. Doing so, I ended up with a very clean outside edge:


  • Repeat the process for the other sides and you end up with a very clean hole:


  • Drilling out holes is much easier. In the past I would use a center punch to mark the center of the hole, start with a very small drill bit, then work up thru the various sizes until I got to the final diameter. Works but kind of slow.
  • This time I used the center punch, then used a step drill bit until I got to the correct size. Using this bit, the process when a lot quicker and the final hole seemed a bit smoother.
  • To finish the square hole, I just used a file. To finish the round holes, I used a deburring tool like this:

  • I bought the deburring tool on a whim and never regretted it. I’ve used it quite a few times and it is far better than trying a round file.

That’s it. I ended up with a great looking case:


I should mention that once the case was done, applied graphics to a vinyl sticker that over layed much of the top of the box. This has button labels, product name, etc on it. This is my first attempt at using such a sticker. Time will tell if it lasts very well.




Posted in c-electronics | Tagged | 4 Comments

How to use VeeCAD Stripboard Editor with CadSoft Eagle

A project I’m working on is a one-off. Since I’m only building one, having a real PCB created is over kill. In the past I would etch my own, but I’m getting to where the chemicals bug me so I prefer not to.

In the past I’ve played with stripboard, but trying to lay components out on it made me dizzier than etchant. It occurred to me that perhaps someone has created software to help lay these boards out.

Sure enough they have. I decided to use VeeCAD. VeeCAD is pretty cool, but it was designed primarily to be used with TinyCad. All well and good, but I really don’t have time to learn another Schematic Editor. I want to design in Eagle and then layout components with VeeCAD.

As I tried to learn how to use Eagle and VeeCAD together, there was very little information available on the process (mainly a few questions in the VeeCAD forum). So as I went thru the process, I kept notes so I can repeat the process again.

Enclosed are my notes in PDF form. I cleaned them up a bit for public consumption, but they are pretty rough. Still, it should be enough to get you thru the process.

VeeCad Notes

Posted in c-electronics | Tagged | Leave a comment

SIM800L GSM/GPRS Part II – Seeking Stability

My first SIM800L dev board was a flop when I tried to use it in an actual project. As mentioned at the end of my last post, the reliability of that SIM800L dev board was horrible. The SIM800L chip would reset regularly – as in roughly every 5 texts or less.

After pondering the problem, I decided I wanted a SIM800L dev board that doesn’t have an onboard voltage regulator. I want control over the power myself even if I am going to have to provide 4.2V rather than 5.

I found this dev board on amazon which fits the bill. No power regulation but it does still give me access to the RST signal:

Further, one of the SIM800L ‘hints’ I stumbled across while troubleshooting my power issue is to use a DC-DC converter rather than a voltage regulator. The comment was it can respond to the current surge faster. I found 7such a module that provides 3A which significantly more than the 2A voltage regulator I was using so I decided to order one of those from Amazon as well:

Clean Power

First, I setup and tested the DC-DC converter. This unit take 4.5V to 24V in and produces 0.8V to 20V. It is a buck converter, so the input voltage needs to be higher than the output. I’m converting 9V to 4.2V so no problem there. There is a tiny trimpot on the converter that is used to adjust the voltage. Before ever connecting this to the cellular chip, I made sure it was producing the proper voltage.

Once the DC-DC converter was functioning, I then setup all of the filtering as specified by the SIM800L datasheet:


Ca is 100uF and Cb is 1uF. The zener diode helps protect the SIM800L chip from over voltage.

Soldering Headers to SIM800L Dev Board

This dev board will not sit on a breadboard properly. But if you only want VCC, RST, TX, RX, and GND that is no problem. All of those signals are on the same side of the board and the pitch is .1″ so a header fits fine on that side.

Connecting SIM800L to PC via FTDI

Before I plug these new components into my project, I want to make sure everything works properly. To do that, I connect the SIM800L dev board to my PC via an FTDI converter. In this case, I want to use a 3.3V FTDI converter. The FTDI converter will only have ground, TX, and RX connected.

Here is the schematic:


not the best picture, but here is the actual setup:



I inserted this power supply and cellular chip into my ailing project and no power issues! When the thermal printer on the 9V power supply kicks in, there is little noise on the 4.2V supply. The project is still undergoing stress testing, but so far the 4.2 power supply and the SIM800L dev card have not had any issues.



Posted in c-electronics | Tagged | 9 Comments

SIM800L GSM/GPRS Cellular Eval Board First Look

I’ve built a project using a SIM900 GSM/GPRS dev card. It works fine, but that dev card is too big to fit in the project case and kind of expensive (comparatively speaking).

I went looking for another solution and found the SIM800L:


Looking thru the manual, it supports all of the AT commands I implemented on the SIM900 in my project. It is also quad-band, so it should work in the U.S.

I found a SIM800L dev card on ebay for $10 so I bought a couple. The downside was it came from China and took a month to get here. Much slower than most of the stuff I have purchased from China in the past.


This schematic seems to match up with the particular SIM800L dev board I have:

The SIM800L Datasheet:

and the AT commands:

Getting It Running

The first thing I wanted to do was get the card connected to my PC so I could verify I could access it, then make sure that it works with my cellular carrier. To do this, I connected the SIM800L dev board to a standard 5V FTDI cable such as:

I am using a 5V FTDI cable. The dev board needs 5V and the tx/rx lines are 5V tolerant.

Connecting the cable to the devboard is very simple using male/female jumper cables:


and here is the final test setup:


If you’ve not used an FTDI cable before, it needs drivers. I believe in Windows 7 and on these will be located automatically. If not, the provider should make drivers available to you.

Once the cable is plugged in, you should see RING diode light continously and the NET diode will flash.

To connect to the dev board, I am using putty. First I need to determine the COM port that was assigned to the FTDI cable which can be found in the device manager:


Now start up putty, select Serial for the connection type, enter the COM port from device manager, and speed is most likely 9600 baud:


Type AT and press enter (the first time I do this, I don’t see the AT echo back). Once you press ENTER, you should see the AT followed by OK.

If you don’t get anything, make sure the wires between your TX/RX lines are correct. Tx goes to Rx and vice versa. If you see garbage, chances are you need to try a different baud rate.

Once AT by itself works, I tried a few other commands to verify operation:




AT+CPIN? is supposed to report SIM card status. Since it hasn’t been installed yet, I guess this ERROR is OK.

Obtaining the SIM Card

To make this device work, you will need a functioning GSM SIM card. Fastest way to take care of this problem is to go to a store and get a pay as you go SIM card. If you don’t have a phone that can make use of that card, you might want to pickup a cheap unlocked GSM cell phone for testing as well.

My normal carrier is a GSM carrier (AT&T, T-Mobile, or any of a host of other carriers that use AT&T or T-Mobile’s networks). I can request an additional line and they just send me a free SIM card. I pay $10 / mo for the additional line and it shares my existing data/text plan.

As already mentioned, it is easier to activate the SIM card if you put it in a phone first. Once you can place calls/texts on the test phone you are sure the SIM card works and any problems you might encounter will not likely be due to the SIM card or carrier.

Inserting the SIM Card

The SIM card is inserted with the contacts towards the PCB and the notched end sticking OUT!


Now the SIM card status command returns ready:


The AT+CNUM reports the correct phone number:

+CNUM: "","1xxxyyyzzzz",129,7,4

AT+CSQ reports roughly 50% signal quality (max is 31):

+CSQ: 17,0

Obtaining Current Time

By default, the SIM800L is not set up to track time status messages coming from the carrier. So if you request the time via AT+CCLK?, it will be wrong. To fix this, type these commands:


Now cycle power on the SIM800. If you connect to the serial port fast enough, you’ll actually see the time ‘commands’ coming from the carrier:


Call Ready

SMS Ready

+CTZV: -28,1

*PSUTTZ: 2016,3,26,17,49,24,"-28",1

DST: 1

and now if you request the time, it will be correct:

+CCLK: "16/03/26,10:49:36-28"

Using the RESET Pin

There are 2 downsides to the SIM900 DEV board I have – it will not come up without you manually pressing the POWER KEY and there is no way to force it to reset. Supposedly there are ways to solder connections to handle these issues, but that is still a bit clumsy.

The SIM800L holds the POWER KEY on for you so as soon as it gets power it is running. That is what I need for my project.

The next question is how does the RESET pin work?

Like one would expect – I grounded RESET and it forced the SIM800L to restart. Perfect!

Apr 2016 Update:

I purchased 2 of these to use in a project. They are both so unreliable they are worthless. Regularly they reset. This is an indication there is not enough power – they need 2A of clean power. Well, I have put them both on a 5A bench power supply and still have issues. Further, I followed the datasheet regarding filtering and that didn’t help either.

I’m trying a simpler board next (no onboard power circuitry nor a reset pin) to see if I can make it work. If it is any better, I’ll post an update.

Yep, much better luck with a different board. Click here to see it.

Posted in c-electronics | Tagged | 5 Comments

Adafruit Thermal Printer Library haspaper() Function Fix

I posted this ‘fix’ on Adafruits’ forum as well.

I have been playing with their mini Thermal Printer (

I started testing the haspaper function in their thermal printer library which returns true if there is paper else false. In the library I have, it fails to detect paper out.

After researching the problem, the only comment I can find is this function is iffy. Might work, might not, depending on the printer.

That seemed kind of odd to me because the printer obviously knows paper is out – it flashes its LED 3 times fast to let the user know and if you attempt to print something, it will not let you print. So if the sensor is there, why wouldn’t they let the end-user sense it?

I found the datasheet for the printer ( and found the escape sequence to detect the printer status is <esc>v<null>. Looking at the code for hasprinter, they are sending <gs>r<null>.

<gr>r<null> is used to determine if the paper is nearly out. If there is no paper, it doesn’t indicate that.

I changed the escape sequence in the hasprinter function from

writeBytes(ASCII_GS, 'r', 0);


writeBytes(ASCII_ESC, 'v', 0);

Now the hasprinter() function in the Adafruit library works properly for me, letting me know when I’m out of paper.

Posted in c-arduino, c-electronics | Tagged | 1 Comment