Adventures in Real-Time with the Raspberry Pi

From UmbraXenu
Jump to navigation Jump to search

For a music box project, I want to use a potentiometer volume control, and a light-controlled resistor (LCD) measuring the room lighting to control things like the display backlighting.

Converting the analog resistor values to digital inputs that the Pi can use can be done in a number of ways, but the classic quick and dirty method is to use a resistor-capacitor pair tied to an I/O pin, and measure the time for the capacitor to charge through the resistor and change the input value. The time will vary directly proportional with the resistance.

The classic way to measure this time is to use a counting loop that checks the input value. Back in the Apple II days, that code would be fine, but on the Raspberry Pi, it's only intended as an example. It wouldn't be very usable in real applications because the counted value has all kinds of dips in the result without changing the resistor.

A Raspberry Pi is more powerful than an Apple II by magnitudes, so what's the problem?

This, that and the other thing

A Raspberry Pi, running Linux, is doing a lot of other things in the background. On the Apple II, user programs had pretty much complete control of the processor, but on the Pi many things are also happening: other programs, cron jobs, disk and network I/O, updating the screen, garbage collection... Even on a multi-core Pi, these steal time from our counting loop. In the long run, these interruptions are smoothed over, but the closer we get to real time, the larger these interruptions become.

Obviously the old counting loop pattern isn't the way to do it on the Pi. (It's also a wasteful method, even on the Apple II.)

Alternatives

  • Don't start from here: Use extra hardware like an A/D chip, Arduino, PIC processor to do the measuring for you. This is probably the best way if you need dependable results.
  • Take total control! Use an OS that lets you have all the processor without interruptions.
  • Work smarter, not harder. This is the option I'll explore.

How real is "real time" really?

Unless you're carefully counting gate delays and starting to worry about the speed of electrical signals, not so much. It's all about the resolution of events that you're dealing with.

If you're pouring wine, "now" can be within a second. If turning on lights at night, five minutes is probably an acceptable window.

Useful software