Grove - Rotary Angle Sensor

Från Karlskrona Makerspace Wiki
Version från den 3 februari 2021 kl. 15.13 av Christian (diskussion | bidrag)
Hoppa till: navigering, sök
Grove - Rotary Angle Sensor

Kompatibilitet

  • Arduino
  • Raspberry Pi

Port

Analog

Exempelkod

Arduino

// Rotary Angle Sensor example
const int potentiometer = A0;                    // rotary angle sensor connect to A0

void setup()
{
    Serial.begin(9600);                         // set the serial communication frequency at 9600 bits per sec
    pinMode(potentiometer, INPUT);
}

void loop()
{
    int value = analogRead(potentiometer);
    Serial.println(value);                      // pirnt the value on the serial monitor screen
    delay(100);                                  // wait 1000ms before printing next value
}

Raspberry Pi

import time
import grovepi

# Connect the Grove Rotary Angle Sensor to analog port A0
# SIG,NC,VCC,GND
potentiometer = 0

# Connect the LED to digital port D5
# SIG,NC,VCC,GND
led = 5

grovepi.pinMode(potentiometer,"INPUT")
grovepi.pinMode(led,"OUTPUT")
time.sleep(1)

# Reference voltage of ADC is 5v
adc_ref = 5

# Vcc of the grove interface is normally 5v
grove_vcc = 5

# Full value of the rotary angle is 300 degrees, as per it's specs (0 to 300)
full_angle = 300

while True:
    try:
        # Read sensor value from potentiometer
        sensor_value = grovepi.analogRead(potentiometer)

        # Calculate voltage
        voltage = round((float)(sensor_value) * adc_ref / 1023, 2)

        # Calculate rotation in degrees (0 to 300)
        degrees = round((voltage * full_angle) / grove_vcc, 2)

        # Calculate LED brightess (0 to 255) from degrees (0 to 300)
        brightness = int(degrees / full_angle * 255)

        # Give PWM output to LED
        grovepi.analogWrite(led,brightness)

        print("sensor_value = %d voltage = %.2f degrees = %.1f brightness = %d" %(sensor_value, voltage, degrees, brightness))
    except KeyboardInterrupt:
        grovepi.analogWrite(led,0)
        break
    except IOError:
        print ("Error")

Mer information

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