Handling Counter Wrap Around

You need to delay a certain amount of time ticks. Easy, right? You can just say:

/* Do some things */
/* wait for target time to pass */
while (get_ticks()<target);

This works fine as long as adding 100 (the delay count) to the current tick counter doesn’t cause an overflow. Remember 100 is 64 hex and consider this 16-bit counter incident (assuming 16 bit math):

target=get_ticks();  // target=0xFFF0
target=target+100;   // target=0054
while (get_ticks()<target);  // get_ticks is FFFE which is not < 54! Immediate fall through

The same problem occurs with any wrap around, regardless of the word size. However, there is an old trick as long as you can do unsigned math. Let’s look at the following cases:

Case A: Current tick=0x0000; target=0x0100

Case B: Current tick=0xFFFE; target=0x00FE

Case C: Current tick=0xFF00; target=0x0000

When you do a subtraction, the top bit will be set if there was a borrow off the end of the word. That is, subtracting 0x0010 from 0x1234 is really the same as subtracting 0x0010 from 0x11234 and and the end you throw away the extra bit at the left. This helps solve our problem. What if you subtracted the target time from the current time?

Let’s consider the case where the tick is just one more than the original current tick:

Case A: 0x0001-0x0100 = 0xFF01

Case B: 0xFFFF-0x00FE= 0xFF01

Case C: 0xFF01-0x0000=0xFF01

And the case where the current tick has wrapped but isn’t up to the target yet (only applies to B):

Case B: 0x0000-0x00FE=0xFF02

Then consider the case when you are one away from matching:

Case A: 0x00FF-0x0100=0xFFFF

Case B: 0x00FD-0x00FE=0xFFFF

Case C: 0xFFFF-0x0000=0xFFFF

Of course, when you hit the target, you get zero. The key takeaway here is that every result will have bit 15 (in this case; the top bit, in general) set until the result matches. This can be fast to implement. For example, here’s a 32-bit timer from an NXP LCP111x delay loop:

// Set up timer 0 
// Ok here's our start time 
// do some stuff here and when done 
// compute the target 
count counts=~counts; // convert to count up (this counter runs down) 
counts+=474; // how many ticks before we proceed (40nS per tick + a little overhead) 
do { clock=~PIT->CHANNEL[0].CVAL; // again, convert to up count 
 } while (clock-counts>=0x80000000UL); // could do a bit test here as well (e.g., while (clock_counts[31]);


Naturally, there are other ways to solve this. If the timer isn’t used for anything else, I could have preloaded it and waited for it to hit zero, but that’s not always an option.

Easy mbed Programming from Linux

If you use mbed you know it is cool not to have to install compilers or build libraries and toolchains. You just enter some code, grab some up to date libraries and press compile. Everything runs in your browser and you download a binary file with your program in it. However, you still have to get it to the board. Most of the Arm boards look like a USB drive and you can simply copy or move the file over to do a program. However, I get tired of manually doing that step. This is especially a problem if you use a GUI. You have to remember to move and not copy (so your browser doesn’t keep renaming the file) and you also need to keep confirming the overwrite on the phantom file still on the “fake” USB drive.
So instead, I write a little command line “script” to do it all for me. You could use inotify, but this is easy and I just do it when I’m developing and stop it when I’m done. Suppose your object file is XXX.bin and you are in the /tmp/mbed directory.

Open a shell and go to the /tmp/mbed directory. In my case, the fake USB drive is at /media/USER/FRDM-KL25Z. Then enter this:

while true
 do if [ - f XXX.bin ]
 then echo Programming
 sleep 1
 mv -f XXX.bin /media/USER/FRDM-KL25Z 
 echo Done
 sleep 2

Now when you save your binary file to /tmp/mbed, it will automatically program the device. Simple!

Quick Qt5 Example for GP3

I noticed Qt5 has a QtSerialPort class. Here’s a simple example of talking to the GP3  using this library:


    static int state=0;
    QSerialPort port("ttyUSB8",this);  // works with /dev/ttyUSB8 or ttyUSB8
    qDebug()<<port.write(state?"\x0C":"\x0D",1);  // Turns on/off light

