Grove - Light Sensor

Från Karlskrona Makerspace Wiki
Version från den 26 oktober 2018 kl. 21.36 av Christian (diskussion | bidrag)
(skillnad) ← Äldre version | Nuvarande version (skillnad) | Nyare version → (skillnad)
Hoppa till: navigering, sök

Kompatibilitet

Port

  • Analog

Exempelkod

Arduino

const int pinLight = A0;
const int pinLed   = 7;

int thresholdvalue=400;                 //the threshold to turn on or off the LED

void setup()
{
    pinMode(pinLed, OUTPUT);             //set the LED on Digital 12 as an OUTPUT
}

void loop()
{
    int sensorValue = analogRead(pinLight);    //the light sensor is attached to analog 0
    if(sensorValue<thresholdvalue)
    {
        digitalWrite(pinLed, HIGH);
    }
    else
    {
        digitalWrite(pinLed, LOW);
    }
}

Raspberry Pi

import time
import grovepi

# Connect the Grove Light Sensor to analog port A0
# SIG,NC,VCC,GND
light_sensor = 0

# Connect the LED to digital port D4
# SIG,NC,VCC,GND
led = 4

# Turn on LED once sensor exceeds threshold resistance
threshold = 10

grovepi.pinMode(light_sensor,"INPUT")
grovepi.pinMode(led,"OUTPUT")

while True:
    try:
        # Get sensor value
        sensor_value = grovepi.analogRead(light_sensor)

        # Calculate resistance of sensor in K
        resistance = (float)(1023 - sensor_value) * 10 / sensor_value

        if resistance > threshold:
            # Send HIGH to switch on LED
            grovepi.digitalWrite(led,1)
        else:
            # Send LOW to switch off LED
            grovepi.digitalWrite(led,0)

        print("sensor_value = %d resistance = %.2f" %(sensor_value,  resistance))
        time.sleep(.5)

    except IOError:
        print ("Error")

Mer information

http://wiki.seeedstudio.com/Grove-Light_Sensor/