Wow! It has been a while. I finally decided to write another one of these. I promised a long time ago to write about timers. Well, almost 4 months later, here we go!

Timers are extremely useful peripherals often built into microcontrollers. Are you going to be doing anything that involves timing or delays in your microcontroller program? Are you going to:

  • Increment a variable every second?
  • Measure the length of time a button is pressed down?
  • Wait for 20 milliseconds?
  • Blink a light every half second?

If you are doing any of the above, or anything even remotely related, you are probably going to be using a timer. A lot of desktop frameworks have a similar kind of setup — Qt, for example, has the QTimer class which allows you to schedule something to happen in the future. .NET has a Timer class that does the same thing. And as you can guess, Mac OS X’s Foundation framework has the NSTimer class. These tend to use lower-level operating system routines, which in turn use hardware timers, and they will run a handler inside your event loop when they fire. You don’t have to know how to use the hardware timers though–the operating system handles it for you. Well, in a microcontroller, you will directly use a timer peripheral to do similar tasks.

Timers can generally be put into several different modes. Some microcontrollers have more complex and powerful timers than others. I’m only going to focus on basic timer concepts here. The first thing you need to know is that timers are usually memory-mapped peripherals built into the microcontroller. They have various configuration registers you can access. The most important register is the counter register. As you can guess, it counts. It holds the timer’s current value, and while the timer is running, it is constantly being incremented or decremented, based on what direction the timer counts. Some timers count up, some timers count down. Some even allow you to set which direction it counts. It doesn’t really matter what direction a timer counts, because you can do all the same things with it either way.

Anyway, so I said this counter register counts up or down, depending on the timer. Let’s pretend that it counts up, for the sake of explaining how this timer works. So the counter starts at zero, and then after a certain amount of time, it will be incremented to 1, and then 2, and so on. How often is it incremented? This is the key to how timers work! Generally the timer runs at a fraction of the system clock rate. So if your microcontroller is running at 100 MHz, the timer might run at 25 MHz. In many microcontrollers, this is configurable. You might be able to set the timer to also run at 100 MHz, or 50 MHz, or 12.5 MHz. Let’s assume that our microcontroller is running at 100 MHz and its timer runs at 25 MHz. This means that in one second, it will be incremented 25 million times. That’s a lot! Alternatively, we could say the counter will be incremented every 1/25,000,000 seconds, or every 40 nanoseconds.

My example here was a little crazy. It’s very doubtful that you need resolution that high. Generally timers, particularly fast ones such as the 25 MHz one we are using here as an example, also have a divider. The divider does exactly what it sounds like — it divides. It does it like this — it has a divider counter register which counts up every time the timer would count. After the divider counter gets high enough, the main timer counter register is finally incremented and the divider counter register is reset to zero. What this does in effect is makes the timer count slower. In this case, let’s say our divider is 25. This means that every 25 ticks of the 25 MHz timer clock, our final counter register is incremented, effectively making it into a 1 MHz clock instead of a 25 MHz clock. It’s just a nice way to slow down the counting. The value the divider will count up to is a value configurable in a register.

So let’s say we’ve configured the timer as follows: the CPU is at 100 MHz, the timer is at 25 MHz, and the timer’s divider is set to 25. Thus, the timer’s counter register is incremented at a rate of 1 MHz, or 1 million times per second. I like making my timers count at nice, even intervals like this because it makes it easier to do the math in your head to figure out how many counts it will take for a certain amount of time to pass. You can do it however you’d like, though!

The only other thing I really need to cover before we jump into the basics is: how to tell the timer to start counting. Timers generally have a configuration register of some kind, and one of the bits in it tells the timer to start counting. For this timer peripheral, let’s say if bit 0 of the timer config register is a 1, it is counting, and if it’s a zero, it’s not counting.

If the timer is configured this way, you now can do some very basic timing. Let’s say all your program does is turn on an LED for a second, then turn it off for a second, and repeat the process. So for our example, we have an LED connected to PORT A, pin 0. Here’s some sample code (keep in mind that TIMER_CONFIG, TIMER_DIVISOR, TIMER_DIVISOR_COUNTER, and TIMER_COUNTER are the registers for the timer):

// Set port A, pin 0 as an output.
DDRA |= 0x01;
// Turn it off.
PORTA &= ~0x01;

// Make sure the timer is turned off
TIMER_CONFIG &= ~0x01;

// Configure the timer to have a divisor of 25, and reset all the counters.
TIMER_DIVISOR = 25;
TIMER_DIVISOR_COUNTER = 0;
TIMER_COUNTER = 0;

// Start the timer (bit 0 of the timer flag register turns it on, in our example)
TIMER_CONFIG |= 0x01;

// Initialize this variable -- it will contain the time we last did something.
uint32_t lastTimeValue = TIMER_COUNTER;

// Do this forever...
while (1)
{
    // Look at the counter's value now.
    uint32_t nowTimeValue = TIMER_COUNTER;

    // Has it been 1 million ticks since the last time we toggled the LED?
    // (1 million ticks = 1 second)
    if ((nowTimeValue - lastTimeValue) >= 1000000)
    {
        // Toggle pin 0 of port A (^ is the XOR operator,
        // think about how it works!)
        PORTA ^= 0x01;

        // Update our "last time" variable to contain this time.
        lastTimeValue = nowTimeValue;
    }
}

Okay, did you follow along? This program will do nothing except toggle that LED on and off. It will toggle it every second. A couple of notes: the data type uint32_t is brought in by including the header file stdint.h. It’s just a portable way of specifying that it’s a 32-bit unsigned value. I could have used unsigned long instead, but I like using uint8_t, uint16_t and uint32_t (and their signed equivalents — int8_t, int16_t, and int32_t) because they make it obvious how big each variable is.

Also, the XOR operator (^) will toggle bits. Remember that PORTA ^= 0x01 is equivalent to: PORTA = PORTA ^ 0x01. This will turn bit 0 on if it’s off, and off if it’s on.

So this works and is fine and dandy, but it takes up the entire main loop of the program! Well, you can put other things to do in the main loop, but if you do it that way, you may not toggle the LED after exactly 1 second, especially depending on what other CPU-intensive things you’re doing in the main loop. This may not matter for something as simple as a blinking light, but for other tasks it could be very important. If you need more precise timing, you need to set the timer to use interrupts instead.

Most timers support a mode where it’s constantly checking the counter to see if it matches another value you specify, and once the counter matches it, it interrupts. This would be the mechanism you would use to do a precise timing. In this case, you have another register called the match value register. You would set your match value register to the value you want the counter to match — 1000000 in this case. What happens after this may depend on the timer. Some timers may have an option to automatically reset the counter back down to zero (or another specified value) after it reaches the match value. In other timers, you might have to adjust the match value instead. I’ll cover both methods so you see what I mean. Assume that the timers and GPIO have been configured as I had them before.

Program 1 (assuming the timer automatically resets the counter back to zero whenever a match occurs):

int main(void)
{
    // All the previous configuration stuff goes here,
    // setting up the GPIO and timer (but don't start the timer yet...)

    // Set the timer match value to 1000000, so it interrupts every 1 second.
    TIMER_MATCH = 1000000;

    // Start the timer
    TIMER_CONFIG |= 0x01;

    // Now our main loop literally does nothing!
    while (1)
    {
    }
}

// This is where the interrupt will jump to -- may need to specify
// to your compiler that it is an interrupt handler.

void TIMER_INT_HANDLER(void)
{
   PORTA ^= 0x01;
}

I may have to explain TIMER_INT_HANDLER to you. This is heavily microcontroller-dependent, but basically you need a way of specifying to the microcontroller what to do when an interrupt occurs. You do this by creating an interrupt handler, and then the address of it gets put into a table of addresses to jump to when a specific type of interrupt occurs (called a vector table). For now, just pretend that TIMER_INT_HANDLER has been properly set up as an interrupt handler for the timer peripheral. I’ll cover that later.

