B4R Code Snippet Set servo angle via potentiometer and show on display

Discussion in 'B4R Code Snippets' started by Peter Simpson, Apr 13, 2017.

  1. Peter Simpson

    Peter Simpson Well-Known Member Licensed User

    SubName: Set a servo angle and show the angle reading on a OLED display
    Description: Their are already a few servo examples on this forum, but here is my take on it. I'm using a quality TURNIGY servo and a standard cheap 10kΩ potentiometer. As you turn the potentiometer the display changes to shows you the angle that the servo is set to, reading ranges from 0° to 179°.

    Note: Using a quality servo is a good idea.
    I used one of my 450/550 RC Heli TURNIGY metal gear servos because they do actually rotate 180°. My cheaper servos tend to only rotate about 160° which is adequate for RC but not for this particular B4R project.
    Code:
    Sub Process_Globals
        
    'These global variables will be declared once when the application starts.
        'Public variables can be accessed from all modules.
        Public Serial1 As Serial

        
    Private Servo As Servo
        
    Private Potentiometer As Pin
        
    Private SSD As AdafruitSSD1306
        
    Private BC As ByteConverter
    End Sub

    Private Sub AppStart
        Serial1.Initialize(
    115200)
        
    Log("AppStart")

        Potentiometer.Initialize(
    0, Potentiometer.AnalogRead)
        Servo.Attach(
    2)

        SSD.InitializeI2C(
    40x3c'Initialise the display on address 0x3c
        SSD.GFX.ConfigureText(4, SSD.WHITE, False'Set display font size and colour

        AddLooper(
    "Loopey")
    End Sub

    Sub Loopey
        Servo.write(MapRange(Potentiometer.AnalogRead, 
    010230179)) 'Read potentiometer value (0 to 1023) and set servo position to the mapped value

        SSD.ClearDisplay
        SSD.GFX.SetCursor(
    203)
        SSD.GFX.DrawText(JoinStrings(
    Array As String(Servo.Read, BC.StringFromBytes(Array As Byte(247))))) 'Read the servo and display the angle
        SSD.Display
    End Sub
    Tags: 10kΩ, Potentiometer, Servo, OLED, Display, Arduino

    10KΩ potentiometer, Microprocessor is connected to analog pin 0 on the Arduino.
    Untitled-1.jpg

    How it's wired up.
    Servo-Potentiometer_bb.png

    What it looks like with the servo set to 90°.
    IMG_20170413_015230.jpg

    Enjoy...
     
    Last edited: Apr 19, 2017
Loading...