Luscious Light


This section has a couple of brief recipes for doing useful things with light sensing.

Using median filter to get reliable ambient light level

The light sensor is typically effected by shadowing, things like where someone passes a sensor briefly, or by reflections where a light flashes onto the sensor.

As an example of how this can cause issues we can consider chickens (Figure ). Domestic chickens are creatures of habit, when dusk falls, they return to their hen house and roost. Foxes are also creatures of habit. When it gets dark, they go out looking for poultry to eat (or anything else small really, foxes are very unfussy). Humans who keep chickens need to go out around dusk and close the hen-house door. Otherwise bad things happen. Unfortunately, humans are not so much creatures of habit, they have a tendency to get distracted, or be late back from work or whatever. Because of this, the automatic hen-house door closer was created. What this does is use a light sensor to detect dusk falling, and close the door, keeping chicken and fox safely separate. In the morning, the light sensor triggers and opens the door again.

A chicken
This is an entirely gratuitous chicken.

So what goes wrong with this and why am I going on about chickens here?

So in early versions of these devices, they used very rudimentary sensors which basically just used pretty raw light value output to trigger door open or close. They discovered a problem, which was that if these were placed near a road, or in a yard where people parked cars, the car headlight beams would trigger the door to open and allow naughty Mr Fox to eat the chickens. More modern versions use filtering to avoid unwanted triggers.

Detecting artificial light switching

Lets say we have a simple light sensor and we want to know whether the light falling onto it is a) artificial light or b) sunlight. One way to do this is to detect when lights are switched on or off.

The code below first filters out brief changes in light levels to avoid being triggered by shadowing, using a median filter, then uses a high pass filter on that to detect abrupt and persistent changes in light state which indicate light on or light off. It also has a lower threshold for light level below which it assumes that there can’t be any light turned on.

Try playing with this algorithm then think about the following questions:

  1. When might it fail to detect light switching?
  2. When might it detect the light is on when it isn’t?
  1. The obvious example of a false negative with this algorithm is if you turn on a light when there is sunlight in the room already.
  2. If you open curtains in a room letting in sunlight suddenly, you will get a false positive with this algorithm.