The following code shows a method of reading analogue sensors on the digital input only Pi. A Light Dependent Resistor (LDR) varies its resistance according to the incident light intensisty.
Here P1-1 is used for 3V3, P1-20 is used for ground, and gpio 18
(P1-12) is used for the gpio.
#include <stdio.h>
#include <pigpio.h>
/*
-----------------------------------------------------------------------
3V3 ----- Light Dependent Resistor --+-- Capacitor
----- Ground
|
+-- gpio
cc -o LDR LDR.c -lpigpio -lpthread -lrt
sudo ./LDR
*/
#define LDR 18
/* forward declaration */
void alert(int pin, int level, uint32_t tick);
int main (int argc, char *argv[])
{
if (gpioInitialise()<0) return 1;
gpioSetAlertFunc(LDR, alert); /* call alert when LDR
changes state */
while (1)
{
gpioSetMode(LDR, PI_OUTPUT); /*
drain capacitor */
gpioWrite(LDR, PI_OFF);
gpioDelay(200); /* 50 micros is
enough, 200 is overkill */
gpioSetMode(LDR, PI_INPUT); /* start
capacitor recharge */
gpioDelay(10000); /* nominal 100
readings per second */
}
gpioTerminate();
}
void alert(int pin, int level, uint32_t tick)
{
static uint32_t inited = 0;
static uint32_t lastTick, firstTick;
uint32_t diffTick;
if (inited)
{
diffTick = tick - lastTick;
lastTick = tick;
if (level == 1) printf("%u %d\ ",
tick-firstTick, diffTick);
}
else
{
inited = 1;
firstTick = tick;
lastTick = firstTick;
}
}
cc -o LDR LDR.c -lpigpio -lrt -lpthread
sudo ./LDR >LDR.dat &
pigs no
pig2vcd </dev/pigpio0 >LDR.vcd &
pigs nb 0 0x40000 # set bit for gpio 18
Change the light falling on the LDR for a few seconds (e.g.
shine a torch on it or shade it with your hands).
pigs nc 0
The file LDR.vcd will contain the captured waveform, which can be viewed using GTKWave.
Overview
Reading circa every 10ms
One reading, circa 400us
The file LDR.dat will contain pairs of timestamps and recharge
time (in us). The following script will convert the
timestamps into seconds.
awk '{print $1/1000000, $2}' LDR.dat
>LDR-secs.dat
Gnuplot is a useful tool to graph data.
Gnuplot readings 14-24 seconds