Authorized Online Retailers:

AMAZON
AMAZON-jp
amzuk

Overview

In the lesson, we’ll show how to using mcp3008 to read Photo-resistor (light sensor) data and control the led brightness.

Hardware Preparation

1 * Raspberry Pi
1 * Breadboard
1 * 10K resistor
1 * Photo-resistor
1 * LED
Jumper wires
1 * T-Extension Board
1 * 40-Pin Cable

Software Preparation
Note: In this lesson, we remotely control raspberry pi via PuTTy on PC. To learn how to config raspberry pi, please visit lesson 1: getting started with raspberry pi.

Work Principle

A photoresistor is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing light intensity.

In this project we use MCP3008 ADC to read the photoresistor voltage value which changes with light. the MCP3008 convert the analog voltage  value to digital signal(binary value) and sent it to the Pi. Then Pi changes PWM input value to control the LED brightness.
Circuit Graph:


Hardware Setup

Sample code

we’ll provide two kinds of codes for C language users and Python language users.

For C language users ,please take following steps:


Note: If you have not installed wiringPi library. Please install it as per our Lesson 3

1)  Download the sample code from osoyoo by typing the following command:

cd   ~

sudo  sudo  wget  http://osoyoo.com/driver/pi3_start_learning_kit_lesson_11/lightsensor.c

Note:
If you want to customize the sample code file , you can use nano editor to edit source code by typing following command in terminal:
sudo nano  lightsensor.c

2)  Compile Code

gcc  -Wall  -o  lightsensor  lightsensor.c  -lwiringPi

3) Run program

A)Before running the program, check MOSI, MISO, SCLK(B10, B9, B11) work mode is ALT0(alternative functions) by typing terminal command:gpio  readall If the mode is not ALTO, Please running the terminal command as followed:

gpio  -g  mode  9    alt0

gpio  -g  mode  10   alt0

gpio  -g  mode   11   alt0

B) Run the program

sudo  ./lightsensor

4) Test Result

When program is executed, the terminal will show print message as code firstly,then show the photoresistor ADC value(voltage). when the photoresistor is shaded, the LED brightness will increase, when  photoresistor is unshaded, the LED brightness will decrease.

Sample Code and Explanation comments

 
 
  1. #include < unistd.h >
  2. #include < stdint.h >
  3. #include < string.h >
  4. #include < errno.h >
  5. #include < wiringPi.h >
  6. #include < stdio.h >
  7. #include < stdlib.h >
  8. #include < wiringPiSPI.h >
  9. //pin 1(BCM GPIO 18) is PWM port
  10. #define LEDPIN 1
  11. //binary number 1000 (decimal 8) is analog channel prefix
  12. #define CHAN_CONFIG_SINGLE 8
  13. //About SPI channel, read http://osoyoo.com/?p=7612
  14. //since B8 connect to CS/SHDN pin, we need select SPI Channel to 0
  15. #define SPICHANNEL 0
  16. //our light sensor connect to MCP3008 CH0, we set annanalog channel to 0
  17. #define ANALOGCHANNEL 0
  18. static int myFd ;
  19. void spiSetup (int spiChannel)
  20. {
  21. if ((myFd = wiringPiSPISetup (spiChannel, 10000)) < 0)
  22. {
  23. fprintf (stderr, "Can't open the SPI bus: %s\n", strerror (errno)) ;
  24. exit (EXIT_FAILURE) ;
  25. }
  26. }
  27. int myAnalogRead(int spiChannel,int channelConfig,int analogChannel)
  28. {
  29. if(analogChannel7)
  30. return -1;
  31. unsigned char buffer[3] = {1}; // start bit
  32. buffer[1] = (channelConfig+analogChannel)
  33. wiringPiSPIDataRW(spiChannel, buffer, 3);
  34. return ( (buffer[1] & 3 )
  35. }
  36. void print_info()
  37. {
  38. printf("\n");
  39. printf("|************************************|\n");
  40. printf("| MCP3008 read lightsensor |\n");
  41. printf("| ------------------------- |\n");
  42. printf("| | ADC | | Pi | |\n");
  43. printf("| |-----|-----------|-----| |\n");
  44. printf("| | CS | connect to| CE0 | |\n");
  45. printf("| | Din | connect to| MOSI| |\n");
  46. printf("| | Dout| connect to| MISO| |\n");
  47. printf("| | CLK | connect to| SCLK| |\n");
  48. printf("| | CH0 | connect to| 3.3V| |\n");
  49. printf("| | CH1 | connect to| GND | |\n");
  50. printf("|************************************|\n");
  51. printf("| LED connect to GPIO1 |\n");
  52. printf("| OSOYOO|\n");
  53. printf("|************************************|\n");
  54. printf("\n");
  55. }
  56. int main()
  57. {
  58. int adc;
  59. if(wiringPiSetup()
  60. {
  61. printf("setup wiringPi failed!\n");
  62. printf("please check your setup\n");
  63. exit(1);
  64. }
  65. spiSetup(SPICHANNEL);
  66. pinMode(LEDPIN,PWM_OUTPUT);
  67. print_info();
  68. for(;;)
  69. {
  70. //read voltage value from analog CH0 pin data from SPI channel 0
  71. adc = myAnalogRead(SPICHANNEL,CHAN_CONFIG_SINGLE,ANALOGCHANNEL);
  72. printf("ADC = %d\n",adc);
  73. //adc is a value between 0 to 1023, 1023 means max vref value 3.3V
  74. pwmWrite(LEDPIN,1023-adc);
  75. delay(1000);
  76. }
  77. }
  78. for(;;)
  79. {
  80. adc = myAnalogRead(SPICHANNEL,CHAN_CONFIG_SINGLE,ANALOGCHANNEL);
  81. printf("ADC = %d\n",adc);
  82. //USE pwmWrite function defined in to control LED brightness
  83. pwmWrite(LEDPIN,1023-adc);
  84. delay(1000);
  85. }

For python user,please take following steps:


When programming with Python language , normally we use GPIO library called RPi.GPIO which comes with Rasbian Jessie OS.
Click here to get more info about RPI.GPIO and Python.

1)  download the sample code from osoyoo by typing following commands:

cd  ~

sudo   wget  http://osoyoo.com/driver/pi3_start_learning_kit_lesson_11/lightsensor.py

Note:
If you want to customize the sample code file , you can use nano editor to edit source code by typing following command in terminal:

sudo nano  lightsensor.py

2)Run the program by typing following command:

