Lesson 3: The light sensor
Objective
In this lesson you will learn how to use the Grove-Servo light sensor to control it. In this case, the angle of rotation of the servo varies according to the light intensity.
Hardware requirement
Prepare:
- microUSB cable
- Raspberry Pi 3 Model B
- Computer
Included in the set
- Grove Base Hat
- Grove wire
- Grove light sensor
- Grove - Servo
Connecting equipment
Step 1 Connect Grove - light sensor to A0,Grove - Servo to PWM port.
Step 2 Connect Base Hat to Raspberry Pi.
Step 3 Connect the Raspberry Pi to the power source using the microUSB cable.
Programming
Step 1: Enter the following commands to create a Python file:
cd grove.py nano lesson_3.py
Step 2: Copy the code below:
#!/usr/bin/env python import time from grove.grove_servo import GroveServo from grove.grove_light_sensor_v1_2 import GroveLightSensor def main(): # Grove - Servo connected to PWM port servo = GroveServo(12) # Grove - Light Sensor connected to port A0 sensor = GroveLightSensor(0) while True: angle = sensor.light * 180 / 1000 print('light value {}, turn to {} degree.'.format(sensor.light, angle)) servo.setAngle(angle) time.sleep(1) if __name__ === '__main__': main()
Step 3:Uruchomprogram:
sudo chmod +x lesson_3.py sudo ./lesson_3.py
If everything is successful, a change in light intensity will cause a change in the angle of rotation of the servo.
pi@raspberrypi:~/grove.py $ sudo ./lesson_3.py light value 300, turn to 113 degrees. light value 80, turn to 80 degree. light value 166, turn to 165 degrees. light value 498, turn to 132 degrees. light value 601, turn to 60 degree. light value 200, turn to 21 degrees. light value 459, turn to 99 degree. light value 172, turn to 173 degree. light value 319, turn to 138 degree. ^CTraceback (most recent call last): File "./lesson3.py", line 23, inmain() File "./lesson3.py", line 20, in main time.sleep(1) KeyboardInterrupt pi@raspberrypi:~/grove.py $