Pretty simple. You can read data back either blocking or using slots. I’ll cook up an example of that later.

Rigol DS1052E and DS1102E Delayed Trigger


I have an old Tek scope. A great 50MHz analog beast that was surely the envy of every engineer — well every engineer in 1976 anyway.

Of course, its a Tek so it is built like a tank and has the usual great features — for a 1976-vintage analog scope. One thing it has that is very cool is “delayed sweep.” The idea is that the scope will trigger as normal and then you can pick a fixed time delay and a different time base to actually drive the display. Huh? All that means is that while watching a regular wave form you can “zoom” in on a section of it. The delay tells you how far into the original screen to start, and the faster sweep gives you the zoom factor. The user interface for this is comical but effective. The scope has a special mode where the time delay and “zoomed” time base makes the trace very bright. So you twist the knobs until the part you want to zoom in on is bright and then you can zoom in.

The Rigol DS1102E (or is it a DS1052E? I forget) has the same capability, but being digital it is very simple and the user interface is much more effective. See the screen shot? The top trace shows a 32kHz PWM signal (about 4%) generated, of course, from a . The bottom trace is the “zoom in” — you can pick delayed sweep from the menus or if you are lazy just click the horizontal scale knob (did you know if you press and hold any button you’ll get help — unless you’ve uploaded unofficial firmware).

Once you turn on delayed sweep you get blue bars on the top that show you the part of the wave you are zooming. You can move the trace with the horizontal position knob and change the zoom level using the horizontal scale. Note that the main window (top trace) is at 10uS/division (you can read that near the bottom of the screen). But the zoomed in part is 500nS/division (right under the enlarged pulse).

When you have seen enough, just click the horizontal scale knob again and you are back to “undelayed trigger” or whatever you want to call it. This can be really handy when you are navigating a long buffer. The top view shows you where points of interest in the buffer are, but the bottom view shows you the detail you want.

What would all of this been worth in 1976? My Tek retailed for about US$2500 in its day. Amazing.

Rigol Scope – Alternate Triggering

Another Rigol triggering mode is the so called “Alternate” Triggering. This reminds me of the old analog scopes with two channels, but better. In those days the time swept by and something was going to get drawn. You had your choice of “alternate” or “chop” mode. In alternate mode, each trigger caused one of your channels to draw. The next trigger would draw the second channel. That made the traces nice and solid but you weren’t really looking at the same time on each trace. If the signals repeated together at the trigger point, it didn’t matter much. But if the signals were not exactly coordinated it could drive you crazy. Chop mode didn’t look as good, but you saw both signals at the same time because the scope would draw a little bit of channel 1 and then a little bit of channel 2 and then back up to 1 and so on.

Well with a digital scope there’s no need for chop mode at all. You just acquire both channels and display both on the screen which, after all, is really a random access device. So what’s alternate mode? Well suppose you are looking at two signals that don’t really have anything to do with one another. What you really want is two scopes, right? One to trigger on one signal and another to trigger on the other. You might not even want the same time scale for each channel. That’s what alternate triggering does. It splits the screen in half and each half is like an independent scope.

For example, see the picture at the head of this article. The top signal is another JavaScript creation. This one is a good candidate for pulse width triggering. Here’s the code:

while (1)
Just a long pulse and a short pulse over and over again. That's the top signal and a perfect candidate for pulse triggering.
The bottom half of the screen is just the scope's 1kHz calibration signal. No worries using edge trigger there. If you trigger on either signal alone, the other one will go crazy. Notice each half is even using its own time base (200uS/div up top and 1mS/div at the bottom).  But with alternate triggering its like getting two one channel scopes out of your dual channel scope. Of course, you lose some functions (notably delayed trace, a topic I'll cover some other time). But you gain the ability to see two unrelated signals at the same time. 


Rigol DS1000E Pulse Triggering


The Rigol DS1102E/DS1052E has several interesting features and I thought I’d try to do a few blog posts highlighting the ones I found most interesting. This time, I’m going to show you “pulse triggering”.