sudo  python  ./lightsensor.py

3) Running result

Once run the program, the terminal will show print message as code firstly, then show the lightsensor AD value. when you cover the Photoresistor, the LED brightness will increase, when increase incident light intensity on Photoresistor, the LED brightness will decrease.

Python Sample Code and Explanation comments

 
 
  1. import time
  2. import os
  3. import RPi.GPIO as GPIO
  4. # change these as desired - they're the pins connected from the
  5. # SPI port on the ADC to the Cobbler
  6. SPICLK = 11
  7. SPIMISO = 9
  8. SPIMOSI = 10
  9. SPICS = 8
  10. #set BCM_GPIO 18(GPIO1) as LED pin
  11. LEDPIN = 18
  12. analogChannel = 0
  13. #setup function for some setup---custom function
  14. def setup():
  15. global p
  16. GPIO.setwarnings(False)
  17. #set the gpio modes to BCM numbering
  18. GPIO.setmode(GPIO.BCM)
  19. # set up the SPI interface pins
  20. GPIO.setup(SPIMOSI, GPIO.OUT)
  21. GPIO.setup(SPIMISO, GPIO.IN)
  22. GPIO.setup(SPICLK, GPIO.OUT)
  23. GPIO.setup(SPICS, GPIO.OUT)
  24. #set all LedPin's mode to output,and initial level to HIGH(3.3V)
  25. GPIO.setup(LEDPIN,GPIO.OUT,initial=GPIO.LOW)
  26. #set LEDPIN as PWM output,and frequency=100Hz
  27. p = GPIO.PWM(LEDPIN,100)
  28. #set p begin with ualue 0
  29. p.start(0)
  30. pass
  31. #print message at the begining ---custom function
  32. def print_message():
  33. print ('|**********************************|')
  34. print ('| MCP3008 read lightsensor |')
  35. print ('| ----------------------------- |')
  36. print ('| | ADC | | Pi | |')
  37. print ('| |-----|-----------|-----| |')
  38. print ('| | CS | connect to| CE0 | |')
  39. print ('| | Din | connect to| MOSI| |')
  40. print ('| | Dout| connect to| MISO| |')
  41. print ('| | CLK | connect to| SCLK| |')
  42. print ('| | CH0 | connect to| 3.3V| |')
  43. print ('| | CH1 | connect to| GND | |')
  44. print ('| ********************************** |')
  45. print (' LED connect to GPIO1')
  46. print ('| OSOYOO|')
  47. print ('|**********************************|\n')
  48. print ('Program is running...')
  49. print ('Please press Ctrl+C to end the program...')
  50. # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
  51. def readadc(adcnum, clockpin, mosipin, misopin, cspin):
  52. if ((adcnum > 7) or (adcnum < 0)):
  53. return -1
  54. GPIO.output(cspin, True)
  55. GPIO.output(clockpin, False) # start clock low
  56. GPIO.output(cspin, False) # bring CS low
  57. commandout = adcnum
  58. commandout |= 0x18 # start bit + single-ended bit
  59. commandout
  60. for i in range(5):
  61. if (commandout & 0x80):
  62. GPIO.output(mosipin, True)
  63. else:
  64. GPIO.output(mosipin, False)
  65. commandout
  66. GPIO.output(clockpin, True)
  67. GPIO.output(clockpin, False)
  68. adcout = 0
  69. # read in one empty bit, one null bit and 10 ADC bits
  70. for i in range(12):
  71. GPIO.output(clockpin, True)
  72. GPIO.output(clockpin, False)
  73. adcout = 1 # first bit is 'null' so drop it
  74. return adcout
  75. #main function
  76. def main():
  77. while True:
  78. #print info
  79. print_message()
  80. adc = readadc(analogChannel, SPICLK, SPIMOSI, SPIMISO, SPICS)
  81. print ('LightSensor ADC = %d'%(adc))
  82. adc=(1023-adc)*100/1023
  83. p.ChangeDutyCycle(int(adc))
  84. time.sleep(1)
  85. #define a destroy function for clean up everything after the script finished
  86. def destroy():
  87. #stop p
  88. p.stop()
  89. #turn off led
  90. GPIO.output(LEDPIN,GPIO.LOW)
  91. #release resource
  92. GPIO.cleanup()
  93. #
  94. # if run this script directly ,do:
  95. if __name__ == '__main__':
  96. setup()
  97. try:
  98. main()
  99. #when 'Ctrl+C' is pressed,child program destroy() will be executed.
  100. except KeyboardInterrupt:
  101. destroy()
  102. adc=(1023-adc)*100/1023
  103. p.ChangeDutyCycle(int(adc))

Leave a Reply

WordPress spam blocked by CleanTalk.
Bombax Theme designed by itx
"