Simple example of using a rotary encoder to drive an RGB LED. At first, you can control the brightness of the red LED. Push the encoder shaft in and you can then control green. Push again to control blue. Then it repeats.

Dependencies:   mRotaryEncoder mbed

main.cpp

Committer:
wd5gnr
Date:
2016-12-29
Revision:
1:126964580159
Parent:
0:3e6a4dfbcb88

File content as of revision 1:126964580159:

#include "mbed.h"
#include "mRotaryEncoder.h"

// Simple demo for Hackaday
// Al Williams

// This require two Keyes modules (or equivalent)
// A KY-040 rotary encoder is connected to D7, D8 and the switch to D2
// D8 connects to CLK and D7 connects to DT
// if the rotation is backwards switch the wiring or swap the definitions in 
// software

// There is also a KY-016 RGB LED with integrated resistors
// This board plugs in with the ground pin next to D13
// then the other pins naturally hit D13, D12, and D11

PwmOut blueled(D13);
PwmOut greenled(D12);
PwmOut redled(D11);

// RGB values for  LEDS
PwmOut *leds[]={&redled, &greenled, &blueled};
float rgb[]={0.0, 0,0, 0.0};
int sel=0;  // which component are we changing?

DigitalIn mybutton(USER_BUTTON);  // not used here

// Here's the encoder object
mRotaryEncoder enc(D7,D8, D2,PullNone);


// Helper function to set the PWM values
void setleds()
{
    for (int i=0;i<sizeof(leds)/sizeof(leds[0]);i++) leds[i]->write(rgb[i]);
}


// Library calls here when you go clockwise
void cw()
{
// modify the selected RGB component    
   rgb[sel]+=0.1;
   if (rgb[sel]>1.0) rgb[sel]=1.0;
   setleds();
}

// Library calls here when you go anticlockwise
void ccw()
{
// modify the selected RGB component    
   rgb[sel]-=0.1;
   if (rgb[sel]<0.0) rgb[sel]=0.0;
   setleds();
}

// Library calls here when you push in on the encoder shaft
void btn()
{
    // change selected component (0, 1, 2)
    if (++sel>2) sel=0;
}

int main() {
// Set up encoder callbacks
    enc.attachROTCW(cw);
    enc.attachROTCCW(ccw);
    enc.attachSW(btn);
    // set fast period
    redled.period(0.01);
    greenled.period(0.01);
    blueled.period(0.01);
    while (true);   // nothing else to do but wait
}