This is a lot simpler! You can put all kinds of other stuff in the main loop, and that interrupt will occur at almost precisely every second. It may vary just a little based on if you have disabled interrupts anywhere in your main loop for interrupt safety (as I mentioned in my last post on interrupts).

Now, here’s another code sample for if your microcontroller does not automatically reset your timer’s counter back to zero after a match occurs:

Program 2 (assuming the timer does *not* reset the counter back to zero when a match occurs):

int main(void)
{
    // All the previous configuration stuff goes here,
    // setting up the GPIO and timer (but don't start the timer yet...)

    // Set the timer match value to 1000000, so it interrupts every 1 second.
    TIMER_MATCH = 1000000;

    // Start the timer
    TIMER_CONFIG |= 0x01;

    // Now our main loop literally does nothing!
    while (1)
    {
    }
}

// This is where the interrupt will jump to -- may need to specify
// to your compiler that it is an interrupt handler.

void TIMER_INT_HANDLER(void)
{
    TIMER_MATCH += 1000000;
    PORTA ^= 0x01;
}

The difference is in TIMER_INT_HANDLER. I added 1,000,000 to the match value, so now it will match again 1,000,000 ticks (1 second) after the last match occurred. In this case, the counter register continues counting past 1,000,000, so by moving the match value up another 1,000,000, it will catch the counter when it gets to 2,000,000. Get it? It’s nothing really difficult, but the first option I showed earlier is easier if your timer peripheral automatically resets the counter back down to zero after a match. So if you have to do it this way, this is how you do it–otherwise, I’d recommend the first approach. You may be asking me: in this method, why didn’t you just set TIMER_COUNTER to zero instead of add 1,000,000 to TIMER_MATCH? Wouldn’t that have the same effect? You may think that it would, but it actually does not. Here’s why:

Between when the timer signals that a match occurred and we actually get to execute the interrupt handler, some time passes by. If the timer itself resets the counter back to zero, this is no problem, because it can reset the counter instantly as soon as the match happens. But if we try to do it ourselves manually, we will only reset it back to zero after so much time has already passed. In other words, the counter might actually be up to 1,000,002 or so before we tell it to go back to zero. In effect, this causes us to toggle the LED every 1 second PLUS however long on average it takes to get to that first instruction that resets the counter. By adding 1,000,000 to the TIMER_MATCH register instead, it guarantees that the next match will occur exactly 1 second after the last match occurred. This may not matter for something as simple as toggling an LED, but if you add up that extra delay over time in a very time-sensitive algorithm, it would cause inaccuracy.

Note that at one point we will overflow the 32-bit TIMER_MATCH register. When the match register gets up to 4294000000, the next time we add 1000000 to it, we will get 4295000000, which is larger than the maximum 32-bit integer (4294967295). That’s okay — it will wrap around and work correctly. The C standard guarantees that unsigned integers will wrap around correctly — e.g. if you add 1 to 0xFFFFFFFF, you will get 0. So in this case, when we add 1000000 to 4294000000, we will end up with a match value of 32704 (4295000000 % 4294967296), and all will be well with the world (the timer counter itself will also overflow correctly back up to 0, and match when it reaches 32704, exactly 1000000 higher than 4294000000 after wrapping).

These are the two simplest ways to use timers. Timers also have all kinds of other crazy features; I described the most common way they are used. I hope I didn’t make that too confusing. It was a lot to digest, but basically, here’s a summary:

  1. Timers are memory-mapped peripherals, and you know what their clock rate is based on what you read in the microcontroller’s data sheet and how you configure it.
  2. Timers have divisors, so you know exactly how long it takes between increments (or decrements) of the timer’s counter.
  3. You can use that information alone to do time-based stuff, but if you want maximum accuracy you should use an interrupt.
  4. To use an interrupt, you set a match value and the timer will interrupt whenever it reaches the match value.
  5. Some microcontrollers will allow you to automatically reset the counter whenever the match value is reached, which is handy for periodic tasks.
  6. If your microcontroller doesn’t automatically reset the counter after a match, you should update the match value instead of resetting the counter value on your own, or your interval between interrupts will be slightly longer than it should be.

Ok, that’s enough for today. I’ll talk more about interrupts and interrupt handlers next time. Have fun!

In my last post, I made the decision that the next post would be about interrupts. Well, here goes nothing…

Interrupts allow a program to be temporarily stopped while another section of code (an interrupt handler) is executed instead. When the interrupt handler finishes up, the program continues where it left off. You can turn interrupts on and off, usually (always?) with a single assembly instruction.

So I’ve described what an interrupt is, but what’s the point? Where are they used? Peripherals built into the microcontroller use interrupts to tell the program that something happened. Examples: there might be an interrupt to tell the program that the serial port just successfully finished sending out a character. Or there might be a timer set up to cause an interrupt to occur every millisecond (which you could use to cause something to occur after a specified number of milliseconds). As you could imagine, this can be extremely useful. Often, you hear about polling I/O versus interrupt-driven I/O. With polling, your program sits in a loop waiting for something to occur, wasting lots of cycles that could be used elsewhere. With an interrupt-driven architecture, your program can be doing other things, and when it’s ready it will receive an interrupt.

Interrupts are a tricky concept because you have to be extremely careful when you’re coding a program that might be interrupted. Let’s take, for example, the following C statement:

blah = blah + 5;

Assume that blah is a variable somewhere. Obviously, that line of code will take whatever is stored in blah, add 5 to it, and store the new value into blah. That one statement does not directly translate into a single assembly language statement — at least in common microcontroller architectures. In general it will translate into three instructions:

1) Load whatever is stored at the memory address of blah into a register
2) Add 5 to the register’s value
3) Store the contents of the register to the memory address of blah

OK–so what’s the big deal? The deal is that since the single line of C translates into 3 assembly instructions, it’s not an atomic operation. An interrupt could occur in between the first and second instruction, or between the second and third instruction. You’re not guaranteed that nothing else will occur while that line of code is executing. If you’re expecting an interrupt to come in and modify the value stored in blah, you may end up with unexpected results. Let’s say that your interrupt routine consists of one line of code:

blah = 0;

If the interrupt fires in between two of the instructions belonging to the line that adds 5 to blah, something weird might happen. Example:

1) Load whatever is stored at the memory address of blah into a register.
2) INTERRUPT! blah = 0 now.
3) Add 5 to the register’s value
4) Store the contents of the register to the memory address of blah

Do you see what happened? The interrupt was supposed to clear blah, but it didn’t actually end up getting cleared. The first instruction read the value of blah into a register, and then the interrupt cleared blah. But that didn’t change the register’s contents, so 5 was added to blah‘s old contents still residing in the register and then the register was re-stored into blah. It’s as if the interrupt never occurred. Ideally, after this code runs, blah should contain 0 (or maybe 5, if the 0 immediately has 5 added to it). Instead, in this particular case, it contains the old value of blah + 5.

This example scenario above is very similar to a real-world bug that I have personally seen in an actual product. The end result was that it caused a speedometer to occasionally show a speed twice as large (and extremely rarely, 3 times as large) as the actual speed.

This kind of subtle behavior is what makes programming with interrupts difficult to grasp when you’re just getting started. It can cause all kinds of crazy stuff to happen that is very difficult to debug.

So how would you solve this problem in a real program? Let’s say you really did want to make sure that blah was cleared by the interrupt. One way to do this is to temporarily disable the interrupt from occurring while you’re modifying blah. Usually the easiest way to do this is to disable all interrupts, do the operation, and then enable all interrupts again:

