Class to control the chainable RGB LED light from Seeed Studios

Dependents:   Nucleo_read_button_interrupt_copy Seeed_Grove_4_Digit_Display_Clock

Revision:
0:fab321797d4b
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/SeeedChainableLED.h	Sun May 21 19:20:57 2017 +0000
@@ -0,0 +1,89 @@
+/**
+ * @file SeeedChainableLED.h
+ * @brief control the chainable LED module from Seeed Studios
+ * @author Nathan Yonkee
+ * @version 1.0
+ * @date 2017-04-20
+ */
+#ifndef SEEED_CHAINABLE_LED_H
+#define SEEED_CHAINABLE_LED_H
+#include "mbed.h"
+#include "DataClockPair.h"
+
+class SeeedChainableLED {
+  private:
+    DigitalOut datPin_;
+    DigitalOut clkPin_;
+    void start_cmd();
+    void stop_cmd();
+    void pin_delay(int delay_us = 6);
+    void send_byte(int byte);
+    void send_color(int r, int g, int b);
+  public:
+    void set_color_rgb(int r, int g, int b, int led = 0);
+    void clear_led();
+    void turn_on();
+    SeeedChainableLED (DataClockPair pins);
+};
+
+SeeedChainableLED::SeeedChainableLED(DataClockPair pins) : datPin_(pins.dataPin), clkPin_(pins.clockPin) {
+    clear_led();
+}
+
+void SeeedChainableLED::start_cmd() {
+    send_byte(0x00);
+    send_byte(0x00);
+    send_byte(0x00);
+    send_byte(0x00);
+}
+
+void SeeedChainableLED::stop_cmd() {
+    start_cmd();
+}
+
+void SeeedChainableLED::clear_led() {
+    set_color_rgb(0,0,0);
+}
+
+void SeeedChainableLED::turn_on() {
+    set_color_rgb(255,255,255);
+}
+
+void SeeedChainableLED::pin_delay(int delay_us) {
+    wait_us(delay_us);
+}
+
+void SeeedChainableLED::set_color_rgb(int r, int g, int b, int led) {
+    start_cmd();
+    send_color(r, g, b);
+    stop_cmd();
+}
+
+void SeeedChainableLED::send_color(int red, int green, int blue) {
+    // Start by sending a byte with the format "1 1 /B7 /B6 /G7 /G6 /R7 /R6"
+    int prefix = 0b11000000;
+    if ((blue & 0x80) == 0)     prefix|= 0b00100000;
+    if ((blue & 0x40) == 0)     prefix|= 0b00010000;
+    if ((green & 0x80) == 0)    prefix|= 0b00001000;
+    if ((green & 0x40) == 0)    prefix|= 0b00000100;
+    if ((red & 0x80) == 0)      prefix|= 0b00000010;
+    if ((red & 0x40) == 0)      prefix|= 0b00000001;
+    send_byte(prefix);
+    // Now send the 3 colors
+    send_byte(blue);
+    send_byte(green);
+    send_byte(red);
+}
+
+void SeeedChainableLED::send_byte(int byte) {
+    for (int i = 0; i < 8; i++) {
+        pin_delay();
+        datPin_ = byte & 0x80;
+        byte <<= 1;
+        clkPin_ = 0;
+        pin_delay();
+        clkPin_ = 1;
+    }
+}
+
+#endif