10. Grayscale Sensor¶
This sensor is used to detect the light density and reflect the analog voltage signal back. So it can be used to detect black and white colors. Below is an example of some material light density.

Warning
Before proceeding with this sensor, you will need to learn about the MCP3008 ADC.
10.1. Connecting the Sensor¶
The grayscale sensor is an analog sensor and cannot be connected directly to the Raspberry Pi pins. It needs an analog to digital converter, MCP3008 ADC in this case, in order to collect proper data.

10.2. Python Program to Get Readings¶
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 43 44 45 46 47 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: Sum=0 Sum2=0 ldr_value=readadc(0) 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 result = ((Sum + Sum2)/1024.0) if result > 0.1: print 'Black' else: print 'White' time.sleep(delay)