__disable_irq();
blah = blah + 5;
__enable_irq();

Pretend that __disable_irq() and __enable_irq() are macros that end up resolving to assembly statements for enabling or disabling interrupts. This will guarantee that when blah is cleared, it will not happen in the middle of adding 5 to it. If the interrupt is supposed to happen while interrupts are disabled, it will occur as soon as interrupts are enabled again.

Think about what I said there — the interrupt may not occur exactly when it’s supposed to. If this is a time-sensitive interrupt, it could be bad to delay it from happening. So if you do this, you should minimize the amount of code you have wrapped in a disable/enable interrupts combination, so if an interrupt does get held off, it doesn’t get held off very long.

I think that’s enough about interrupts for today. This should be a decent introduction to interrupts and why they have the potential to cause all kinds of problems. But they are really useful, and it’s vital to understand them if you’re going to be writing software for a microcontroller. Remember how I talked about an interrupt that could occur every millisecond? I’m going to go into how to do that kind of thing in my next post. We’ll be moving back into peripherals built into microcontrollers: in this case, timers.

In my last post in the series about microcontroller programming for normal programmers, I talked a little bit about general purpose I/O. I’d like to expand on this topic today by talking about inputs, outputs, pull-ups, and pull-downs. As a summary, a GPIO pin on a microcontroller can be set up to be an input or an output, and if it is set as an input, there are various options you can set for how the input works. This is the first step toward getting the microcontroller to actually do something. I’ll go into more detail now.

When I was talking about a hypothetical “light-emitting diode” peripheral last time, I was basically describing the output functionality of a GPIO port. If you set a GPIO pin as an output, you can control whether its output is a 1 or 0. What does this 1 or 0 mean? Well, a microcontroller generally operates at a voltage, such as 5 volts or 3.3 volts. I’ve been playing with various incarnations of the ARM Cortex-M3, and they have all been 3.3V, while older microcontrollers like the Freescale 68HC11 run at 5V. I’ve also seen some new Cortex-M3s that operate at 5V, but let’s just assume for today that we’re working at 3.3V. Generally, this means your GPIO pins also operate at that same voltage. Basically, a 1 is represented by 3.3V (VCC), and a 0 is represented by 0V, or ground (GND). Since the LED was connected to one of the microcontroller’s pins, we could turn it on or off by setting the GPIO pin’s output value to 0 or 1.

If you understand everything I just wrote, congratulations. You understand outputs.

Inputs are different. You have something else hooked up to your GPIO pin, but you’re not controlling it. Instead, you’re determining whether it’s currently “showing” a 1 or 0 value to you. What kind of use would this have? Well, the easiest example is probably a push button. If you want to determine whether a push button is “pushed” or “released”, you could hook it up to a GPIO pin so that you can read whether you’re seeing a 1 or 0. However, because of how electricity works, it’s going to get slightly complicated, so bear with me.

If you’re not familiar with how buttons work, here’s a quick explanation. Buttons have two terminals on them. When the button is pushed, the terminals are connected together internally, creating a “closed circuit”, allowing electricity to flow through them. If the button is not being pushed, the terminals are not connected together, so electricity is not allowed to flow between them. Got it? Good!

When you wire a button to a microcontroller’s GPIO pin, you hook one of the button’s terminals to the pin, and you hook the other terminal to either ground or VCC (3.3V in our case). But you’re not done yet! Let’s assume we wired the button to GND (0V). See the picture above. So when the button is pushed, the circuit will close, and thus, it will be as if the microcontroller pin was connected directly to ground. If you read the port pin at this time, you will get a 0. However, if the button is not pressed, the circuit does not close. In that case, as far as the microcontroller pin is concerned, it’s not connected to anything else in the circuit. It’s floating. This means the value you read from the pin will be unpredictable.

So…we need a way to make it so the pin thinks it has 3.3V connected when the button is not pressed. That way, it would read a 1 if the button is released, and a 0 if it’s pressed. How can we do that? Well, we need to hook it to VCC as well. So we leave the existing connection to the button in place, but also add another connection so the port pin is always connected to VCC. See the picture below.

Let’s think about what this will do. When the button is released, the port pin is connected directly to VCC, reading a 1. But if it’s set up this way and you press the button, the port pin will still be directly connected to VCC, but closing the button’s circuit will also directly connect it to GND at the same time. In other words, you will have VCC and GND directly connected together with no resistance in between (the button itself doesn’t count as resistance — it’s just like a wire). This is commonly referred to as a short circuit, and it will cause things to get hot very quickly. You will probably burn up the circuit board and the microcontroller, creating some magic smoke in the process.

Now what? How can we safely stay hooked to both VCC and GND simultaneously? We need a resistor. Instead of connecting the GPIO pin directly to VCC, put a resistor between the pin and VCC. See below.

When the button is released, the pin will no longer be directly connected to VCC, but it will be connected to VCC through a resistor, which is perfectly OK, and will still cause the voltage on the pin to be 3.3V, or 1. When the button is pressed, the pin will be connected to VCC through the resistor, and also directly to GND through the button. If you think about it, this also means VCC will be connected to GND through a resistor. Since there’s a resistor in between, you won’t get any smoke. It’s no longer a short circuit. Now let’s look at it from the point of view of the port pin–it’s still simultaneously connected to GND and VCC. Since it’s connected to VCC through a resistor, and directly to GND, GND will “win”. VCC is trying to pull the port pin’s value up to a 1, but with the resistor in between, it’s a very weak connection compared to the pin’s connection to GND, so GND keeps the port pin pulled down to 0.

I know this may be kind of confusing, especially if you have no experience with electricity. I hope the pictures make sense. I didn’t understand this concept at first, but it’s pretty important. You need to understand it so that you can understand pull-up and pull-down resistors.

Basically, here’s the purpose of pull-up and pull-down resistors. When nothing is hooked up to a pin, a pull-up or pull-down resistor will give that pin a default value. If you have a pull-up resistor enabled, the default value will be a 1. If you have a pull-down resistor enabled, the default value will be a 0. In our example, we started out with the microcontroller only hooked to the button, which gave the input a value of 0 when the button was pressed. We then added a connection to VCC through a resistor to give the input pin a value of 1 when the button was not pressed. It turns out that what we added is called a pull-up resistor, and most microcontrollers nowadays have them built in. You just have to enable them.

So instead of having to add a resistor outside of the chip, we actually can get away with hooking the button directly to the pin as we did in the first picture, which I am showing again below.

Until we enable the internal pull-up resistor on that pin, we’ll run into the same problem I mentioned at first–when the button is not pressed, the value we read will be unpredictable, because the pin is not hooked to anything in the circuit. So if we enable the pull-up resistor, the full circuit will look just like the third picture above where we added the resistor. It’s just that the resistor connected to VCC is inside the chip, so we don’t have to bother adding it to our circuit board–we just have to tell the microcontroller to turn it on. Nice, huh?

Pull-down resistors work the same way, but they connect the pin through a resistor to ground, rather than VCC. Many microcontrollers also have pull-down resistors built in.

I’ve talked enough about the hardware side for one day, so now let’s get to the part we programmers enjoy–the software. Usually, you have a memory-mapped GPIO peripheral. Let’s assume we have a hypothetical PORTA peripheral mapped in memory to address 0x100.

PORTA is made up of four 8-bit registers:

DATAA
DDRA
PULLUPA
PULLDNA

DATAA is at 0x100, DDRA is at 0x101, PULLUPA is at 0x102, and PULLDNA is at 0x103.

I’m actually going to explain the DDR register first. DDRA stands for data direction register A. It describes whether each pin on PORTA is an output or an input pin. An input is represented by a bit being zero, and an output is represented by a bit being 1. So if DDRA was set to 0x03, then port A pins 0 and 1 are outputs, and the rest of its pins are inputs. It’s as simple as that.