If you are used to an analog scope, triggering is pretty simple. The idea is that when the scope sees the voltage go above (or below if you select negative slope) some trigger level voltage, the scope starts its sweep. Once it starts, its going to go to the end. With a digital scope like the Rigol, the instrument buffers traces all the time and when the trigger event occurs, it marks some point in the buffer and then fills in the rest of the buffer. So nominally that trigger point is the center. You can look backwards at what happened before the trigger and forward to what happened after the trigger.

With a digital instrument you can more fun kinds of triggers. So here’s an example of where “normal” triggering isn’t really adequate. Pulse width modulation (PWM) varies a pulse train to have a particular duty cycle. For example, a 50% PWM signal might be “on” for 10uS and “off” for 10uS. This can be used to control a motor’s speed or a lamp’s brightness efficiently, among other things.

The board is an economical way to convert a serial port (or a USB port with a serial adapter)) into an analog and digital I/O port. There’s 8 digital I/O, 5 analog inputs, a counter, and — what I’m interested in right now — a hardware PWM output. You can actually output “bursts” of PWM on any of the digital ports, but the hardware output just keeps making a PWM signal until you reprogram it or tell it to stop.


The 9.47uS isn’t critical. It just needs to be bigger than the small pulses and smaller than the wide pulses. Then push the down arrow and select Single for the sweep type. This will cause the scope to get one trigger, record the data, and stop.

If the Run/Stop button is red then the scope has already triggered (not likely in this case). It should be green, so if it is red, push it so that it is green. Now you can run the JavaScript program (assuming your CLASSPATH is set right,

java GP3Script pwmtest.js

will do it.

You can see the result at the start of this post. The Run/Stop button turns red and you should see something like the picture. Notice that the trigger point is marked with the T flag. It occurs AFTER it sees a pulse greater than 9.47uS. You can see that the pulse before that was in fact very narrow (the 10% pulse; about 4uS wide). So we did actually capture the exact moment that the board switched from 10% to 75%. Of course there is plenty of data to the left and the right of the trigger if you want to see more of either width pulse.

Don’t forget when using pulse triggering you still need to set the trigger level or the results can be unstable. You want the level high enough up the pulse to keep noise near ground level from triggering it, it seems.

You can select lots of options on the pulse trigger, including when a pulse is greater than a certain width, less than a certain width or equal to a certain width. You can also pick positive or negative pulses. This is a great way to let the scope watch your data instead of having to collect a lot of samples and then try to find the interesting part.

Random Electronic Projects

A few pictures I ran across of some old projects.

I really like the Radio Shack boards that are laid out like a solderless breadboard. This is a “game show” style controller produced for a client with a Basic Stamp. The only downside to these boards is that they are one sided and the copper will very easily delaminate if you get it too hot.

Another client project, this one is an H-bridge for motor control, driven by a Basic Stamp and .

A board to control HVAC equipment.

This StarFire board (bare and assembled) was a PIC processor used to gather, store, and transmit model rocketry telemetry. I volunteer with a group that lets high school kids learn about engineering by building . The PIC is riding in a socket that allows an in circuit emulator to attach. Note the two attached to produce RS232 ports. One was socketed, so the board could hook to a PC during development, but a TTL-level GPS in flight, if I recall.

Learn Electronics the MIT Way

Want to take an electronics course at MIT? Don’t pack up, mortgage the house, and move to Massachusetts! Just download the MIT course on basic electronics. This is part of their Open Courseware initiative I’ve written about before. Of course there’s no instructor support and no credit, but it sounds like a good class if you want to know more about electronics. From the site:

Subject 6.071 Introduction to Electronics provides undergraduate students with both a basic and practical understanding of electricity and electronics. The emphasis is on applications rather than theory. Consequently there is a strong hands-on component to the subject to enable students to gain practical experience. Topics covered in the subject include:

* DC and AC circuits

* Diodes, transistors, operational amplifier
* Analog and digital electronics

* Detectors and transducers

* Electronic control
* Signal processing and noise

The focus of the subject is understanding the critical issues involved in assembling and using an array of electronic equipment to carry out various missions. Thus, there is more emphasis on the application as opposed to design.

Let me know how you like it!