8. Voltage Sensor

../_images/voltagesensor.jpg

There are many applications for the voltage sensor, such as measuring battery levels (Voltage), estimating battery life, tracking solar power generation or even to measure how many power consumption is being used by the raspberry pi. This module allows you to measure voltages of 0-25V.

Warning

Before proceeding with this sensor, you will need to learn about the MCP3008 ADC.

8.1. Connecting the Sensor

../_images/voltagesensor-nopi.jpg

Inputs:

  • GND: Connected to the low side of the voltage you are measuring.
  • VCC: Connected to the high side of the voltage you are measuring

Outputs

  • S: Connected to your MCP analog input.
  • ‘-‘ (or minus): Connected to the ground.
  • ‘+’: not connected.

Note that the voltage sensor is an analog sensor and cannot be connected directly to the Raspberry Pi pins. It needs an analog to digital converter, MCP3008 in this case, in order to collect proper data.

Full circuit:

../_images/voltagesensor1.jpg

8.2. Python Program to Read Voltage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import spidev
import time

delay = 0.5
ldr_channel = 0

spi = spidev.SpiDev()
spi.open(0,0)

def readadc(num):
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer([1, 8+adcnum << 4, 0])
    data = ((r[1]&3)<<8 + r[2])
    return data

while True:
    for i in range(8):
        Sum=0
        Sum2=0
        ldr_value=readadc(i)
        if ldr_value != 0:
            result = ldr_value/1024;
            Sum=Sum+10
            while result != (ldr_value%1023):
                result = result/1024
                Sum = Sum + 10
                if Sum > 1024:
                    break
                
            result = ldr_value%1023
            while result != 1:
                result = result/2
                Sum2 = Sum2 + 1
                if Sum2 > 1024:
                    break

        vout = ((Sum + Sum2) * 5.0)/1024
        vin = vout / 0.2 #(75/300 + 75)
        print ("_______________________")
        print ("LDR Value:" + str(vin) + " " + str(i))
        time.sleep(delay)