If you set a pin as an output, you can change its output value by changing the appropriate bit in the DATAA register. For instance:

DATAA |= 0x01;

will set port A, pin 0 to the value “1” or “high” or “3.3V” or however you’d like to think of it.

DATAA &= ~0x02;

will set port A, pin 1 to the value “0” or “low” or “ground”.

If you read my last post about memory-mapped peripherals, this should all make sense.

On the other hand, if you set a pin as an input, you have a few more options. You can turn on the pin’s pull-up or pull-down resistor (but certainly not both at the same time–that would make no sense). You don’t have to turn on either resistor if you don’t want to. It only makes sense to enable pull-ups or pull-downs on pins set to input–the value will be ignored for outputs.

PULLUPA |= 0x04;

will turn on the pull-up resistor on port A, pin 2.

PULLDNA |= 0x08;

will turn on the pull-down resistor on port A, pin 3.

Finally, to read the input value on an input pin, you read the DATAA register. If you only care about a specific pin, you can ignore the rest of the bits using bitwise operations in C. For instance:

if (DATAA & 0x04)

The above line will be true if port A, pin 2 has an input value of 1 (in our example, that would mean the button connected to it is not being pressed)

if ((DATAA & 0x04) == 0)

The above line will be true if port A, pin 2 has an input value of 0, meaning the button is pressed.

If you try to read the input value of an output pin, it will just tell you the last value you set it to output.

Whew! You made it! That’s really all you need to know about GPIO for now. The way I described the software interface to these GPIO pins is generally exactly how it works in a real microcontroller. The registers might have slightly different names, and their organization in the memory map may be different, but that’s essentially how it goes. I did skip some more advanced stuff, but for now the other stuff is not important.

Congratulations–you’ve made your way through understanding the first built-in peripheral in a microcontroller. My next article will be an introduction to interrupts–a very important concept in microcontroller programming. The reason they are important is that they tell you that an operation has completed, or something is ready. Interrupts also took me quite a while to fully understand, but they are another important concept. If you’ve ever used signal handlers in your regular desktop programs, it’s the same kind of concept. Your program stops and another portion of code executes instead, and then your program picks up where it left off as soon as the other portion of code is done. Anyway, I won’t go into any more detail about them until my next article. See you then!

Note: I have written a post containing updated compatibility information you may want to read here. The remainder of this post below is still very important, but I’d like to make sure everyone has the most up-to-date information about compatibility between the different DLLs and parallel port cards out there. If you’re looking for my patched io.dll for Willem programmer compatibility, see below.

Last year I bought a Willem EPROM programmer board from Sivava. It’s basically a cool little board with various sockets for plugging in EPROM/EEPROM/Flash/etc chips for reading/erasing/writing. Apparently it can even program some AVR microcontrollers. I have the PCB50 version of the board.

Here’s the deal. It has a USB port, but it’s only for supplying power. All communication goes through the parallel port. As everybody should know at this point, the parallel port is on the way out. No, scratch that. The parallel port is long gone. I had to use a really old HP Pavilion with a Celeron running Windows 98 to do anything with it. The programmer worked great, and I was able to fix a computer’s BIOS chip that I had messed up while trying to hack its BIOS.

Let’s fast forward to over a year later (a.k.a. now). I have a homebuilt PC with an Intel DX58SO motherboard and a Core i7 CPU, running Windows 7 Ultimate edition, 64-bit. The DX58SO literally has no legacy peripherals, other than a single PCI slot. It has no PS/2 ports, no parallel port, no serial ports, and no standard IDE ports. It does have a variety of types of PCI Express slots, though.

I recently bought a sweet PCI Express 1x card with four serial ports and a parallel port from Newegg. (Note: Newegg’s product specs lie about this card — the parallel port does not support EPP or ECP mode, according to a sticker on the box, even though Newegg says it does). I remembered that I had my programmer and decided I totally needed to get it working in Windows 7.

Easier said than done.

It’s difficult enough to get low-level legacy stuff working in Windows 7, but when you’re using the 64-bit edition, a lot of older stuff breaks even more. Also let’s remember that add-on parallel ports do not get mapped to the standard I/O addresses for parallel ports (0x378 and 0x278), but instead some other random address (mine is at 0x3000). I tried running the software that came with the board, but it just gives me errors and actually won’t let me exit without forcing it to quit from the task manager.

Let’s go on a Google adventure. Google lesson #1: sometimes when you’re looking for info about Windows 7 64-bit, you can find very useful stuff when you search for Vista 64-bit (or XP 64-bit) instead. My first search was willem vista 64-bit.

The second result was a digg posting titled Willem Eprom for Vista and 64bit XP (digg post is no longer available; link removed). The linked page is a forum posting at a forum called onecamonly.com. The post is by the admin of the site, and he mentions to install software called TVicPort and then a modified io.dll file. The first comment on the digg posting was by a user named rabitguy, who said he had a Willem board working on Windows 7 64-bit with tvicport and iodllwrapper.

So I kept seeing this io.dll and iodllwrapper stuff. What exactly is it? Let’s Google for “io.dll”.

The first result is to a homepage for io.dll. Basically, it explains that it’s a library allowing direct port access from several different Windows versions. Awesome! Except it doesn’t mention Windows Vista or Windows 7, or anything 64-bit at all. Crap. Well, I looked in the installation directory for the Willem software that came with my Sivava programmer board, and sure enough, in C:\Program Files (x86)\EPROM50, there’s an evil file named io.dll. So that’s why it doesn’t work.

So anyway, I searched for iodllwrapper, deciding to follow the advice of rabitguy. The first result is to a forum posting on an Amiga message board. I did a search on that page for “Willem” and found a posting by Toni Wilen who wrote a 64-bit-compatible io.dll wrapper which depends on TVicPort and uploaded it as an attachment to the forum, called iodllwrapper.zip. He even included the source code. Aha! So I think I get it. He wrote a DLL that provides all the functions that io.dll would provide, except rather than implementing the raw functionality himself, he forwards the relevant function calls to TVicPort, which handles all the low level stuff (in a manner that works on 64-bit operating systems!). Actually it’s a pretty genius idea. So I downloaded his DLL and tried it out, replacing the stock io.dll file that came with the Willem software with his new wrapper.

I crossed my fingers and opened the programmer software. Awesome! I no longer got a bunch of weird errors when the program opened! I’m pretty sure Toni’s DLL would have worked great, but there’s a problem in my case. I don’t have a built-in parallel port, so my parallel port is at a non-standard I/O address (0x3000). The Willem software only lets you choose from a list of three standard I/O addresses where built-in parallel ports would appear.

Ugh! So I was stuck again. At this point I was about to throw in the towel. But first, I thought about it and came to the conclusion that I can’t be the only one with this problem. So I searched for io.dll willem address.

The first result this time was Ben Ryves’ Remapped IO.DLL. So someone else had the exact same problem! Ben also wrote an IO.DLL wrapper (and he included his source code, too!). His solution is to add an additional file called io.ini into the same directory as io.dll. You put the I/O address of your parallel port into that file (so my io.ini file would contain one line — 0x3000), and set the Willem software to use LPT1. The wrapper DLL looks for any I/O reads/writes in the LPT1 range and remaps them to actually occur at the address specified in the io.ini file. This is exactly what I needed!

It uses another DLL called inpout32.dll to do the dirty work. Actually, Ben’s site very nicely describes everything his DLL does, so I won’t go into any more detail about it.

Well, it turns out that his DLL didn’t work for me, either. It seems that it’s just not compatible with 64-bit Windows 7, at least in my experience. I just could not get it to work. The Willem software would not detect the connected board. I looked at the homepage for inpout32, and apparently there is a 64-bit version, so maybe if I had fiddled long enough I could have gotten inpoutx64 to work, but at this point I actually had an idea of my own, after looking at the source code that Ben included for his DLL.

I knew from everything I had read that Toni’s 64-bit-compatible io.dll wrapper using TVicPort did work. All it was missing was the remapping. So I took Ben’s code and modified it to use TVicPort rather than inpout32.dll. (Alternatively I could have added the remapping to Toni’s code.) I only changed a few lines. I just changed the calls to inpout32.dll for reading/writing to use the corresponding TVicPort functions instead, and also added initialization and deinitialization code for TVicPort.

So I compiled it with Visual C++ Express Edition 2008…ran the “Test Hardware” function on the Willem software…and success! It found the hardware! I was stoked, so I grabbed a BIOS chip from an old motherboard I’m not using anymore (Asus A7V133). It’s a SyncMOS F29C51002T. I chose that model in the software, set up the DIP switches correctly, and stuck the chip in the cool ZIF socket on the programmer board. I then read the BIOS from the chip. I looked at the read buffer and it looked good! I saw stuff about an Award BIOS, so it sure looked like it was working. I happened to have a good copy of the same BIOS file from when I had messed with that same chip on the older computer, so naturally I did a diff against them to make sure that the file was read correctly.

It didn’t read correctly. It differed by just a few bytes. It was mostly OK, but mostly is not good enough when you’re reading to/writing from chips that contain computer code and/or data. At this point I decided to sleep on it and think about it the next day. That approach really works well in all aspects of life in my experience. When I had trouble learning to play a piano piece I would sleep on it and the next day it was like my brain had somehow prepared itself ahead of time, and I would play the part I had been struggling with perfectly.

The next day I noticed that the TVicPort driver actually has an option for two I/O port access “modes.” The default mode is hard mode, which is slower, but provides more reliable access to an I/O port if it’s already been opened by a different driver. Soft mode is faster, but has trouble if a port is already open by another driver. On a whim I decided to try out soft mode. I read the chip again, and this time it worked perfectly. I then erased it, wrote the file back, and compared it. Perfect. I did this several times just to make sure I wasn’t getting lucky, and it worked every time.

So either I got really unlucky on my first try with hard mode, or using soft mode fixed it. I don’t know which one is the case, but regardless, I now have my programmer working in Windows 7 64-bit. And this is the end of our Google adventure.

Google can do a lot of great things if you’re willing to sit down and search. And search. And search. I didn’t actually find all this stuff that easily. I tried many different searches, wording things slightly differently. I ended up only showing you guys the search queries I tried that gave me interesting results.

So…thank you to everyone I mentioned in my post. I’ve never met you or even corresponded with you, but you all helped me get this working. Thank you rabitguy, admin at onecamonly, Toni, and Ben. With all of your info I got it working.

So naturally, here’s my io.dll wrapper, based on Ben’s wrapper, along with the source code for it.
Remember, I’m not responsible for any damage done by this software–it’s been tested lightly and seems to work for me, but your mileage may vary!
Download 64-bit remapped IO.DLL wrapper and source code (new version 1.1 which fixes a bug–thanks Paco!)
You will also need to download TVicPort from here.

Install TVicPort, then restart your computer (mine didn’t work until I restarted, and it does ask you to restart). Replace the io.dll file in the Willem software directory (C:\Program Files (x86)\EPROM50 on my computer) with this patched version. Open up the io.ini file, replace the address there with your parallel port’s I/O address (make sure you keep the “0x” before the address or it won’t work), and put it in the same directory you just copied the DLL file to. Set the Willem software to use LPT1 (0x378). If everything is working correctly, you should be able to go to the Help menu and choose Test hardware, and it will say “Hardware present” in the status bar at the bottom.

If you need to compile the modified io.dll for yourself or make modifications, grab TVicPort.h and TVicPort.lib from the TVicPort installation (C:\TVicPortPersonal\Examples\MSVC) and put them in the project directory. After doing that it should compile.

Hope this helps anyone out there, and thanks again to everyone whose information and source code helped me out!

A quick note: To find your parallel port’s I/O address, go into the Device Manager and open up your parallel port. It’s in the Resources tab:

The I/O range that is 8 bytes long (in my case, 3000-3007) is the important one. So prefix the start address with 0x (so in my case, I ended up with 0x3000) and that’s the value you should put in the io.ini file.

Version History:

  • 1.1 – Fixed a bug where I was calling functions from DllMain that I should not have been calling, causing the DLL to not work for at least one person – August 15, 2011. [Download]
  • 1.0 – Initial release – October 9, 2010. [Download]

I couldn’t resist jumping into my “microcontroller programming for high level programmers” series as soon as possible, so I’d like to go into a bit more detail about where I left off in my last post–memory-mapped peripherals.

Like I said in my last post, I missed out on memory-mapped peripherals during my CS education (which is not too surprising). My mental model for how memory addresses work was missing a chunk of knowledge. I thought that every memory address was a storage location–either RAM (readable and writable) or ROM (only readable). It turns out that memory addresses in computers can also be used for other stuff, like telling an external chip or a built-in peripheral to do something.

A memory-mapped peripheral works exactly how I just described. The peripheral reserves a portion of the address space on the computer. You write to (or read from) somewhere inside that address range, and the peripheral does something in response. Let me give you a simple example:

Let’s pretend that a microcontroller has an “LED” peripheral. By LED I mean a light-emitting diode–a little green or red or whatever other color light. Get used to the acronym “LED” because it’s very common. An example of an LED is the power light on your computer. Anyway, back to the pretend world. Imagine that the physical microcontroller chip has eight pins you can hook up to LEDs to light up, and your program can control them. The “LED” peripheral is mapped to memory location 0x1234, and it’s one byte long. Each of the eight bits in the byte controls one of the LEDs. If a bit is one, its corresponding LED will be turned on, and if the bit is zero, its corresponding LED will turn off.

In a C program, you would then turn the LEDs on and off by changing the value at address 0x1234. I’m going to assume you understand pointers. I’m creating a pointer so that I can manipulate the LED peripheral. Remember that uint8_t is usually typedef’d as unsigned char–an 8-bit integer that has no sign bit, so you can mess with all eight bits without worrying about side effects. Here’s some sample code:

#include <stdint.h>

/* Get a pointer to the LED peripheral */
/* Note that you cannot do this in Linux in a user program */
/* because each user program has its own virtual address space */
/* and other sections of memory are protected from direct access */

volatile uint8_t *LED = (volatile uint8_t *)0x1234;

/* Turn all LEDs off */
*LED = 0;

/* Wait for 1 second -- just pretend this is already implemented */
wait_milliseconds(1000);

/* Turn every other LED on -- 0x55 == 01010101 in binary */
*LED = 0x55;

wait_milliseconds(1000);

/* Turn on the LED associated with bit 7 -- 0x80 == 10000000 binary */
*LED |= 0x80;

wait_milliseconds(1000);

/* Turn off the LED associated with bit 0 -- 0x01 == 00000001 binary */
*LED &= ~0x01;

Ok–I hope that wasn’t too much to start out with, but I’ll try to explain in detail what I did.

First, I created a pointer that points to the LED peripheral’s address (0x1234). I said earlier that the peripheral is one byte long. That’s why I picked a uint8_t as the type — because a uint8_t is 8 bits, or 1 byte, in size.

You may have noticed that I defined the pointer as volatile. Why did I do that? I’ll tell you as soon as I finish explaining the rest of the code. It will be easier to describe what it does as soon as you understand exactly what the code does.

After that, I write a zero to the LED peripheral. Remember that since the variable “LED” is a pointer, I have to use the * operator to tell it to write to the address to which LED is pointing. Since every bit of a zero byte is zero, this turns off all the LEDs (if any were on already). Next, I call an imaginary function to wait for 1000 milliseconds, or in other words, one second.

Then, I write 0x55 to the LED peripheral, turning on the LEDs associated with bits 0, 2, 4, and 6. Of course, I wait a second here too.

For the last few operations, I turn on the LED associated with bit 7 (without affecting the other LEDs), wait another second, and then turn off the LED associated with bit 0 (again without affecting the other LEDs). If you haven’t seen the bitwise operations |, &, and ~ used much in C, you should definitely learn them before venturing onward. They will be used endlessly to manipulate individual bits in memory-mapped peripherals. Sometimes you want to turn on a single bit at an address while leaving all the rest of the bits unchanged. The | operator is perfect for this. Likewise, the & operator (combined with ~ for a bitwise NOT) works great to turn off a single bit without affecting the other bits. Study those two lines in my example code carefully until you understand exactly what they are doing.

If you were to run a program like this on a real microcontroller that had a real “LED” peripheral, you would physically see the LEDs changing each time the corresponding code wrote to the LED memory-mapped peripheral.

Back to the volatile keyword for a minute. Declaring a pointer as volatile forces the C compiler to always access the memory address a pointer points to, no matter what, with no optimizations allowed. You’ll notice that I write several different values to the LED peripheral in this program. A good compiler might notice that I first write 0 to it, then write 0x55, then turn on bit 7 (effectively writing 0xD5) and then turn off bit 0 (effectively writing 0xD4). It might think “hey, why should I do all these intermediate operations? I know that it will effectively end up with the value 0xD4, so why not just write that in directly?” For normal variables in a program, this could very well be a great idea to make your program run faster, because it would save unnecessary arithmetic operations from needing to be performed. For memory-mapped peripherals, it’s not such a great idea, because those intermediate values being written to the peripheral actually have a meaning. The volatile keyword simply makes sure the compiler does not make any optimization decisions like that. Whenever you’re accessing a memory-mapped peripheral, a pointer to it should be defined as volatile.

I will finish off this first real post of the series with a reality check. In my experience, there’s not really such thing as an “LED” peripheral. Instead, what you end up using is a “GPIO” peripheral. GPIO stands for General Purpose Input/Output. A microcontroller might have several “ports” — port A, B, C and D, for example, each eight bits. The physical chip would have pins corresponding to each port. Port A pin 0, port A pin 1, and so on. There would also be corresponding memory-mapped peripherals for each port. So if you had LEDs hooked up to port A pins 0 through 7, you could then do exactly what I showed in my “LED” example, except you would write to the GPIO port A peripheral, which would be memory mapped similar to how I described before.

It’s a little more complicated than that because I only really described the “output” capabilities of GPIO ports. You can also configure GPIO pins as inputs, so they read data from an external source and your program can see whether they are “high” or “low”. I hope that makes sense, and I’ll go into more detail about GPIO in the future. The memory space of a GPIO peripheral is more than just a byte wide. There are other sections of its memory space for configuring things like whether a pin is input or output, and also pull-up/pull-down resistors for inputs. In general, you will see these various sections of the memory-mapped address space referred to as the peripheral’s “registers.”

Anyway, that’s all for this first post. If you happen upon this post and have any questions, feel free to ask in the comments and I will try my best to answer them.

When I went to college, I majored in computer science. I took classes about algorithms, data structures, software engineering, design patterns, systems analysis and design (now that is a BORING topic!), web development, databases, operating systems, and even assembly language and computer architecture. To be honest, I actually thought those last two classes I listed were some of the more interesting topics my education covered (and they were both electives, not really part of the core CS curriculum). Maybe that’s a sign I should have done more in the computer engineering side of things. I don’t know for sure.

I’m not saying I didn’t enjoy my CS education, because I did! It was awesome, and I always looked forward to taking my CS classes. I was a math minor as well, and as you can probably guess, I enjoyed taking math classes. I actually took more math classes than I needed (such as operations research) just because they were fun. I guess my point is that I’m not dissing on my CS education; I’m only trying to point out that I had multiple interests in college.

After graduating college, I ended up working at a place that does a lot of work with microcontrollers. I’ve also written some “ordinary” desktop or web-app software, but I’ve found myself really enjoying the work with microcontrollers. As a person with a bachelor’s degree in computer science, I didn’t have any trouble picking up on the concepts. After all, computer science is not a “here’s how to program a generic desktop application in Visual Studio” type of education. You can apply what you learn to many different fields. But in order to fully understand the concepts, you have to do examples, at least in my opinion. And the examples I did in college were C/C++ console applications running on Linux, Java console and GUI applications, shell scripts, and websites in various flavors such as Java servlets, JSP, ASP.NET, PHP, and Ruby on Rails. All of this stuff is pretty high-level–even C apps running on Linux are high-level compared to bare metal code. So in doing this, I understood the general computer science ideas that the curriculum was actually teaching, but I didn’t really have any kind of concrete experience with directly programming to a microcontroller. Even in the assembly class, we ran programs on floppy disks inside of DOS, so that wasn’t bare metal either.

So as you might expect, when I first started at the place where I work, I knew literally nothing about how to use microcontrollers. I had no idea how microcontrollers actually did anything. I remembered from my assembly language class that x86 machines use a software interrupt instruction to talk to a PC’s BIOS, but that was about it. I heard my coworkers throw around terms like “SPI”, “I2C”, “UART”, “GPIO”, “PWM”, “DMA”, “CAN”, “Timers”, “Watchdog”, and all that kind of stuff, but had no idea what they meant.

Luckily, I have become familiar with this stuff (thanks to reading datasheets and my awesome coworkers, of course!), and once you get down to it, it’s really not complicated. It turns out I didn’t understand what goes on inside computers at one specific level. My computer architecture class was at too low of a level (transistors, gates, adders, ALU, etc.), and my assembly language class was at too high of a level (this is what registers are, this is what instructions are, here’s an example of how you multiply two numbers in the x86 instruction set, now go make your own DOS program that uses DOS and/or BIOS interrupt routines to do something cool), if that makes any sense at all.

I think it’s important to understand both of those levels, but there’s a level in between as well. I think I’ll call it “memory-mapped peripherals.” It turns out that microcontrollers have a bunch of special extra devices built in to assist you. They might do stuff like communicate with another chip that’s connected to it or display a message on an LCD display. Ok, so memory-mapped I/O is not really a “level”, but it points out a concept that somehow slipped through the cracks of my education.

So anyway, I’ve decided I’m going to write a series of posts about how to do microcontroller programming from the perspective of someone who has experience with “normal” application programming. I’ll try to teach all the stuff that datasheets just assume you know. I’m sure there are people out there with this same kind of issue. I know I was one of them! If you’re interested in this, stay tuned, and I will start doing more posts! Below is a list of posts in this series I have already written, and I’ll keep it up to date as I add more.

Posts in the series:

I was so excited about fixing that Polaroid DVD recorder on Thursday (see my last post) that I remembered I had an RCA DVD recorder also sitting around that had quit working. Quite a while ago, we had a power outage. When the power came back on, my RCA DRC8052NB DVD recorder wouldn’t turn on. The LCD on the front panel turned on, and the message “HELLO” scrolled across it. I couldn’t get it to stop without unplugging the power.

The normal behavior when you first plug it in is for the “HELLO” message to scroll across for a few seconds. Then it’ll say something like “NO DISC”. Finally, it’ll shut itself back down and display the time, waiting for you to power it back up. Then, when you press the power button to turn it on, the “HELLO” message will come back for a few seconds, and finally it will turn on and display the current channel number or “NO DISC” or whatever else, depending on the mode you left it in when it was last turned off.

Anyway, so “HELLO” kept scrolling indefinitely. I figured it was a similar problem to what I saw on the Polaroid DVD recorder. The difference was that in the Polaroid DVD recorder, nothing displayed on the front panel. At first thought, I figured it might have something to do with the power board. But because the LCD was displaying a message, that made me a bit skeptical because you’d think a program on the main DVD board would be displaying that message, which would mean the main DVD board would be getting a good 3.3V power input.

I went ahead and checked it out with my multimeter. This power supply board is a bit different because it needs some sort of signal to tell it to turn on. I tried powering it up with its cable that goes to the “motherboard” (I don’t know the technical term for it, so I’ll call it the motherboard from now on) disconnected, but nothing happened. So I had to leave the motherboard plugged into the supply while measuring the output voltages. Anyway, the 3.3V output was only 2.8V, and several of the other voltages were pretty far out of range too. Some of the 5V outputs were only 4.5V, and the 40V output was only 35V. Sounds like a power supply problem again…I guess the “HELLO” message doesn’t necessarily mean the output from the power supply is good.

My suspicion was confirmed when I found some other postings online about this exact same model. In fact, this question on FixYa has several answers all pointing to a single capacitor that was probably causing the problem. Another post on FixYa also seemed to point toward capacitors.

None of the capacitors on the power supply board looked weird. In the Polaroid DVD recorder I fixed earlier, two of the capacitors were bulging. In this one, nothing looked weird to me. But an answer to that first FixYa question I linked to above also pointed out that the capacitor looked OK but was still bad.

Based on the first FixYa question, I went ahead and desoldered the 1000uF, 6.3V capacitor (C22). Multiple answers in that question implied that particular capacitor was the source of the problem. Interestingly enough, the footprint on the board for that capacitor is a lot larger than the actual capacitor soldered in. It makes me think that perhaps the board was originally designed for a cap with higher ratings.

Luckily, when I fixed the Polaroid DVD recorder, I ordered two of each capacitor I replaced, even though I only needed one. As you’ll remember, one of those capacitors was a 1000uF, 16V capacitor. It perfectly fit the footprint on the RCA DVD recorder’s power board. Since it was the same capacitance with a higher max voltage, I was good to go.

I soldered it in, put the power board back into place and reconnected all of the wires going into it. I plugged the DVD recorder back into AC power. The “HELLO” message came on, and I crossed my fingers. A couple of seconds later, the “NO DISC” message appeared, and shortly thereafter, the display read “12:00 AM”. Awesome!

I pressed the power button to turn the DVD recorder back on. Then I measured some of the power board’s outputs. The 3.3V output now was correctly at 3.3V. The 40V output was still pretty low (36V) but it was higher than it was. I didn’t bother to check the 5V outputs because it was a tight fit and I didn’t want to short anything like I did in the Polaroid one!

Anyway, thanks to roybro123 and neveo1999 on FixYa. Their answers helped revive my DRC8052 DVD recorder.

Before I realized that I already had a 1000uF capacitor sitting around here, I ordered all new capacitors on DigiKey for the DVD recorder. Oh well–it’ll be nice to have the spare parts laying around in case another one goes bad.

In conclusion, cheap capacitors suck. Companies are saving a few pennies by using cheap capacitors instead of high-quality ones. Or maybe they’re not allowing for proper ventilation and the capacitors are getting stressed from too much heat. Something along those lines. It’s a little disturbing to me that these products came from two different manufacturers and they both had bad caps as the problem. The problem was widespread enough that other people saw it too. Whatever happened to quality control? I actually bought both of these DVD recorders on Woot.com for a really good deal, refurbished. I think I now know why the manufacturers were getting rid of them for so cheap. But anyway, Woot is an awesome website you should check out some time. 10 PM pacific time every night–a new deal!

Now that I’ve done some electronics repair blogs, I think I’ll go back into my area of expertise–computer stuff. I’m an electronics newbie. My soldering technique is terrible and I really don’t have a clue what I’m doing. I probably have no business working on power supply boards. I work for a company that makes electronics, but I don’t do any of the electronics stuff–I write software. But having coworkers around to answer my questions about the hardware stuff helps, so I guess that’s why I feel comfortable working on this stuff without worrying about getting lethally shocked.

Anyway, I don’t know what my next blog will be about, but I’ll think of something soon! Until next time, goodbye!

So today I finally fixed this Panasonic DRA-01601A DVD recorder. The symptoms were the following: you plug in the DVD recorder. The device automatically powers on, the fan starts spinning, and nothing else happens. The front display stays completely black, nothing appears on the video screen.

If you actually plan on trying this, BEWARE. The power supply board can carry high voltages that are very dangerous. There’s a reason these devices have a sticker telling you not to open it because there’s an electric shock risk. The big black capacitor near where the AC power enters the board can hold high voltages and should be discharged before working on it. If you don’t know what you’re doing, get someone else who does know what they are doing to fix it for you. I left it unplugged for a day and it was discharged by then, but I still checked it with a multimeter to make sure it was safe to work on the board.

I opened it up and disconnected the ribbon cable going from the tan colored power supply board to the green DVD recorder board. I removed it on the power supply board side so I could measure the power supply outputs. Using a multimeter I checked each output. The 3.3V output was out of range, somewhere in the 2-ish volt range. The rest were fine. I figured this was the problem, since it’s likely the DVD board needs the 3.3V output to run.

Looking at the board’s capacitors, I noticed two of them were bulging at the top. I circled them in red in the picture below. It may be hard to see in the pic, but the tops of those two capacitors look quite a bit different from the tops of all the rest of them.

Both of those green capacitors were bulging. In fact, the shorter one on the right had actually let out some gunk underneath. I replaced them with caps with matching capacitance/voltage ratings. One was 2200uF 10V, and the other was 1000uF 16V. I powered it up again and checked the outputs. The 3.3V output was now correct! I plugged everything back in, fired up the DVD recorder, and everything worked fine again. Great success! Honestly I probably should have replaced all four of those green caps. They look pretty cheap, and I doubt the other two will last long either.

Sidenote: While I was testing the outputs the first time, I accidentally shorted the -12V output to a nearby pin. I should have been more careful, but I was not. Unfortunately this caused a spark, and the power supply turned off momentarily and came back up. After that, the -12V output was screwed up and measuring very low voltage. I checked out diode D11 on the board and I had blown it–it was appearing as a short in both directions, pulling the output down to ground. The marking on the diode was not very helpful–it said something like:

C12
ET

Not the greatest identification. I looked for “C12 diode” on Google and most of the matches were 12V Zener diodes, so I got a 12V, 1W Zener diode (BZX85C12) and it seemed to work OK, and the output was fine after that. It was a little thicker than the original so maybe the original wasn’t 1W. Anyway, my guess is the diode was just for overvoltage protection, and it definitely did its job! (Or maybe it was being used as a cheapo voltage regulator?)

Edit 2: It looks like Qt 5.0 will now give us public access to QWinEventNotifier, so the contents of this article are definitely still useful. Thank you Leo (see the comments below) for pointing that out!

Edit: On April 30, 2011, Sebastian informed me that this approach no longer works in Qt 4.7.2. It looks like we no longer have access to the private header files. See the comments for more information where I describe what has changed and mention a few workarounds. My post continues unmodified below in case people are using older versions, or if we regain access to the QWinEventNotifier class in the future.

Lately I’ve been working with a CAN-USB adapter. I’ve been interfacing to it through a Qt GUI app. When you’re dealing with CAN, you need some kind of notification that you’ve received a message. On a microcontroller, an interrupt tells you when a message has arrived. With this CAN adapter, the driver needs to send some kind of notification to your app. Otherwise, you’re constantly polling to see if a new CAN message has arrived (and using up your computer’s CPU time needlessly).

This particular CAN adapter has both Linux and Windows drivers. The two drivers use slightly different APIs, so I’ve been using #ifdefs for the Qt app to work on both platforms.

On Linux, the driver gives you a file descriptor that you can pass to select() or a similar function to wait for activity, similar to how you’d wait for activity from a socket. In fact, that’s exactly how you handle it in Qt — you make a QSocketNotifier with the file descriptor the driver library gave you, and then the QSocketNotifier fires its activated() signal whenever a CAN message comes in. So this effectively integrates the USB to CAN adapter into the main thread’s event loop.

Dealing with this device in Windows is a little more complicated. First of all, the driver DLL doesn’t work with MinGW out of the box, but there are tutorials on the web with instructions to get a DLL compiled with Microsoft’s compiler to work correctly with MinGW. I can’t remember exactly how I did it, but those tutorials helped me with that. It was something about the way the functions in the DLL export file were named. Maybe I’ll write another blog post about that later, if I can figure out how I did it the first time. Bad Doug!

Anyway, the other thing about the Windows driver is that it doesn’t give a file descriptor to notify you that a CAN message has arrived. Instead, you’re supposed to pass it a Windows event handle, which it will then put into the signaled state whenever a message comes in. So you’re supposed to create a Windows event object with CreateEvent() and give the newly created event handle to the CAN library. Then, in a Windows app, you would use WaitForSingleObject() or something like that to wait for the driver to signal you.

Using this info, you could already solve the problem in a Qt app. Create a new thread in Qt that sits in a while loop, calling WaitForSingleObject() with an unlimited timeout. Whenever the event object is signaled, emit a Qt signal. You can then attach a slot in the main thread to that signal, and then you will be notified whenever a new CAN message is ready. This approach works, but it just seems like overkill because you’re creating a new thread with its own mini event loop just to forward the event to Qt’s event loop. Qt’s main thread already has an event loop, so why not just get the main thread’s event loop to listen for the event directly?

It turns out this is definitely possible to do with Qt. It’s just that the class is kind of hidden in the bowels of Qt, probably because it’s a Windows-specific thing. The class is called QWinEventNotifier, and you can use it in a Qt app by doing:

#include <QtCore/private/qwineventnotifier_p.h>
(Thanks, QExtSerialPort, for showing how to #include this class in your code–I saw it in Qt’s source code, but I couldn’t figure out how to add it in my program.)

From this point on, it’s simple. 3weyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu (Sorry, that was the kitten.) Just create a QWinEventNotifier, passing the event handle returned from CreateEvent() to the constructor. Connect the QWinEventNotifier’s activated(HANDLE) signal to a slot. That’s it! Qt will take care of it from there, giving you a notification whenever a CAN message is ready for reading.

You don’t have to do anything special to be able to call CreateEvent, at least in my experience. Just #include <windows.h> and then you have complete access to CreateEvent and whatever other Windows function you need. It all just works.

I’m sure this can be adapted to work with other Windows event type stuff. Since my description of this solution was a little abstract, I’ll provide a concrete (silly) code example. I create a thread that does nothing other than signal a Windows event object every second or so. This is basically simulating the CAN library signaling when a message is received. Other than that, the main thread just creates a QWinEventNotifier that receives that signal. Here ya go:

wineventtestthread.h:

#ifndef WINEVENTTESTTHREAD_H
#define WINEVENTTESTTHREAD_H

#include <windows.h>
#include <QThread>

class WinEventTestThread : public QThread
{
    Q_OBJECT
public:
    explicit WinEventTestThread(void *eventH, QObject *parent = 0);
    void run();
private:
    HANDLE eventHandle;
    bool keepRunning;
signals:

public slots:

};

#endif // WINEVENTTESTTHREAD_H

wineventtestthread.cpp:

#include "wineventtestthread.h"
#include <QDebug>

WinEventTestThread::WinEventTestThread(HANDLE eventH, QObject *parent) :
    QThread(parent)
{
    this->eventHandle = eventH;
    this->keepRunning = false;
}

void WinEventTestThread::run()
{
    qDebug() << "Test thread ID: " << QThread::currentThreadId();
    this->keepRunning = true;

    while (this->keepRunning)
    {
        // wait a second
        sleep(1);

        // signal the windows event
        if (SetEvent(this->eventHandle) == 0)
        {
            qDebug() << "Test thread: Error signaling event";
        }
        else
        {
            qDebug() << "Signaled event in thread " << QThread::currentThreadId();
        }
    }
}

mainwindow.h:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <windows.h>
#include <QMainWindow>
#include <QtCore/private/qwineventnotifier_p.h>
#include "wineventtestthread.h"

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private:
    Ui::MainWindow *ui;
    WinEventTestThread *thread;
    HANDLE eventHandle;
    QWinEventNotifier *notifier;
private slots:
    void eventSignaled(HANDLE h);
};

#endif // MAINWINDOW_H

mainwindow.cpp:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // create the windows event
    qDebug() << "Main thread ID: " << QThread::currentThreadId();

    this->eventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);

    if (this->eventHandle == NULL)
    {
        qDebug() << "Error creating event handle.";
    }
    else
    {
        // set up notifications when it's signaled
        notifier = new QWinEventNotifier(this->eventHandle);
        connect(notifier, SIGNAL(activated(HANDLE)), SLOT(eventSignaled(HANDLE)));
        thread = new WinEventTestThread(this->eventHandle);

        // start the test thread (it will start signaling the windows event)
        thread->start();
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::eventSignaled(HANDLE h)
{
    qDebug() << "Signal received in thread " << QThread::currentThreadId();
}

Voilà!

Recently I’ve been reading about how Flash has its own “cookies” where websites can store data, called Local Shared Objects. People who don’t like the possibility of being tracked often delete their browser’s cookies, but many people overlook the Flash Local Shared Object collection. I consider myself a savvy computer user, and I certainly didn’t think of them until the last couple of months.

Flash Player Settings Manager

You can edit the settings that specify which websites are allowed (and not allowed) to save flash cookies using Adobe’s web-based Website Storage Settings panel. Unfortunately, to be frank, it sucks. Why? I’ll tell you why:

  1. You can’t sort the list of websites. The order they appear in the list is totally arbitrary (to my knowledge). If I’m looking for a specific website to delete its cookies, I have to search through the entire list until I find it. I can’t use my brain to do a binary search on it, since it’s not sorted. 😉
  2. You can’t search for a specific website in the list. Honestly, if I could search for a site by name, I wouldn’t really care about complaint #1 above. But since I can’t, it also belongs on this list.
  3. The scrollable list of websites is only four items high. It’s bad enough that it’s in an arbitrary order, but searching through a long list is absolutely hellish when the list can only show four items at a time.

No offense intended toward the designer of this panel. I’m a developer, and I know I’ve made my fair share of UIs that could use some improvement. I doubt many people use the panel anyway, so it’s probably not high on any kind of priority list. Anyway, the point of this post is not to trash on Adobe’s settings manager, but it’s to recommend an alternative.

I was going to write my own editor for these storage settings, but then I discovered that BetterPrivacy already exists. It’s a Firefox extension that allows you to do pretty much everything the Website Storage Settings panel does, but in a much less masochistic manner. I didn’t do any searching for such an add-on for Internet Explorer, Safari, or Chrome, but they may exist. Anyway, I may still make an app to edit these suckers just for fun, although others probably already exist.

If you don’t mind forbidding all websites from saving Flash cookies, which may cause you to lose saved usernames in Flash websites (if that matters), you can forget having to deal with BetterPrivacy. Instead, delete all your Flash cookies in the Website Storage Settings panel I already mentioned, and then set the global size to zero (and “Never Ask Again”) at the Global Storage Settings panel. Doing so will prevent Flash from saving Local Shared Objects, period.

That’s all for now!