Skip navigation
2014

This time we have a sneak peak at the PI household to see their preparations for the BYOB Party

 

raspberry_pi_raspanimated.gif

 

Mr PI, not to be outdone by the young whipper-snapper Mr UNO Mrs Yun decided to have a crack at driving a couple of those fancy LED matrix panels from Adafruit, the idea being that messages can be posted to the iot.eclipse.org MQTT Broker and mr PI would subscribe to them and display the data (Messages) on the matrix display in glorious colour

 

Having all that extra memory allows the PI to calculate the patterns for much bigger displays but I was concerned that the timing may be an issue, after all, PI struggles even with a simple WS2812B neopixel.

 

Well as it happens I need not have been concerned, the timing on these boards is pretty straight forward and really only affects the refresh rate, not the actual clocking of the data to the display

 

The boards work a bit like a TV, well not quite but you'll see what I mean

these particular boards have two sets of serial data inputs, consisting of an R, G, B data line for each serial channel, a clock line to control the data feed and an Output enable / Latch to lock in the data and display on the LEDs

 

you clock as many pixels as there are in a row (up to 3 bytes per pixel) so 32 pixels = 92, 184 if you count both panels as the serial out from one feeds into the serial in of the next. The boards can be extended as far as needed, the cpu just needs to be able to clock out the data fast enough to keep up a decent refresh rate

 

there are 3 address lines permitting sending the RGB data to one of 8 LED rows (Remember there are two channels of RGB so we cover the 16 rows with 8 addresses and two serial streams), so the best refresh rate of a line is one in 8

 

if your using more than one board daisy chained then you simply clock out more data before firing the latch line

 

that's all there is to it basically.

 

So Adafruit has done an awesome job of creating a library to support these boards and you can download it from their site ( here: https://learn.adafruit.com/connecting-a-16x32-rgb-led-matrix-panel-to-a-raspberry-pi/overview

and part two where the topic adds additional boards in cascade https://learn.adafruit.com/16x32-rgb-display-with-raspberry-pi-part-2

 

there is a nice set of instructions on how to wire up the PI to the panels and plenty of sample code that can run the boards

 

raspberry_pi_wiring_diagram.png

 

Code is a C module and there is also Python samples

 

additional help can be found here https://github.com/Boomerific/rpi-rgb-led-matrix

 

there are a lot of wires used to connect the matrix panels but this is no different no matter the controller your using.

 

for example this is an easy to follow Python sample

import RPi.GPIO as GPIO
import time
 
delay = 0.000001
 
GPIO.setmode(GPIO.BCM)
red1_pin = 17
green1_pin = 18
blue1_pin = 22
red2_pin = 23
green2_pin = 24
blue2_pin = 25
clock_pin = 3
a_pin = 7
b_pin = 8
c_pin = 9
latch_pin = 4
oe_pin = 2
 
GPIO.setup(red1_pin, GPIO.OUT)
GPIO.setup(green1_pin, GPIO.OUT)
GPIO.setup(blue1_pin, GPIO.OUT)
GPIO.setup(red2_pin, GPIO.OUT)
GPIO.setup(green2_pin, GPIO.OUT)
GPIO.setup(blue2_pin, GPIO.OUT)
GPIO.setup(clock_pin, GPIO.OUT)
GPIO.setup(a_pin, GPIO.OUT)
GPIO.setup(b_pin, GPIO.OUT)
GPIO.setup(c_pin, GPIO.OUT)
GPIO.setup(latch_pin, GPIO.OUT)
GPIO.setup(oe_pin, GPIO.OUT)
 
screen = [[0 for x in xrange(32)] for x in xrange(16)]
 
def clock():
  GPIO.output(clock_pin, 1)
  GPIO.output(clock_pin, 0)
 
def latch():
  GPIO.output(latch_pin, 1)
  GPIO.output(latch_pin, 0)
 
def bits_from_int(x):
  a_bit = x & 1
  b_bit = x & 2
  c_bit = x & 4
   return (a_bit, b_bit, c_bit)
 
def set_row(row):
   #time.sleep(delay)
  a_bit, b_bit, c_bit = bits_from_int(row)
  GPIO.output(a_pin, a_bit)
  GPIO.output(b_pin, b_bit)
  GPIO.output(c_pin, c_bit)
   #time.sleep(delay)
 
def set_color_top(color):
   #time.sleep(delay)
  red, green, blue = bits_from_int(color)
  GPIO.output(red1_pin, red)
  GPIO.output(green1_pin, green)
  GPIO.output(blue1_pin, blue)
   #time.sleep(delay)
 
def set_color_bottom(color):
   #time.sleep(delay)
  red, green, blue = bits_from_int(color)
  GPIO.output(red2_pin, red)
  GPIO.output(green2_pin, green)
  GPIO.output(blue2_pin, blue)
   #time.sleep(delay)
 
def refresh():
   for row in range(8):
  GPIO.output(oe_pin, 1)
  set_color_top(0)
  set_row(row)
   #time.sleep(delay)
   for col in range(32):
  set_color_top(screen[row][col])
  set_color_bottom(screen[row+8][col])
  clock()
   #GPIO.output(oe_pin, 0)
  latch()
  GPIO.output(oe_pin, 0)
  time.sleep(delay)
 
def fill_rectangle(x1, y1, x2, y2, color):
   for x in range(x1, x2):
   for y in range(y1, y2):
  screen[y][x] = color
 
 
def set_pixel(x, y, color):
  screen[y][x] = color
 
fill_rectangle(0, 0, 12, 12, 1)
fill_rectangle(20, 4, 30, 15, 2)
fill_rectangle(15, 0, 19, 7, 7)
 
while True:
  refresh()



if you have not already updated or installed Python, now would be a good time

 

this is the code I used finally for the messages, it is a relatively

import os
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
 
text = (("Raspberry Pi ", (255, 0, 0)), ("and ", (0, 255, 0)), ("Adafruit", (0, 0, 255)))
 
 
font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 16)
all_text = ""
for text_color_pair in text:
  t = text_color_pair[0]
  all_text = all_text + t
 
print(all_text)
width, ignore = font.getsize(all_text)
print(width)
 
 
im = Image.new("RGB", (width + 30, 16), "black")
draw = ImageDraw.Draw(im)
 
x = 0;
for text_color_pair in text:
  t = text_color_pair[0]
  c = text_color_pair[1]
   print("t=" + t + " " + str(c) + " " + str(x))
  draw.text((x, 0), t, c, font=font)
  x = x + font.getsize(t)[0]
 
im.save("test.ppm")
 
os.system("./led-matrix 1 test.ppm")

easy task to change the message to one you like (Look for this line "text = (("Raspberry Pi ", (255, 0, 0)), ("and ", (0, 255, 0)), ("Adafruit", (0, 0, 255)))"  )

 

What I am planning to do is to have the PI subscribe to the elcipse mqtt broker with a specific topic "BreadBoard_Messages" and as messages are published, a modified version of the code will create the required image and then render and scroll it across the panels.

 

This will allow party messages or tweets to be received and shown during the BYOB  Party, My PI may not be able to interact too much but if he can pull this off it will be a great feat and useful in the future too

 

here is a short video demonstrating the PI driving a couple of the panels

 

in the next post I hope to have the code ready to read from the subscription data and render as an animated display in near real time

 

that's where I have challenged my son to help, integrate two sets of code into one great application

 

Ill be back with the results in a few days on this one

 

See you soon

The the Minions have been busy educating Trinket and as of now have indoctrinated him into the minion union,

 

This....Is....The....First....BIOMINIONOID.

 

Meet BOB

 

P1010353.JPG

 

Bob is new, he is improved, he is the first Bionic Minion, he is still a baby, Oh ya, he may be bigger than his buds but he has a long way to evolve but he is aware of his surroundings, and he is ready for the BYOB Party, the minions will keep him safe and under control so all is good

 

between the HR-S501 motion detector, the HC-SR04 ultrasonic sensor and those goggles, he is awesome

 

so what makes him tick

 

his heart, small as it may be has loads of power, an ATTINY 85 with 8K flash running at 16Mhz, a few IO pins and built in USB capability

 

as much as the minions tried, he only has a limited capacity and so only has a few tricks

 

He will wake up if he senses movement from over 20 feet away, he will wake up and look around with those wonderful green eyes of his

 

If you get within a couple of feet he will see you and put on a pretty light show, but dont be fooled, get too close and he may think your after his sucker and will shows his anger by turning his eyes RED, just back away and he will calm down, get out of sight and he will go back to sleep

 

there are only 8 pins on an ATTINY85 so here's how they where used:

2 pins for power

2 pins taken with the ultrasonic sensor

1 pin with the PIR

1 pin to drive the WS2812 LED strings in two circles of 16 (32 in total)

1 pin for reset

1 pin spare but coupled with the USB so not easy to use for anything

 

The minions could not educate Bob as much as they would like as they where exceeding his capacity but they did a pretty good job

 

here is the video

 

So the fun was to integrate the NEOPIXELS, the Ultrasonic Sensor and the PIR to the ATTINY85 but still be able to upload the code (The Trinket takes a couple of K to provide a boot loader via USB so this only leaves a little over 5K), It still has one pin available but with a 1.5K pullup, the PIR had a hard time grounding when using pin 3 it so I had to move to using pin 0. Pin 3 is available for perhaps a switch but there is no code space remaining given the current memory usage because of the boot loader.

 

At the end of the day I was able to squeeze everything in but at a reduced set of patterns on the neopixels, no room for even additional if statements.

 

here is the software (Attached for easy copying if so desired)

/*
NeoPixel Ring goggles sketch -- for steampunk, rave or Burning Man fashion!
Welding or costume goggles using 50mm round lenses can be outfitted with
a pair of Adafruit NeoPixel Rings: http://www.adafruit.com/product/1463


Please exercise common sense.  These goggles emit a LOT of stray light and
should NOT BE WORN ON YOUR EYES.  They're for fashion and costuming only,
for display on a hat or on your forehead.


Draws a spinning rainbow on both eyepieces.  Not a Mac beachball, honest.
"Eyes" glance around and blink at random.


For 'reflected' colors (rainbows rotate in opposite directions, while eyes
look in same direction), connect the output of the first ring to the input
of the second.  Or you can connect the inputs of both rings to the same
Arduino pin if that's easier -- the rainbows will both twirl in the same
direction in that case.


By default, pixel #0 (the first LED) on both rings should be at the TOP of
the goggles.  Looking at the BACK of the board, pixel #0 is immediately
clockwise from the OUT connection.  If a different pixel is at the top,
that's OK, the code can compensate (TOP_LED_FIRST and TOP_LED_SECOND below).


Modified by Peter Oakes to add a couple extra patterns, motion and range sensors
to trigger the wakeup of the rings and to to sleep with inactivity
*/


#include <Adafruit_NeoPixel.h>
#ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc.
  #include <avr/power.h>
#endif


#define PIN            4
#define PIR            0 // PIR input pin
#define trigPin        2 // UNLTRA Trigger pin
#define echoPin        1 // echo back pin


#define TOP_LED_FIRST  0 // Change these if the first pixel is not
#define TOP_LED_SECOND 0 // at the top of the first and/or second ring.


#define EFFECT         xECTO // Choose a visual effect from the names below


#define RAINBOW        0
#define ECTO           1


int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration = -1; // Duration used to calculate distance


Adafruit_NeoPixel pixels = Adafruit_NeoPixel(32, PIN, NEO_GRB + NEO_KHZ800);


const int8_t PROGMEM
  yCoord[] = { // Vertical coordinate of each pixel.  First pixel is at top.
    127,117,90,49,0,-49,-90,-117,-127,-117,-90,-49,0,49,90,117 },
  sine[] = { // Brightness table for ecto effect
    0, 28, 96, 164, 192, 164, 96, 28, 0, 28, 96, 164, 192, 164, 96, 28 };


// Eyelid vertical coordinates.  Eyes shut slightly below center.
#define upperLidTop     130
#define upperLidBottom  -45
#define lowerLidTop     -40
#define lowerLidBottom -130


// Gamma correction improves appearance of midrange colors
const uint8_t PROGMEM gamma8[] = {
      0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,
      0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  1,
      1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,
      3,  3,  4,  4,  4,  4,  5,  5,  5,  5,  5,  6,  6,  6,  6,  7,
      7,  7,  8,  8,  8,  9,  9,  9, 10, 10, 10, 11, 11, 11, 12, 12,
     13, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20,
     20, 21, 21, 22, 22, 23, 24, 24, 25, 25, 26, 27, 27, 28, 29, 29,
     30, 31, 31, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 41, 42,
     42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
     58, 59, 60, 61, 62, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 75,
     76, 77, 78, 80, 81, 82, 84, 85, 86, 88, 89, 90, 92, 93, 94, 96,
     97, 99,100,102,103,105,106,108,109,111,112,114,115,117,119,120,
    122,124,125,127,129,130,132,134,136,137,139,141,143,145,146,148,
    150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,
    182,184,186,188,191,193,195,197,199,202,204,206,209,211,213,215,
    218,220,223,225,227,230,232,235,237,240,242,245,247,250,252,255
};


uint32_t
  iColor[16][3];      // Background colors for eyes
int16_t
  hue          =   0; // Initial hue around perimeter (0-1535)
uint8_t
  iBrightness[16],    // Brightness map -- eye colors get scaled by these
  brightness   = 220, // Global brightness (0-255)
  blinkFrames  =   5, // Speed of current blink
  blinkCounter =  30, // Countdown to end of next blink
  eyePos       = 192, // Current 'resting' eye (pupil) position
  newEyePos    = 192, // Next eye position when in motion
  gazeCounter  =  75, // Countdown to next eye movement
  gazeFrames   =  50; // Duration of eye movement (smaller = faster)
int8_t eyeMotion    =   0; // Distance from prior to new position
boolean off = true;


void setup() {
#ifdef __AVR_ATtiny85__ // Trinket, Gemma, etc.
  if(F_CPU == 16000000) clock_prescale_set(clock_div_1);
  // Seed random number generator from an unused analog input:
  randomSeed(analogRead(2));
#else
  randomSeed(analogRead(A0));
#endif


pinMode(PIR, INPUT_PULLUP);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

pixels.begin();
}


void loop() {


  if(digitalRead(PIR) == 1)// wer are awake
  {
    doeffect();
    off = false;
  }
  else
  {
    if (off == false)
    {
      colorWipe(pixels.Color(0, 000, 0), 50); // Off as no one is watching
      off = true;
    }
  }
  delay(15);
}


void doeffect()
{
   uint8_t i, r, g, b, a, c, inner, outer, ep;
  int     y1, y2, y3, y4, h;
  int8_t  y;
  
  //is anyone near ?
rangecheck();


if (duration > 100 && duration < 1000)
{
  colorWipe(pixels.Color(255, 0, 0), 50); // Red eyes, back away
}
else if(duration > 1500 && duration < 2000)
{
  colorWipe(pixels.Color(0, 255, 255), 50);
  colorWipe(pixels.Color(255, 255, 0), 50);
  colorWipe(pixels.Color(255, 0, 255), 50);
  colorWipe(pixels.Color(0, 0, 255), 50);
}
else
{
   // A steampunk aesthetic might fare better with this more subdued effect.
  // Etherial green glow with just a little animation for visual spice.
  uint8_t i, r, g, b, a, c, inner, outer, ep;


  a = (hue >> 4) & 15;
  c =  hue       & 15;
  for(i=0; i<16; i++) {
    b = (a + 1) & 15;
    iColor[i][1] = 255; // Predominantly green
    iColor[i][0] = (pgm_read_byte(&sine[a]) * (16 - c) +
                    pgm_read_byte(&sine[b]) *       c  ) >> 4;
    iColor[i][2] = iColor[i][0] >> 1;
    a = b;
  }
  hue -= 3;
}


  // Render current blink (if any) into brightness map
  if(blinkCounter <= blinkFrames * 2) { // In mid-blink?
    if(blinkCounter > blinkFrames) {    // Eye closing
      outer = blinkFrames * 2 - blinkCounter;
      inner = outer + 1;
    } else {                            // Eye opening
      inner = blinkCounter;
      outer = inner - 1;
    }
    y1 = upperLidTop    - (upperLidTop - upperLidBottom) * outer / blinkFrames;
    y2 = upperLidTop    - (upperLidTop - upperLidBottom) * inner / blinkFrames;
    y3 = lowerLidBottom + (lowerLidTop - lowerLidBottom) * inner / blinkFrames;
    y4 = lowerLidBottom + (lowerLidTop - lowerLidBottom) * outer / blinkFrames;
    for(i=0; i<16; i++) {
      y = pgm_read_byte(&yCoord[i]);
      if(y > y1) {        // Above top lid
        iBrightness[i] = 0;
      } else if(y > y2) { // Blur edge of top lid in motion
        iBrightness[i] = brightness * (y1 - y) / (y1 - y2);
      } else if(y > y3) { // In eye
        iBrightness[i] = brightness;
      } else if(y > y4) { // Blur edge of bottom lid in motion
        iBrightness[i] = brightness * (y - y4) / (y3 - y4);
      } else {            // Below bottom lid
        iBrightness[i] = 0;
      }
    }
  } else { // Not in blink -- set all 'on'
    memset(iBrightness, brightness, sizeof(iBrightness));
  }


  if(--blinkCounter == 0) { // Init next blink?
    blinkFrames  = random(4, 8);
    blinkCounter = blinkFrames * 2 + random(5, 180);
  }


  // Calculate current eye movement, possibly init next one
  if(--gazeCounter <= gazeFrames) { // Is pupil in motion?
    ep = newEyePos - eyeMotion * gazeCounter / gazeFrames; // Current pos.
    if(gazeCounter == 0) {                   // Last frame?
      eyePos      = newEyePos;               // Current position = new pos
      newEyePos   = random(16) * 16;         // New pos. (always pixel center)
      eyeMotion   = newEyePos - eyePos;      // Distance to move
      gazeFrames  = random(10, 20);          // Duration of movement
      gazeCounter = random(gazeFrames, 130); // Count to END of next movement
    }
  } else ep = eyePos; // Not moving -- fixed gaze


//  // Draw pupil -- 2 pixels wide, but sup-pixel positioning may span 3.
//  a = ep >> 4;         // First candidate
//  b = (a + 1)  & 0x0F; // 1 pixel CCW of a
//  c = (a + 2)  & 0x0F; // 2 pixels CCW of a
//  i = ep & 0x0F;       // Fraction of 'c' covered (0-15)
//  iBrightness[a] = (iBrightness[a] *       i ) >> 4;
//  iBrightness[b] = 0;
//  iBrightness[c] = (iBrightness[c] * (16 - i)) >> 4;


  // Merge iColor with iBrightness, issue to NeoPixels
  for(i=0; i<16; i++) {
    a = iBrightness[i] + 1;
    // First eye
    r = iColor[i][0];            // Initial background RGB color
    g = iColor[i][1];
    b = iColor[i][2];
    if(a) {
      r = (r * a) >> 8;          // Scale by brightness map
      g = (g * a) >> 8;
      b = (b * a) >> 8;
    }
    pixels.setPixelColor(((i + TOP_LED_FIRST) & 15),
      pgm_read_byte(&gamma8[r]), // Gamma correct and set pixel
      pgm_read_byte(&gamma8[g]),
      pgm_read_byte(&gamma8[b]));


    // Second eye uses the same colors, but reflected horizontally.
    // The same brightness map is used, but not reflected (same left/right)
    r = iColor[15 - i][0];
    g = iColor[15 - i][1];
    b = iColor[15 - i][2];
    if(a) {
      r = (r * a) >> 8;
      g = (g * a) >> 8;
      b = (b * a) >> 8;
    }
    pixels.setPixelColor(16 + ((i + TOP_LED_SECOND) & 15),
      pgm_read_byte(&gamma8[r]),
      pgm_read_byte(&gamma8[g]),
      pgm_read_byte(&gamma8[b]));
  }
  pixels.show();
}


// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<pixels.numPixels(); i++) {
      pixels.setPixelColor(i, c);
      pixels.show();
      delay(wait);
  }
}






//void rainbow1(uint8_t wait) {
//  uint16_t i, j;
//
//  for(j=0; j<256; j++) {
//    for(i=0; i<pixels.numPixels(); i++) {
//      pixels.setPixelColor(i, Wheel((i+j) & 255));
//    }
//    pixels.show();
//    delay(wait);
//  }
//}


//// Slightly different, this makes the rainbow equally distributed throughout
//void rainbowCycle(uint8_t wait) {
//  uint16_t i, j;
//
//  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
//    for(i=0; i< pixels.numPixels(); i++) {
//      pixels.setPixelColor(i, Wheel(((i * 256 / pixels.numPixels()) + j) & 255));
//    }
//    pixels.show();
//    delay(wait);
//  }
//}
//// Input a value 0 to 255 to get a color value.
//// The colours are a transition r - g - b - back to r.
//uint32_t Wheel(byte WheelPos) {
//  if(WheelPos < 85) {
//   return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
//  } else if(WheelPos < 170) {
//   WheelPos -= 85;
//   return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3);
//  } else {
//   WheelPos -= 170;
//   return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3);
//  }
//}
void rangecheck()
{
/* The following trigPin/echoPin cycle is used to determine the
distance of the nearest object by bouncing soundwaves off of it. */
digitalWrite(trigPin, LOW);
//delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
//delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
/* Send a negative number to computer and Turn LED ON
to indicate "out of range" */
}

 

The making of BOB was left to my Daughter Jessica, here is her log of the process.

 

This is what we’re making, minus the digital stuff.

Cut out and iron together two layers of interfacing, one for each eye (substitute with paper if you like).

Glue to the inside of two Mason jar lid rims.

Place on a square of yellow felt. Center goggle pieces and cut out 2 grey felt goggle straps. Place.

Cut out outlines of your electronic pieces and trace onto the board with iron off marker.

To start the diaper, cut a big piece for the back, rounded at the bottom corners.

Cut out a thinner layer for the front overlap section. Glue that one on top.

Cut little safety pins out of grey fabric; 2 half circles and two long rectangles, half circles on top.

Cut safety pins in half and glue them on.

(Yes these are inaccurate, shush ;P only cut one side in half to be accurate)

Trace the outline of your baby onto a board, measure in a half-inch, round off the top and cut it out.

Fold the edge of the felt over the board (only the lower half, so you can insert electronics) and glue on.

Cut holes through board for whatever pieces require it,

(Mine needed 2 wire holes and the nose and mouth pieces)

Insert the gadgets and glue down.

Finish glueing on the eyes, the goggles, and fold over the rest of the felt edges.

 

And your done, aside from software and power, see video and above for all that stuff

 

Happy new year, Jessica Oakes



The Internet of Holiday Lights

(The Santa monitor & lights -  part-2)




    Hello again folks and Mary Christmas to you all! In this part i'm going to speed up things a little bit and go to the second stage of the challenge and build the first objective - windows and aquarium/vibe lamp lights. So far i've tested and installed almost 5m of RGB strip with one Arduino UNO + one Infineon RGB shield with the Dave's examples on I2C protocol (with a bit of tweaking on the delays and maximum light values) on my window.


IMG_0008.JPG


This is the Dave's code for arduino UNO and Infineon RGB shield with minor tweaks from line 170 to 199 to work with simple RGB and get 6 colours:


  // Infineon RGB_LED_Shield_Master_Tester
  // by Michelle Chia


  // Demonstrates I2C communication with the RGB LED Shield for safe configuration. Tested at 48Vin, 6V forward voltage LED. LED current up to 350mA.
  // Modified 13 August 2013

  #define ADDRESS                    0x15EUL

  #define INTENSITY_RED              0x11U
  #define INTENSITY_GREEN            0x12U
  #define INTENSITY_BLUE    0x13U
  #define INTENSITY_RGB              0x14U
  #define CURRENT_RED                0x21U
  #define CURRENT_GREEN              0x22U
  #define CURRENT_BLUE              0x23U
  #define CURRENT_RGB                0x24U
  #define DMXOFF    0x30U
  #define DMXON                0x31U
  #define DMXSLOT    0x32U
  #define DMX8BIT                    0x33U
  #define DMX16BIT                  0x34U
  #define OFFTIME_RED                0x41U
  #define OFFTIME_GREEN              0x42U
  #define OFFTIME_BLUE    0x43U
  #define WALKTIME                  0x50U
  #define DIMMINGLEVEL              0x60U
  #define FADERATE                  0x61U
  #define _CHANGE_ADDRESS            0x70U

  #define READ_INTENSITY_RED        0x81U
  #define READ_INTENSITY_GREEN      0x82U
  #define READ_INTENSITY_BLUE        0x83U
  #define READ_CURRENT_RED          0x84U
  #define READ_CURRENT_GREEN        0x85U
  #define READ_CURRENT_BLUE          0x86U
  #define READ_OFFTIME_RED          0x87U
  #define READ_OFFTIME_GREEN        0x88U
  #define READ_OFFTIME_BLUE          0x89U
  #define READ_WALKTIME              0x8AU
  #define READ_DIMMINGLEVEL          0x8BU
  #define READ_FADERATE              0x8CU
  #define DIRECTACCESS_READ          0x90U // read twice
  #define DIRECTACCESS_MOVE      0x91U
  #define DIRECTACCESS_AND          0x92U
  #define DIRECTACCESS_OR            0x93U

  #define SAVEPARAMETERS            0xA0U

  #define BCCUMODID                  0x50030008U
  #define CHIPID                    0x40010004U
  #define REDINTS                    0x500300A0U // BCCU_CH5
  #define REDINT                    0x500300A4U
  #define BLUEINTS                  0x50030078U
  #define STARTWALK                  0x50030018U

  #include <Wire.h>

  unsigned int c[2] = {0};
  unsigned int d[4] = {0};
  unsigned int on = 0;
  unsigned int message = 0;
  unsigned long redcurr = 0;
  unsigned long greencurr = 0;
  unsigned long bluecurr = 0;
  unsigned long redoff = 0;
  unsigned long greenoff = 0;
  unsigned long blueoff = 0;
  unsigned long redint = 0x00;
  unsigned long greenint = 0x00;
  unsigned long blueint = 0x00;
  unsigned long fadetime = 0x00;
  unsigned long walk = 0x00;
  unsigned long brightness = 1;

  void setup() {


    Serial.begin(9600);
    Wire.begin();

    while (on != 1) // Wait for shield to respond
    {
      I2CDMX (ADDRESS, DMXOFF); // disable DMX
      I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Immediate fade
      I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // 0% brightness level
      on = I2CREAD(ADDRESS, READ_DIMMINGLEVEL); // Request for brightness level
      if (message == 1 && on == 0) // If message received and brightness level = 9%
      {
        message = 0;
        on = 1; // break out of loop
      }
    }

    while (redcurr != 0x15 || greencurr != 0x15 || bluecurr != 0x15 || redoff != 0x38 || greenoff != 0x39 || blueoff != 0x38 || brightness != 0)
    {
        I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0000, 0x000, 0x0000); // Off Light
  // Ensure that parameters are set up correctly. Read back and check. If wrong, write and read again.
        redcurr = I2CREAD (ADDRESS, READ_CURRENT_RED); // Read the red current intensity
  greencurr = I2CREAD (ADDRESS, READ_CURRENT_GREEN); // Read the green current intensity
  bluecurr = I2CREAD (ADDRESS, READ_CURRENT_BLUE); // Read the blue current intensity
  redoff = I2CREAD (ADDRESS, READ_OFFTIME_RED); // Read the off-time of the red channel
  greenoff = I2CREAD (ADDRESS, READ_OFFTIME_GREEN); // Read the off-time of the green channel
  blueoff = I2CREAD (ADDRESS, READ_OFFTIME_BLUE); // Read the off-time of the blue channel
  brightness = I2CREAD (ADDRESS, READ_DIMMINGLEVEL); // Read the dimming level

        I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
  I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x39); // Set off-time of green channel to 0x39
  I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
  I2CWRITE2BYTES (ADDRESS, CURRENT_RED, 0x15); // Set current intensity of red channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_GREEN, 0x15); // Set current intensity of green channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_BLUE, 0x15); // Set current intensity of blue channel to 0x15
  I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000);
    }

    delay(100);
    I2CWRITE2BYTES (ADDRESS, FADERATE, 0x1023); // Fade Rate --> 0.7s
    I2CWRITE2BYTES (ADDRESS, WALKTIME, 0x000F);
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0555, 0x0555, 0x0555); // White Light
    I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0FFF); // Maximum Brightness


    delay(2000); // wait 2 sec
    // change lamp colour to red
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0FFF); // change red colour intensity to 0xFFF
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000); // change green colour intensity to 0x000
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); // change blue colour intensity to 0x000
    delay(1000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0FFF);
    delay(1000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0FFF);

    delay(1000); // Read back values from slave
    Serial.print("Red Int: ");
    redint = I2CREAD (ADDRESS, READ_INTENSITY_RED); // request from shield red colour intensity
    Serial.print("Green Int: ");
    greenint = I2CREAD (ADDRESS, READ_INTENSITY_GREEN); // request from shield green colour intensity
    Serial.print("Blue Int: ");
    blueint = I2CREAD (ADDRESS, READ_INTENSITY_BLUE); // request from shield blue colour intensity
    Serial.print("Red Curr: ");
    redcurr = I2CREAD (ADDRESS, READ_CURRENT_RED); // request from shield peak current reference of red channel
    Serial.print("Green Curr ");
    greencurr = I2CREAD (ADDRESS, READ_CURRENT_GREEN); // request from shield peak current reference of green channel
    Serial.print("Blue Curr: ");
    bluecurr = I2CREAD (ADDRESS, READ_CURRENT_BLUE); // request from shield peak current reference of blue channel
    Serial.print("Red PWM: ");
    redoff = I2CREAD (ADDRESS, READ_OFFTIME_RED); // request from shield off-time of red channel
    Serial.print("Green PWM: ");
    greenoff = I2CREAD (ADDRESS, READ_OFFTIME_GREEN); // request from shield off-time of green channel
    Serial.print("Blue PWM: ");
    blueoff = I2CREAD (ADDRESS, READ_OFFTIME_BLUE); // request from shield off-time of blue channel
    Serial.print("Walk: ");
    walk = I2CREAD (ADDRESS, READ_WALKTIME); // request from shield walk-time
    Serial.print("Brightness: ");
    brightness = I2CREAD (ADDRESS, READ_DIMMINGLEVEL); // request from shield brightness level
    Serial.print("FadeTime: ");
    fadetime = I2CREAD (ADDRESS, READ_FADERATE); // request from shield fade rate
    I2CWRITE2BYTES (ADDRESS, WALKTIME, 48); // set walk-time 480ms



  }

  // the loop routine runs over and over again forever with pairs of colours
  void loop() {

    // change lamp colour: red blue green cyan purple and yellow
//MAGENTA
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0FFF);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0FFF);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000)
    delay(3000);
//CYAN
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000);  // RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0FFF); //BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0FFF);//GREEN
    delay(3000);
//YELLOW
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0FFF);  // RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); //BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0FFF);//GREEN
    delay(3000);
//RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0FFF);  // RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); //BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000);//GREEN
    delay(3000);
//BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000);  // RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0FFF); //BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000);//GREEN
    delay(3000);
//GREEN
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000);  // RED
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); //BLUE
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0FFF);//GREEN
    delay(3000);








  }
/*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - Defined I2C Commands i.e. INTENSITY_RED, INTENSITY_GREEN, INTENSITY_BLUE
                  unsigned int Data - 16bit data to be written to slave
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 2 bytes of word to the I2C bus line
  */

  void I2CWRITE2BYTES (int Address, int Command, unsigned int Data)
  {
    unsigned int upperByte, lowerByte; // Separate 4 byte data into 2 byte values
    lowerByte = Data;
    upperByte = Data >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // Putting address into correct format
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD)); // Start I2C transmission
    Wire.write(byte(lowerSLAD)); // address lower 8 bits of i2c address
    Wire.write(byte(Command)); // write command
    Wire.write(byte(upperByte)); // write data
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);

  }
  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - Defined I2C Commands i.e. INTENSITY_RGB, CURRENT_RGB
                  unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree - Three 16bit data to be written to slave
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 6 bytes of word to the I2C bus line
  */

  void I2CWRITE6BYTES (unsigned int Address, unsigned int Command, unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree) // DataOne: Red, DataTwo: Green, DataThree: Blue
  {
    unsigned int upperByte, lowerByte; // Split each Data parameter into upper and lower 8 bytes because I2C format sends 8 bytes of data each time
    lowerByte = DataOne;
    upperByte = DataOne >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    lowerByte = DataTwo;
    upperByte = DataTwo >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    lowerByte = DataThree;
    upperByte = DataThree >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);

  }

/*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - Defined I2C Commands i.e. DMX16Bit
                  unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree, usigned int DataFour, unsigned int DataFive - Three 16bit data to be written to slave
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 12 bytes of word to the I2C bus line
  */

  void I2CWRITE12BYTES (unsigned int Address, unsigned int Command, unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree, unsigned int DataFour, unsigned int DataFive, unsigned int DataSix) // DataOne: Red, DataTwo: Green, DataThree: Blue
  {
    unsigned int upperByte, lowerByte;
    lowerByte = DataOne;
    upperByte = DataOne >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command)); // write command
    Wire.write(byte(upperByte)); // write 2 bytes
    Wire.write(byte(lowerByte));

    lowerByte = DataTwo;
    upperByte = DataTwo >> 8;
    Wire.write(byte(upperByte)); // write next two bytes
    Wire.write(byte(lowerByte));

    lowerByte = DataThree;
    upperByte = DataThree >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataFour;
    upperByte = DataFour >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataFive;
    upperByte = DataFive >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataSix;
    upperByte = DataSix >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);

  }

  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - Defined read I2C Commands i.e. READ_INTENSITY_RED, READ_INTENSITY_GREEN, READ_INTENSITY_BLUE
  Parameters (OUT): None
  Return Value: Requested data from Shield will be sent back
  Description: This function will request 2 bytes of word from the shield
  */

  unsigned int I2CREAD (unsigned int Address, unsigned int Command) // Returns data sent by slave
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.requestFrom(upperSLAD, 2, true);
    unsigned int data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      message = 1;
      c[i] = Wire.read(); // receive a byte as character
      i++;

    }
    Wire.endTransmission(true);

    data = c[1]; // write data to serial monitor. c[1] is higher byte
    data = (data << 8) | c[0];  // shift left and combine with lower byte
    Serial.print("0x");
    if (data < 0x1000)
        Serial.print("0");
    Serial.println(data, HEX);
    return data;
  }

  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - DIRECTACCESS_READ
  Parameters (OUT): None
  Return Value: Requested data from the Shield will be returned
  Description: This function will request 4 bytes of data from shield.
  */

unsigned long I2CREAD_DIRECTACCESS (unsigned int Address, unsigned int Command, unsigned long registerAddress)
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // sending command + address
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));

    unsigned int firstByte, secondByte, thirdByte, fourthByte;
    firstByte = registerAddress >> 24; // top byte
    secondByte = registerAddress >> 16;
    thirdByte = registerAddress >> 8;
    fourthByte = registerAddress; // bottom byte

    Wire.write(byte(firstByte));
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));

    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD)); // request for read
    Wire.write(byte(lowerSLAD));
    Wire.requestFrom(upperSLAD, 4, true);
    unsigned long data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      d[i] = 0;
      d[i] = Wire.read(); // receive a byte as character
      i++;
    }


    Wire.endTransmission(true);

    data = d[3]; // combining into one variable. Highest byte received first
    data = (data << 8) | d[2];
    data = (data << 8) | d[1];
    data = (data << 8) | d[0];
    Serial.print("0x");
    if (data < 0x10000000)
        Serial.print("0");
    Serial.println(data, HEX);
    return data;
  }
  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  int Command - Defined I2C Commands i.e. DIRECTACCESS_OR, DIRECTACCESS_AND, DIRECTACCESS_MOVE
                  unsigned long registerAddress - address of target register
                  unsigned long Data - 32 bits data to be written to register
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 4 bytes of data to specified register
  */
  void I2CWRITE_DIRECTACCESS (unsigned int Address, unsigned int Command, unsigned long registerAddress, unsigned long Data) // For accessing registers directly
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // sending command + address
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));

    unsigned int firstByte, secondByte, thirdByte, fourthByte; // Send address of register first
    firstByte = registerAddress >> 24; // top byte
    secondByte = registerAddress >> 16;
    thirdByte = registerAddress >> 8;
    fourthByte = registerAddress; // bottom byte

    Wire.write(byte(firstByte));
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));

    firstByte = Data >> 24; // top byte
    secondByte = Data >> 16;
    thirdByte = Data >> 8;
    fourthByte = Data; // bottom byte


    Wire.write(byte(firstByte)); // send 4 bytes of data
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));
    Wire.endTransmission(true);

  }
  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  unsigned int newAddress - Address the shield should change to
  Parameters (OUT): None
  Return Value: None
  Description: This function will change the I2C address of the slave
  */

  void CHANGEADDRESS (unsigned int Address, unsigned int newAddress)
  {
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(0x70)); // Command to change address
    lowerSLAD = (unsigned int) (newAddress & 0x00FF);
    upperSLAD = newAddress >> 7; // Split address into 2 bytes
    upperSLAD |= 0xF0; // 10 bit addressing: First 5 bits have to be 11110.
    upperSLAD &= 0xFE;
    Wire.write(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.endTransmission(true);
  }

  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                  unsigned int Command - DMXON, DMXOFF
  Parameters (OUT): None
  Return Value: None
  Description: This function will enable or disable DMX512 control on shield
  */

  void I2CDMX (unsigned int Address, unsigned int Command) // Switch off / on the DMX
  {
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // Putting address into correct format
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD)); // Start I2C transmission
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.endTransmission(true);

  }
  /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
  Parameters (OUT): None
  Return Value: None
  Description: This function will request the shield to save configurations to flash memory
  */

  void I2CSAVEPARAM (unsigned int Address)
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(SAVEPARAMETERS)); // write SAVEPARAMETERS command
    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD)); // write to address lower 8 bits of slave address
    Wire.requestFrom(upperSLAD, 2, true);  // send READ request with upper slave address
    unsigned int data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      message = 1;
      c[i] = Wire.read(); // receive a byte as character
      i++;
    }
    Wire.endTransmission(true); // STOP condition

    data = c[1]; // print the data on serial monitor
    data = (data << 8) | c[0];
    Serial.print("0x");
    if (data < 0x1000)
        Serial.print("0");
    Serial.println(data, HEX);

  }

































    In the first part i've presented to you, Arduino YUN + Infineon RGB shield and MQTT server library, for a remote manual control of an application, with a javascript html application developed by kartben.


Controlling Holiday Lights using MQTT and the Arduino Yún and Infineon RGB shield

 

      Now i have an automated lighted window and still working on a lighted lamp too (ah wires all over ). By tweaking, you can obtain combination of colours and timings, from a simple RGB led strip (obtained 6 colours in total : base colours > red, blue, green and combined colours > cyan, magenta and yellow from combining each two colours from the first three).


4-3.png

    The third and hopefully final stage, will represent the sensor array and the music conditioned by them. The "hohoho" sounds on a proximity sensor, and the "chillout carol" sounds if it snows. Stay tuned till then...i'll be back shortly with interesting feeds. Till then, here's a demo of the second part with only 3 colours:

 

View from inside:


P.S. - oh yeah, and flowers .


View from outside:


...and a dog .


Please enjoy!






Coming soon: The Santa monitor & lights - (T.I.O.H.L.)part-3

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.

In the fourth post I used the Linux part of the Yun to get at the current date and time.

In the fifth post I scavenged a stepper motor from a flatbed scanner.

In post six that motor was running.

Post seven is covering the Infineon RGB LED shield.

My post number eight is an aside on programming the advent calendar logic.

In post nine I'm covering the creative 'Arts & Crafts" part.


This time I'll cover Time and Event handling.


Why Time management


My wreath will be doing several things. A few of them event handled, other repetitive.

  • There are some animations happening (LEDs dimming and flashing)
  • A connection with the Eclipse MQTT broker needs to be kept alive.
  • I'm sending MQTT messages to something for surprise functionality on a regular base.
  • Others.

 

I can handle all of this in the loop() function without real issues (it's not that complex after all). But a timer can handle all of this without me having to worry about it too much.

The ATMega has spare timers, so why not.

 

In my design I need three granularities:

  • things to be done approx each second
  • actions that should be done each minute
  • hourly activities

 

timeandevent0001.jpg

 

So I've set up a counter that ticks every second and manages the cadence.

void timerInit() {
  // initialize timer1 for 1 second ticks; ISR(TIMER1_COMPA_vect) will be called as interrupt handler
  noInterrupts();           // disable all interrupts
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;


  OCR1A = 62500;            // compare match register 16MHz/256/1Hz
  TCCR1B |= (1 << WGM12);   // CTC mode
  TCCR1B |= (1 << CS12);    // 256 prescaler
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
  interrupts();             // enable all interrupts
}




 

 

My interrupt handler does nothing more than marking what jobs need to execute:

ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  static unsigned int uSeconds = 0;
  uSeconds++; // every call is a second
  bRunSeconds = true; // so yes, flag that the seconds handler should be called
  bRunMinutes = ! (uSeconds % 60); // each 60th second, flag that the minutes handler should be called
  if (uSeconds > 3599) { // every hour
    bRunHours = true; // flag that the hours handler should be called
    uSeconds = 0; // and start over
  }
}




This is a very short routine that is guaranteed to give back control to non-interrupt code fast

 

I have a function that calls the right schedule at the right times. That function is the first call in my 'arduino sketch' loop():

void loop()
{

  timerTasks();

  // non timer related functionality comes here
  // ...




 

void timerTasks() {
  if (bRunSeconds && ! bIsRunningSeconds) { // timer interrupt flagged that seconds handler should be called
    runSeconds(); // but we only run it if it's not active
  }
  if (bRunMinutes && ! bIsRunningMinutes) { // timer interrupt flagged that minutes handler should be called
    runMinutes(); // but we only run it if it's not active
  }
  if (bRunHours && ! bIsRunningHours) { // timer interrupt flagged that hours handler should be called
    runHours(); // but we only run it if it's not active
  }
}




 

As an example, here's some household variables, runSeconds() and the beginning of runMinutes():

boolean bRunSeconds = false;
boolean bIsRunningSeconds = false;
boolean bRunMinutes = false;
boolean bIsRunningMinutes = false;
boolean bRunHours = false;
boolean bIsRunningHours = false;


void runSeconds() {
  bIsRunningSeconds = true;

  Serial.print("s"); // remove when confident


  // task: keep MQTT alive
  client.yield(30); // this takes 30 ms. May reduce the parameter // if you get duplicates, increase

// surprise functionality removed

  bRunSeconds = false;
  bIsRunningSeconds = false;
}


void runMinutes() {
  bIsRunningMinutes = true;

  Serial.println("m"); // remove when confident

  // ..




 

Why Event management


MQTT is event driven for the receiving side. You subscribe to a message, and provide the callback function that will be invoked upon incoming messages.

That is currently the only (non-interrupt) event driven scenario in my design.

 

timeandevent0002.jpg

Here's my handler. Some functionality that I'll reveal later is removed.

 

void messageArrived(MQTT::MessageData& md) // this handler is called when a subscribed MQTT message arrives
{
  MQTT::Message &message = md.message;

  // debug code
  sprintf(printbuf, "Message arrived: qos %d, retained %d, dup %d, packetid %d\n",
  message.qos, message.retained, message.dup, message.id);
  Serial.print(printbuf);
  sprintf(printbuf, "Payload %s\n", (char*)message.payload);
  Serial.print(printbuf);
  // end debug code



  // in the real world, I should validate if this is the right topic -- I've only subscribed to one so I'll not bother

  // here be secret codes for surprise functionality

}




 

Other candidates?


I may add an interrupt handler for a button that I plan to use, but since that is only to be used in calibration scenario's, I may just handle that in my loop(). I'm not in the mood to pull out my debounce lib.

I would go full-fledged if I had a keyboard or an end-user button interface. But that's not the case, so a simple check of the pin state in my loop will do.

 

update: execution log of one hour operation

invoking linux date
linux date invoked
20141231


20141231
day: 20141231 checking against: 20141130 checking against: 20141201 checking against: 20141202 checking against: 20141203 checking against: 20141204 checking against: 20141205 checking against: 20141206 checking against: 20141207 checking against: 20141208 checking against: 20141209 checking against: 20141210 checking against: 20141211 checking against: 20141212 checking against: 20141213 checking against: 20141214 checking against: 20141215 checking against: 20141216 checking against: 20141217 checking against: 20141218 checking against: 20141219 checking against: 20141220 checking against: 20141221 checking against: 20141222 checking against: 20141223 checking against: 20141224 checking against: 20141225 checking against: 20141226 checking against: 20141227 checking against: 20141228 checking against: 20141229 checking against: 20141230 checking against: 20141231 found state : 22
0
...
0
Payload secret
119
...
116
motor adjust in seconds: 9
115
motor adjust in seconds: 9
114
motor adjust in seconds: 9
113
motor adjust in seconds: 9
112
motor adjust in seconds: 8
111
motor adjust in seconds: 7
110
motor adjust in seconds: 6
109
motor adjust in seconds: 5
108
motor adjust in seconds: 4
107
motor adjust in seconds: 3
106
motor adjust in seconds: 2
105
motor adjust in seconds: 1
104
motor adjust in seconds: 0
103
motor adjust to advent state
102
...
65
m
64
...
6
5
m
4
3
2
1
0
0
...
0
Payload secret
119
...
106
motor adjust in seconds: 9
105
motor adjust in seconds: 8
104
motor adjust in seconds: 7
103
motor adjust in seconds: 6
102
motor adjust in seconds: 5
101
motor adjust in seconds: 4
100
motor adjust in seconds: 3
99
motor adjust in seconds: 2
98
motor adjust in seconds: 1
97
motor adjust in seconds: 0
96
motor adjust to advent state
95
m
94
93
...
36
35
m
34
33
...
4
3
2
1
0
0
...
0
0
m
0
...
0
m
h
invoking linux date
linux date invoked
20141231


20141231
day: 20141231 checking against: 20141130 checking against: 20141201 checking against: 20141202 checking against: 20141203 checking against: 20141204 checking against: 20141205 checking against: 20141206 checking against: 20141207 checking against: 20141208 checking against: 20141209 checking against: 20141210 checking against: 20141211 checking against: 20141212 checking against: 20141213 checking against: 20141214 checking against: 20141215 checking against: 20141216 checking against: 20141217 checking against: 20141218 checking against: 20141219 checking against: 20141220 checking against: 20141221 checking against: 20141222 checking against: 20141223 checking against: 20141224 checking against: 20141225 checking against: 20141226 checking against: 20141227 checking against: 20141228 checking against: 20141229 checking against: 20141230 checking against: 20141231 found state : 22
0
0
...


 

 

 

 

 


Link to previous posts

 

Preface

 

My project for the Internet of Holoday lights was based around our living room which was not very livable. It was a mess and with the upcoming holidays I wanted to set the living room in such a way that it would be suitable for entertaining guests. Additionally I wanted to accomplish the above mentioned in such a way that the holiday lighting becomes part of the living room and I don't need to remove it after the holidays. Hence the concept of Dynamic Living-room Lighting.

 

In the previous posts, I have review the YUN and the infineon shield and have presented an overview of the project system.

 

For this post, I explain how I setup the living room stage from scratch.

 

What was

 

The image below show what the living room looked like when I had applied for the roadtest plus. It had a lot of work to be done and we were missing some bits and pieces. I had planned it but executing the plan was a lot harder than I thought.

 

2014-12-04 16.36.42.jpg

 

And so be begin

 

As you can see there are a lot of unwanted elements that would not be very 'welcoming' and hence the first thing was to dispose of the additional bit. The wooden TV stand and messy corner needs to be cleaned hence I started by removing everything.

 

IMG_20141220_151038.jpg

The wall seems pretty dull and gloomy and the whole thing wont work with just lights. We need a better setting so I went out to look for something to make things better. I found PVC sheets that can be used for the wall and I could fit them pretty easily. No paint or anything necessary hence me and my wife took a day out to set them up. We also bought a tree and I order a wooden wall mounting rack which I setup on the wall. My better half decided to demonstrate her skills with Styrofoam and cardboard to fabricate a fireplace.

a.jpg

 

The result was mocked up in the cold of the night as...

 

b.jpg

 

It looks better but we want it to be a lot better. My wife put some thought into it and...

IMG_9194.jpg IMG_9210.jpg

 

output_4ja5gI.gif

 

We setup everything but the christmas tree was a bit empty. I bought some decorations and we made some our own as well. Since we are minion themed hence it seemed fit to make our minion ornaments.

 

20141222_212601.jpg

 

 

 

 

The minions ornaments were made by hand my my wife as seen in the above image and the final result is...

 

IMG_9261.jpg

and..

 

IMG_9263.jpg

 

With that the stage is set and ready for the electronics side... In the next post I will detail the making of the electronics for the tree.

 

IMG_9233.jpg

 

Documentation is taking a lot more time than I thought but I will try and document as much as possible so that you can setup things at your end as well.

 

Cheers,

IP

Slowly working away on my Arduino learning and project for the Internet of Holiday Things RoadTest. Running into some issues on the most basic learning steps such as making an LCD screen work. Maybe you have some suggestions?

 

I got this LM041 datasheet & application note - Datasheet Archive from peteroakes . It's sturdy built 16x4 display that seems to have weathered the ages quite well.

 

I went and bought a 10k ohm potentiometer and hooked everything up per the Arduino LCD Tutorial but I don't appear to be having much luck.

 

The thing that frustrates me most is that one of my past configurations did get my Hello World running but I managed to do something that removed it.

 

I am using the standard LiquidCrystal library and running example code such as AutoScroll and HelloWorld. As I write this I am cycling through the rest of the example codes and still seeing a lot of Greek letters.

 

One of the sketches causes  my text to come out in a jumble of Greek and Latin characters.

 

This sketch caused my text to display mostly Japanese!

 

I am currently trouble shooting this problem by removing different D Pins and seeing what happens.

 

All pins in is currently rotating the following characters: #, 3, C, S, c, s. This corresponds to the top 4 bits of the combination 0xxx, and the bottom 4 bits always being 0011.

 

All pins in

 

Removing DB7 and putting DB6 into Pin 2 is currently rotating the Japanese characters shown below. This corresponds to the top 4 bits with combination 1xxx, and the bottom 4 bits always being 1011. Note that appears that moving the DB6 connection to Pin 2 is causing the first bit in each nibble to hold at 1.


 

 

Removing DB7 from Pin 2, and connecting DB6 to Pin 2

 

Removing DB6 from Pin 3 and leaving DB7 in place seems to cause a display of t,u,v,w,l,),>,<. This corresponds to an upper nibble of 0111, and a lower nibble that is x1xx.

 

 

I am not quite sure what I should be doing to fix the issue but will tackle this more in the coming days. One thing to note is that these issues haven't exactly been 100% replicate-able so I apologize in advance if I have a few of the details wrong!

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.

In the fourth post I used the Linux part of the Yun to get at the current date and time.

In the fifth post I scavenged a stepper motor from a flatbed scanner.

In post six that motor was running.

Post seven is covering the Infineon RGB LED shield.

My post number eight is an aside on programming the advent calendar logic.


This time I'm covering the creative 'Arts & Crafts" part.



Building the wreath


One of my kids helped me (read: did virtually everything) to build the wreath. We used only simple techniques.
The first task was to draw the top and bottom layer on a piece of paper.

wreath0001.jpg

 

wreath0002.jpg

 

We then transferred these drawings onto thick carton. We used a fat pencil to color the backside of both drawings black, taped the paper on the carton and traced the cut lines.

 

backside.jpg

That transfers the lines to the carton

calculeer.jpg

Next actions were to dremel out the two layers...

dremel.jpg

... and to decorate them

IMG_3547.JPG

 

Then it was back over to me, to add leds and motor, and to assemble the wreath.

IMG_3550.JPG IMG_3552.JPG

IMG_3565.JPG

 

Now the only two things left are writing the firmware and building the secret IoT part...

Hi All,

 

I tried to open a discussion but the website wouldn't publish it so I just created a quick blog about this project.

 

I was planning to make a quick IDE hard drive controller with an ATmega328p, and was wondering if anyone might know how the internal buffer addresses are incremented inside the hard drive during read/write operations?

 

Is there a set rate data has to be read from or written to the hard drive, or would the read/write pins be toggled to load the next set of 16 bit word during the read/write operations?

 

I'm a little confused, searching for tutorials, but they're not describing how the addresses are incremented, they're just saying read or write 512 bytes in one shot for either read or write sector operation.

 

Your help would be appreciated, thanks.

 

I know there are pre-written libraries, but I'll be interfacing this in a circuit of it's ow connected directly to an ATmega which will act solely as a dedicated IDE controller using the LBA access scheme.

link back to primary post BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights

 

In this episode I will demonstrate and provide all the code used to allow a browser / smartphone / tablet to adjust the colour of a light strip that is connected via an NRF24L01 2.5Ghz wireless link

 

In a previous episode I showed how to get Mosquitto server, pub and sub clients loaded into the YUN and how to use them

 

This post is extending on Benjamin Cabé's excellent demonstration and after finding all the scripts and getting the page hosted by the YUN itself I have a working demonstration that looks like the following

 

 

I can enter colours from either a subscription to the wheel ("theBreadBoard_Strip") being hosted at iot.elcipse.org or by entering colour selections directly at the YUN or the UNO via their serial terminals

 

Pay attention to case as the subscriptions are case sensitive

 

any changes via the wheel is almost instantly relayed to the UNO and subsequently displayed on the light strip,

 

The UNO is supporting a command interpreter to allow direct commands to be sent to it via any configured input mechanism (Serial or NRF at this time)

The YUN is supporting a simpler command structure at this time and simply relays the commands it receives onto the UNO via the NRF radio

 

A point to note is the YUN does not support the standard output pins for SPI, namely the MISO, MOSI and SCK lines do not exist on pins 11, 12, 13 and are only accessible via the programming header and the Infineon Shield needs stacking headers if your to add additional IO devices like a NRF24L01

 

Once all the pins where sorted out it was simply a matter of finding all the additional libraries for the web page to operate, the basic functionality required for talking to iot.elcipse.org of course comes from the PAHO js libraries but the colour wheel , Raphael and the boostrap all had to be found

 

Bootstrap · The world's most popular mobile-first and responsive front-end framework.

Raphaël—JavaScript Library

Color Wheel Demo

 

on the YUN you need to create a folder and sub folder in the root of a micro SD card "/arduino/www", once loaded into the YUN it immediately shows up at this location under the LINUX "/mnt/sda1/arduino/www" and a simpler path "/www/sd", from the home network it can be accessed as "http://arduino.local/sd/", it will automatically serve index.html


I have zipped up the SD card structure and attached for you to use


also the modified sketches for the YUN and the UNO with MQTT support and NRF24L01, there not cleaned up yet but they all work


I will be cleaning up the sketches as I add more functionality etc, I am getting close to full ram usage so it is essential before I continue much further


here is a quick video to show how it functions,




My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

I am now working on the software part of the 'advent state' logic.

 

In my design, there is a bottom layer (the wreath) with 4 lights that represent advent candles. They are always on.

On top of that, I'm mounting a circle with holes (the 'light filter').  That filter can turn and is driven by a motor.

 

 

Depending on what week of the advent we are, one, two, three or all four of the candles have to be shown.

There are 23 states:

  • state 0: not an advent date
  • state 1: first Sunday of advent, show one candle
  • state 2: first Monday of the advent, still show one candle
  • ...
  • state 8: second Sunday of the advent, show two candles
  • ...
  • state 15: third Sunday, show three candles
  • ...
  • state 22: fourth Sunday of the advent, and any day thereafter until January 6, show four candles

 

 

So I need logic to convert the day of advent into a particular position of the filter.

In one of my official posts on this contest, I have discussed my solution to get that date from the Yun's linux part.

And in that post, I was talking about intelligent solutions that would calculate the state for that day with nifty algorithms.

 

But now that I'm really implementing the solution, on a Sunday night after 12, the brain doesn't want to play along. So I resorted to a cheeky implementation:

  • I've hard-coded an array with advent days for the years 2014 and 2015
  • I've provided a second array with the corresponding states for each day in the advent
  • A lookup function that finds the correct state for any date within the covered period (let's call it the commercial guarantee period)
  • A function that looks up the day in linux and converts it to a long, in its own dodgy way

 

Below is the code. If you're looking for good code practices, this would be the right time to avert the eyes.

 



// includes for advent intelligence
#include <Process.h>


// ================================ START ADVENT CALENDAR SECTION ===========================================================


/* 
Advent intelligence


There are 23 states in my advent interpretation:
0: no advent
1: 1st sunday
2: 1st monday
...
8: 2nd sunday
...
15: 3rd sunday
22: 4rd sunday and any date between 25/12 and 6/1
For days between 25/12 and 6/1, state = 22 (same as 4rd advent Sunday


I have written the code this way to annoy you
to avoid any brain effort from my side, I have listed all dates from the first Sunday until January 6 in an array, 
and the corresponding advent states in a second array. If you find the day, you can look up the advent state.
For days not found in the list, state = 0


The date is presented as a long, just a conversion of the string YYYYMMDD converted to numerical. 
e.g.: date string "20141229" becomes long 20141229. Go figure :)


*/


// array with the advent intelligence lookup keys
long adventIntelligenceKey[] = {
// 2014
20141130, 20141201, 20141202, 20141203, 20141204, 20141205, 20141206, 20141207, 20141208, 20141209, 
20141210, 20141211, 20141212, 20141213, 20141214, 20141215, 20141216, 20141217, 20141218, 20141219, 
20141220, 20141221, 20141222, 20141223, 20141224, 20141225, 20141226, 20141227, 20141228, 20141229,
20141230, 20141231, 20150101, 20150102, 20150103, 20150104, 20150105, 20150106,
// 2015
20151129, 20151130, 20151201, 20151202, 20151203, 20151204, 20151205, 20151206, 20151207, 20151208,
20151209, 20151210, 20151211, 20151212, 20151213, 20151214, 20151215, 20151216, 20151217, 20151218, 
20151219, 20151220, 20151221, 20151222, 20151223, 20151224, 20151225, 20151226, 20151227, 20151228, 
20151229, 20151230, 20151231, 20160101, 20160102, 20160103, 20160104, 20160105, 20160106
};


// array with the corrsponding advent intelligence state
int adventIntelligenceValue[] = {
// 2014
  1,  2,  3,  4,  5,  6,  7,  8,  9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 
22, 22, 22, 22, 22, 22, 22, 22,
// 2015
 1,  2,  3,  4,  5,  6,  7,  8,  9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 22, 22, 22, 22, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22
};


/*
long getSysDate()
this function asks the Yun's linux part for the sysdate,a nd translates that to a long
retval: long - The current date as configured on the lini distro, just a conversion of the string YYYYMMDD converted to numerical
*/


long getSysDate() {
  long lRetval = 0L;
  Process date;                 // process used to get the date
  Serial.println("invoking linux date");
  if (!date.running())  {
    date.begin("date");
    date.addParameter("+%Y%m%d");
    date.run();
  }
  Serial.println("linux date invoked");
  while (date.available()>0) {
//    lRetval = date.readString().toFloat();    
    String timeString = date.readString();    
    Serial.println(timeString);


    lRetval = timeString.substring(0, 4).toInt() * 10000;
    lRetval += timeString.substring(4, 6).toInt() * 100;
    lRetval += timeString.substring(6, 8).toInt();
  }
  Serial.println(lRetval);

  return lRetval;
}


/*
int getAdventState(long day)
this function looks up the state of the advent. See comment section "Advent intelligence" above for the different states.
If the day passed to this function is found in the array adventIntelligenceKey, the corresponding state in array adventIntelligenceValue is returned.
Else we assume that we are not in the advent, and we return state 0.
The commercial guarantee of the gizmo powered by this algorithm should expire at the latest at the last day represented in the array above.
param day: the Long representation of a day to process, just a conversion of the string YYYYMMDD converted to numerical
retval: long - The current date as configured on the lini distro, just a conversion of the string YYYYMMDD converted to numerical
*/
int getAdventState (long day) {
  int i;
  int iRetval = 0;
  
  Serial.print ("day: ");
  Serial.print(day);
  for (i = 0; i < (sizeof(adventIntelligenceKey) / sizeof(adventIntelligenceKey[0])); i++) {
    Serial.print (" checking against: ");
    Serial.print (adventIntelligenceKey[i]);
    if (day == adventIntelligenceKey[i]) {
        iRetval = adventIntelligenceValue[i];
    Serial.print (" found state");
    break;
    }
  }
  Serial.print (" : ");
  Serial.println (iRetval);
  return iRetval; 
}


// ================================ END ADVENT CALENDAR SECTION ===========================================================




void setup() {
  // general setup
  Serial.begin(9600);    // initialize serial  
  
  // advent intelligence setup
  // the advent logic uses the lini part of the Yun, so Bridge needs to be initialised
  Bridge.begin();        // initialize Bridge
  
  // init motor
  
  // init leds
  
}


void loop() {
  
  int iState;


  // get date
  // get advent state
  
  iState = getAdventState(getSysDate());
  delay(10000); // TODO : remove debug code
  
  // adjust to advent state
  
  
  // do secret logic with MQTT


}

 

So all high standards have been thrown out of the door, but the code works:

 

adventlogic.jpg

It's been a while since I last wrote here but I was busy developing my project!

 

I set up the Arduino Yún and it's fantastic. The Linux side is very handy, but I nearly ran out of memory on the Atmega chip (LCD driving libraries and fonts are resource-heavy!).

While I'm still working on the different clients, I am nearly finished developing the web interface and the Arduino communication code.

 

The Web Interface

 

It’s coded in Python (CherryPy as backend) and Javascript and is hosted on the linux-side of the Yún. It can connect to any of the lights so that you can control them as you want. Here's a screenshot:

 

HaMCNHX.png

 

It’s pretty basic and I plan on adding more features. It’s also my first experience with Javascript. On the upper right, there is a button you can use to choose which client to connect to: it turns green if the connection is successful, red otherwise.

I found the color picker on Google and tweaked it a little bit: unfortunately, I don’t remember who made it as it was a few weeks ago.

The Web Interface is sending commands in the following form, which will then be read by the Arduinos: MODE,R,G,B$. For example, if you want to set the orange color, the command would be “M,255,128,0$”, with ‘$’ as the terminating character. This is a Python test server running on my desktop, receiving commands from the web interface.

 

UiZSV5b.png

 

The ‘F’ stands for fade and the following numbers are the starting and ending values for each color. The last one, ‘5’ in this case, is the delay between each fade step in milliseconds.

‘S’ is strobe mode, and ‘100’ is the delay between each color change in milliseconds.

As you can see, the code is now opening a new connection for each command sent. This is quite bad practice, so I’ll need to fix it.

 

Python server and script (+ Arduino communication).

 

These are running on the Linux side of the Yún and they are called and started by the setup() function in the Arduino sketch. There is a set of useful commands from the Bridge and Process classes which can be used to run Linux commands from the Arduino.

 

In this case, I’m using runShellCommandAsynchronously() to start a non-blocking Python process (i.e. the Arduino sketches continues to run, without waiting for its completion).

 

I’m calling it twice, to run both the webUI application and the script that connects to the various clients and sends the needed strings.

 

Here’s the file that sends commands to the various clients. It sends the string received from the Arduino only if it’s different from the previous one.

 

import socket
import string
import sys
sys.path.insert(0, '/usr/lib/python2.7/bridge/')
from bridgeclient import BridgeClient


def send(host, port, command):
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


  if(sock.connect_ex((host, port)) == 0): #if connection is successful
  print ("Connected to %s:%d") % (host, port)
  print ("Sending command %s") % command
  sock.send(command) #send the string
  sock.close() #and close the socket
  return 0
  else:
  print ("Connection failed :(")
  return 1


bridge = BridgeClient()
last_command = "0"


while 1:
  if(bridge.get("status") != "0"): #check if we need to update
  IP = bridge.get("IP") #get the IP
  port = int(bridge.get("port")) #get the port and convert it to an integer
  command = bridge.get("data") #get the string we need to send
  if(command != last_command): #if it's different than the previous one...
  if(send(IP, port, command) == 0): #...send it and check the result
  last_command = command #the string we just sent becomes the last sent
  bridge.put("response", "0")
  else:
  bridge.put("response", "1")





 

That’s how it works: when you call the Bridge.put(“destination”, “value”) function in the Arduino sketch, it puts your value into a “destination” variable. This value can then be retrieved from the Python script after declaring a BridgeClient object and using the command bridge.get(“destination”).

 

I'm now working on the Yún controller, and here's a (very messy) picture!

 

IMG_20141228_220326.jpg

 

Also, tomorrow I will setup the Uno and the Infineon shield, and maybe share the clients code (which receives the commands and controls the lights accordingly).

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.

In the fourth post I used the Linux part of the Yun to get at the current date and time.

In the fifth post I scavenged a stepper motor from a flatbed scanner.

In post six I got that motor working using a Velleman motor driver.


I am now adding the Infineon LED shield to the design. That finishes off the electronics part of my design.

 

IMG_3516.JPG


Theft


I blatantly stole peteroakes BYOB Party #3, Infineon Library Available. I've seen in the comments on the Internet of Holiday Lights blogs that I won't be the only one running away with it. Works perfectly, Peter!

So I won't elaborate on the software part here. Check Peter's blog post.


I didn't have stacking headers available. And normal mail headers do not leave enough spece between the shields. Using them would very likely create short circuits or other mishaps.

I decided to take another approach. I soldered female headers upside down on the bottom side of the Infineon shield, and used prepped' male headers to match the female headers of the two chields.

'Prepped' means that I forced the plastic part of the male headers to the center of the pins, so that there's enough pin left on both sides to make contacts with the female headers:

IMG_3510.JPG


stacker.jpg


Electronics prototyping finished


Now that I have all parts of the software solution tried out (I also tested the IoT MQTT library and got that working though I didn't blog about that [yet?]), I'm done with the investigating cycle.

The four main electronics functions of my design are covered:

  • I can drive a motor with sufficient precision, needed to get the light filter in the correct position.
  • I can talk to the linux part to get the current date for my timezone. I need that to know where I am in the advent cycle.
  • I can drive the Infineon shield to handle the lights part
  • I'm able to use the Eclipse IoT services for surprise functionality that I'm not going to reveal yet.


I've also tested the two most hardware dependent parts in combination: the stepper motor shield and the Infineon RGB driver shield. That worked out ok.



Here's the code of a combined stepper/led exercise:


// led shield includes
#include <Wire.h>
#include "Infineon.h"
// stepper shield includes
#include <Stepper.h>


// stepper constants
#define STEPA 4
#define STEPB 12
#define ENAA 5
#define ENAB 10
const int stepsPerRevolution = 96;

Infineon RGBLEDS = Infineon();


Stepper myStepper(stepsPerRevolution, STEPA, STEPB);



void setup() {              


    Serial.begin(9600);


    // led shield
    Wire.begin();
    Serial.println("buy time to start the serial monitor...");
    delay(5000); // wait 5s
    Serial.println("polling led shield...");
    while (RGBLEDS.on != 1) // Wait for shield to respond, keep setting the values till it does
    {
    
      Serial.println("led shield setup");


      RGBLEDS.I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Immediate fade
      Serial.println("faderate set up");
      RGBLEDS.I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // 0% brightness level
      RGBLEDS.on = RGBLEDS.I2CREAD(ADDRESS, READ_DIMMINGLEVEL); // Request for brightness level
      if (RGBLEDS.message == 1 && RGBLEDS.on == 0) // If message received and dimming level = 0%, "message" is set in the I2CREAD function
      {
        Serial.println("message check for 0");
        RGBLEDS.message = 0;
        RGBLEDS.on = 1; // break out of loop
      }
    }
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x38); // Set off-time of green channel to 0x39
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
    RGBLEDS.I2CWRITE6BYTES (ADDRESS, CURRENT_RGB, 0x80, 0x05, 0x05); // max:  0x80 = 780mA
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Fade Rate between intensities --> 0.0s
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, WALKTIME, 0x0000); // walk time between colors = 0s
    RGBLEDS.I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0555, 0x0555, 0x0555); // low level White Light
    RGBLEDS.I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0FFF); // Maximum dimming level means inensity settings are directly used
  
    // stepper shield
  pinMode(ENAA, OUTPUT);  //Set control pins to be outputs
  pinMode(ENAB, OUTPUT);
  digitalWrite(ENAA, LOW);
  digitalWrite(ENAB, LOW);
  // set the speed at 30 rpm:
  myStepper.setSpeed(30);



}

  // the loop routine runs over and over again forever:
  void loop() {
    Serial.println("colour loop...");
    // change lamp colour to red
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0, 0x0, 0x0); // all off
    delay(500); // wait 1000ms
    step(stepsPerRevolution);
    // change lamp colour to green
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x03ff, 0x03FF, 0x03FF); // 25%
    delay(500);
    step(-stepsPerRevolution);
    // change lamp colour to blue
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x07ff, 0x07ff, 0x07ff); // Blue
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0bff, 0x0bff, 0x0bff); // Blue
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0fff, 0x0fff, 0x0fff); // Blue
    delay(500);
    step(stepsPerRevolution);
  // White, Silver, Gray, Black, Red, Maroon, Yellow, Olive, Lime, Green, Aqua, Teal, Blue, Navy, Fuchsia, Purple
    RGBLEDS.SETCOLOUR( White);
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Silver );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Gray );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Black );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Red );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Maroon );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Yellow );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Olive );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Lime );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Green );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Aqua );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR( Teal);
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Blue );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Navy );
    delay(500);
    step(stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Fuchsia );
    delay(500);
    step(-stepsPerRevolution);
    RGBLEDS.SETCOLOUR(Purple );
    delay(500);
    step(stepsPerRevolution);

  }



void step(int steps) {
    digitalWrite(ENAA, HIGH);
    digitalWrite(ENAB, HIGH);
    myStepper.step(steps);
    digitalWrite(ENAA, LOW);
    digitalWrite(ENAB, LOW); 
  }









In my last two posts i covered how i setup the Eclipse Ponte Bridge locally and how my Arduino Yun with an Infineon Shield was reading from a MQTT topic from it using HTTPClient

 

In this post i will cover how i used Arduino Uno with an ESP8266 to publish a MQTT message with RGB values.


Arduino Uno + ESP8266


IMG_4441.JPG


I ordered the ESP8266 during this road test because my initial plans of using an Arduino Uno with a CC3200 Simple Link Launchpad didn't work out very well. For $7 it provides bang for the buck as long as you tolerate the initial getting to know you phase. Most of the frustration is because of the different versions and the lack of official documentation. That though seem to be improving of late as the firmware seem to have stabilized somewhat and an updated SDKs seem to have been released this month.

 

I was lucky in that the ESP8266 i got already had the latest firmware and i had the version v0.91 board.  I didn't have to update the firmware. The following is the pin definition of my ESP8266:

ESP8266_V091.png

 

I tried initially to try to use the UNO as a FTDI driver by connecting the ESP8266 to Uno with level shifters. But that didn't work. No response at all from the ESP8266. Then i bought a FTDI breakout board with a 3.3v output and i was able to talk to ESP8266 using CoolTerm (Except for the Arduino, i am using all these different tools for the first time. That added to frustration levels sometimes. But it was well worth it as it helped me learn so many new things). Once i become comfortable with the AT commands, i hooked the ESP8266 back to Arduino Uno using level shifters.

 

Again nothing from Uno.

 

One of the major misconceptions out there seem to be around using level shifters. Every one (including much respected AdaFruit) keeps saying you need to use level shifter to connect the RX pin of the ESP8266 to Uno's TX pin since uno operates at 5V. But the data sheet i found here says this in page 15.

All digital IO pins are protected from over-voltage with a snap-back circuit connected between the pad and ground. The snap back voltage is typically about 6V, and the holding voltage is 5.8V. This provides protection from over-voltages and ESD. The output devices are also protected from reversed voltages with diodes.

 

I am not an electrical or electronics engineer. But that statement seemed to me that it might be OK to connect the ESP8266 directly to my Uno. So i just did that and it worked. (It would be interesting to hear from the engineers in this Element 14 community about that particular statement above)

 

Following is the wiring i did:

 

1. Arduino 3.3v power to bread board red power rail

2. Arduino Ground to bread board ground (black rail)

3. ESP8266 Ground to bread board ground (black rail)

4. ESP8266 CH_PD to bread board red power rail ( This is the reset pin. I was not brave enough to connect it to Uno's reset pin. So every time i loaded my sketch, i had to pull this out and push it back in. A veritable stress test i would say.)

5. ESP8266 TX to Arduino Uno Digital Pin# 2 ( i will be using software serial library to designate this pin as RX for arduino)

6. ESP8266 RX to Arduino Uno Digital Pin#3 ( designated as TX pin using software serial library)

7. ESP8266 Vcc to bread board power rail


That's all. I have been using this setup for a few days now. It has gone through couple of power surges (too much bad weather with lightning here) and still working.


The Software (ESP8266RESTHelper Library)


As i mentioned in the beginning i have already set up Ponte MQTT/HTTP/Coap Bridge locally. ESP8266 has a TCP stack that can be accessed via AT commands. So all i had to do is prepare the proper AT commands for the ESP8266 and make it send PUT requests to the Ponte HTTP bridge for publishing MQTT topics. Other clients whether they use MQTT libraries or HTTP GET (see here) were able to receive the messages.


Since i started working on the AT commands i ended up creating a helper library to do http GET and POST as well.  The ESP8266RESTHelper library is available here at Github. If you are interested take a look and use it as you see fit. Please note apart from the sendMQTTMessage other functionalities are not fully tested. But it might give you a starting point.


Here is the sketch that's running on my Arduino Uno. Visit the Github library to see the API and the AT command sequence.

#include <SoftwareSerial.h>
#include "ESP8266RESTHelper.h"
ESP8266RESTHelper esp8266=ESP8266RESTHelper();
void setup() {
  esp8266.begin();
}
void loop() {
  //Send Red -- topic name starts with "/resources/" because the Ponte http bridge expects PUTS to be sent that way. The actual topic for clients is just "FromArduinoUnoESP/RGB"
  esp8266.sendMQTTMessage("192.168.1.217",6000,"/resources/FromArduinoUnoESP/RGB","255,0,0");
  delay(2000);
]  //send Green
  esp8266.sendMQTTMessage("192.168.1.217",6000,"/resources/FromArduinoUnoESP/RGB","0,255,0");
  delay(2000);
  //Send blue
  esp8266.sendMQTTMessage("192.168.1.217",6000,"/resources/FromArduinoUnoESP/RGB","0,0,255");
  delay(2000);
}





 

Here is a video of the Arduino Uno with ESP8266 sending MQTT messages and the Arduino Yun receiving the mqtt messages and changing the led strip using httpclient(explained in this blog entry) (note that blue led on the ESP8266 go on and off when TCP send happens)

 

 

Updates:

1. Software Serial Library:  (Thanks to a question from Wes in the comments)

I am using Arduino Ide version 1.5.8 beta..This includes a SoftwareSerial Library as part of the core ide libraries..

 

Arduino - Software

 

If you need the Github location for the core libraries, its here:

https://github.com/arduino/Arduino/tree/ide-1.5.x/hardware/arduino/avr/libraries

 

2. My ESPRESTHelper library is using String object.. i have come to realize String is not the ideal thing to use. I am running into weird memory issues once the code becomes bigger and the dynamic memory becomes full. It is ok for simple proof of concepts. I will update the library soon to remove Strings from it.

turfgnome

Light Shield Review Part 1

Posted by turfgnome Dec 27, 2014

I have been working with the light shield on the arudino uno as I do not have any risers with me on my vacation, and did not think that I would need them for this project.  The good news is I found I still had the leftover 4 pins needed for my relay setup.  The shield came without the pins so I had to get some but soldering them on is not a problem.  So far I can only get a few colors however when I get home I will see if I have the stuff to make the changes I need to get a better quality color control as currently I am only reliable at red, green, blue, and white light.  I will update this sometime next week with my changes.

 

2014-12-19 11.52.36.jpg

List of previous posts

 

The Teaser

The project documentation is taking forever and I will release it much more systematically. For now, here is a small video of one of the parts which is the audio controlled LED lights. I am using the ARDUINO RGB LED SHIELD, XMC1202ARDUINO RGB LED SHIELD, XMC1202 and an Arduino. I am using an analog filter and the details will be released in an upcoming post.

 

 

Cheers,

IP

This post is part of my entry to the Internet of Holiday Lights road test challenge. A full list of all the post is available at this link.

 

In the earlier blog post, i introduced Ponte and set it up locally on my windows PC.

 

In this post i will demonstrate how i used the HTTP Client on the Arduino Yun to read the MQTT messages and light up the LED strip using the Infineon Shield. This code does not use any of the MQTT Client libraries to subscribe to a topic. It just uses the HttpClient available on Arduino Yun's bridge library and keeps polling the HTTP bridge on the Ponte server for message availability.

 

The HTTP Client in Arduino Yun works by creating a process on the linux side to run "curl" program. Once the linux side receives a response, its sent over the hardware serial port to the Arduino processor. In the code below, i am setting up the base Url for the Ponte server with the MQTT topic and accessing it the loop using the HttpClient. The get method on the HTTPClient is a blocking call. You can use the getAsynchronously() method if you need a non-blocking call.

 

Once a response is received, I am parsing it to split the RGB values, map it to a maximum of 4095 which is the maximum value for the intensity parameter on the Infineon RGB Shield.

 

//Description: Arduino Yun sketch to read an MQTT Topic on Ponte bridge using HTTP Client
//Code uses a custom version of Infineon RGB shield library created with samples from Infineon
//Written for the Internet of Holiday Lights challange at element14.com
//http://www.element14.com/community/groups/arduino/blog/2014/12/11/intro-interactive-wifi-christmas-tree
//Date: December 26, 2014
//Author: Mohan Palanisamy
//Please note that the code doesn't include much of error handling as its a Proof of Concept code.
#include <Bridge.h>
#include <HttpClient.h>
#include <Wire.h>
#include "InfineonRGB.h"

//Using two strings to easily differentiate base url and the topic..
//Base url points to my local installation of Ponte server. /resources is where ponte adds topics.
String mqttPonteBaseUrl="http://192.168.1.217:6000/resources/";
String mqttTopic="FromPonte/RGB";
String currentColor="";


HttpClient httpClient;
InfineonRGB rgbShield= InfineonRGB();

void setup() {
  Bridge.begin();
  Wire.begin();
  rgbShield.begin();
  delay(1000); //small delay to let bridge initialize
}


void loop() {

  httpClient.get(mqttPonteBaseUrl+mqttTopic);


  while (httpClient.available())
  {
    String response=httpClient.readString();
    //Ponte bridge responds with a Not Found if there is no message for the topic.
    if(!response.equals("Not found"))
    {
       changeColor(response);
    }
  }

  delay(200); //change this delay of you don't want the http get to be called so often
}


void changeColor(String rgbString)
{
      //Parse RGB;
      int rIndex=rgbString.indexOf(',');
      int gIndex=rgbString.indexOf(',', rIndex+1);


      int r= rgbString.substring(0,rIndex).toInt();
      int g= rgbString.substring(rIndex+1,gIndex).toInt();
      int b= rgbString.substring(gIndex+1).toInt();
   
      //map to the maximum intensity available on the infineon shield
      r=map(r,0,255,0,4095);
      g=map(g,0,255,0,4095);
      b=map(b,0,255,0,4095);
   
      rgbShield.setRGB(r,g,b); //light up
}



 

Here is the code in action. I use the mosquitto_pub application to send mqtt messages. Please note that the messages are sent with retain flag (-r) to make sure its accessible from the http bridge whenever a client connects and asks for it.

$ mosquitto_pub -r -h 192.168.1.217 -t FromPonte/RGB -m "255,0,0"



 

 

 

The best way to listen for MQTT messages is by using the MQTT libraries. They provide the fastest response because the TCP connections are kept alive until they are explicitly closed. This demonstration of HTTP Client is another way of consuming MQTT messages without dependence on additional libraries when your application doesn't need the entire functionality offered by the MQTT stack and a HTTP bridge like Ponte is available.


All code is available at this github location.

 

Stay tuned for further use cases for the Ponte Bridge as i continue to build additional modules for my Interactive WiFi christmas tree.

Update: See here for the MQTT publisher..

Part 3.3: Arduino Uno + ESP8266 + Eclipse Ponte HTTP Bridge = MQTT Magic

Okay, I confess right up front, this is a bit of a spam, but I think you will forgive me when you see it.  We (Original Design & Development) just launched Omnuino on Kickstarter.  With all the humility and reserve this retiring Brit has in spades, I think it's a pretty cool addition to the Arduino multiverse.  I'll let the picture and Kickstarter tell the story...

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.

In the fourth post I used the Linux part of the Yun to get at the current date and time.

In the fifth post I scavenged a stepper motor from a flatbed scanner.


I have that motor working now.






The motor driver kit

In my previous post I blogged about driving the motor with a 4 transistor H-bridge, and how I goofed that up. So I ended up dragging home a Velleman MOTOR & POWER SHIELD VOOR ARDUINO.

That shield's design is very similar to the Arduino Circuit for Bipolar Stepper Motor (the two pins example). Here's the two schematics side by side:

bipolar_stepper_two_pins2.png  velleman.jpg


Velleman and myself have one particular thing in common. We're both from Belgium.
The last time I've built a kit from them must have been somewhere in the late 80's. So I was quite excited to spend an evening of my Christmas holidays building up the kit.
There was one unpleasant thingy though. The smd ic was packaged in bubble wrap with tape around it. And someone in the kit assembly department must have been too strong for that job:

IMG_3489.JPG

No real harm done, I could straighten the pins without too much effort. Still, I'm expecting better...


Building the kit


That was not too difficult. There's only one smd component. In stead of soldering it with a fine tip pin by pin at the end - as advised by Velleman - I put that one up first.

I used solder paste and hot air. At my age, your eyes are happy that the don't have to stare at the 20 tiny pins while hand soldering each of them.

 

solder station

My solder station is an Aoyue 968A+. I've bought that with a voucher my company gave me earlier this year as a present. Because I'm a cheapskate, I searched for the lowest price (shipping included). That was on Amazon America.

The pleasant surprise came a week later when the Belgian tax authorities charged me an import tax that was lifting it way up above buying local. Go figure.

Photo 26-12-14 22 45 57.jpg

 

I'm rather fond on that solder station. Works well for me.


The other thing that I did different than Velleman's instructions is using flux. I'm soldering lead-free, and flux is more than welcome in that situation.
The kit is complete, and the instructions are easy to follow. And since it's been a while since I did that, it was quite an entertaining exercise.


IMG_3492.JPG



The software


I want to use the Arduino Stepper library. In this contest, one of my goals is to stick close to the nature of the devices.
IMG_3503.JPG


Since there isn't too much difference in design between Velleman's kit and Arduino's example, it shouldn't be too hard. And it isn't.

For the moment, I've left all the jumpers on my kit in their default position.

  • enable coil A on digital3
  • direction coil A on digital 2
  • enable coil B on digital 9
  • direction coil B on digital 8


I could use the Ardiono Shield example libraries with these changes:


in the constructor and setup(), I switched the output pins to reflect the jumpers on my shield, and enabled the enable (sic) pins.

#define STEPA 2
#define STEPB 8
#define ENAA 3
#define ENAB 9
#define BUTTON_CTRL 4
// ...
Stepper myStepper(stepsPerRevolution, STEPA, STEPB);


void setup() {
  pinMode(ENAA, OUTPUT);  //Set control pins to be outputs
  pinMode(ENAB, OUTPUT);
  digitalWrite(ENAA, LOW);
  digitalWrite(ENAB, LOW);
// ...
// set the speed at 60 rpm:
  myStepper.setSpeed(60);
   // initialize the serial port:
  Serial.begin(9600);

// ...








in the loop(), I took advantage of the enable capability of my shield:

void loop() {
  // step one revolution  in one direction:
// ...    
    Serial.println("clockwise");

    digitalWrite(ENAA, HIGH);
    digitalWrite(ENAB, HIGH);
    myStepper.step(100*stepsPerGearRevolution);  //  yes, I'm testing 100 full turns of the slowest wheel in my gearbox top test the resolution :) -- too lazy to count the cogs and ratios in my gearbox
    digitalWrite(ENAA, LOW);
    digitalWrite(ENAB, LOW);
    delay(500);
  }






I've successfuly tested the following examples on my stepper motor / shield combination:

examples.jpg

I haven't tried the other Stepper examples. I have no reason why they shouldn't work too.


Motor and gearbox resolution


I've measured the motor resolution by adapting the stepper_oneRevolution example.

I found info on my motor (the Neocene 2T3542146) on the manufacturer's site. The step angle is 3,75°. 3,75°per Step = 96 steps per rotation.

I have verified that by running this adapted example:

#include <Stepper.h>


const int stepsPerRevolution = 96;  // change this to fit the number of steps per revolution
// for your motor


// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 2);


int stepCount = 0;         // number of steps the motor has taken


void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(3, OUTPUT);  //Set control pins to be outputs
  pinMode(9, OUTPUT);
  digitalWrite(3, HIGH);
  digitalWrite(9, HIGH);

}


void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:" );
  Serial.println(stepCount);
  stepCount++;
  delay(25);
}






To measure the full resolution, I marked one cog of the slowest gear in the reduction. Then I activated the motor and counted how many rotations of the motor where needed for one full rotation of that last gear in the reduction.

I came at approx 29.5 rotations.

Then I made the following sketch to fine tune. It waits for a button press and then takes what I think are the right amount of steps to make the slowest gear go around 100 times.

That should give me enough resolution to survive the advent weeks.



/*
Stepper Motor Control - one revolution


This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.


The motor should revolve one revolution in one direction, then
one revolution in the other direction.




Created 11 Mar. 2007
Modified 30 Nov. 2009
by Tom Igoe  (adapted by jc for the Internet of Holiday Lights - Velleman KA03 motor driver with Neocene 2T3542xmotor


*/


#include <Stepper.h>


#define STEPA 2
#define STEPB 8
#define ENAA 3
#define ENAB 9
#define BUTTON_CTRL 4




const int stepsPerRevolution = 96;


const int stepsPerGearRevolution = 30*stepsPerRevolution-32;  // change this to fit the number of steps per revolution


Stepper myStepper(stepsPerRevolution, STEPA, STEPB);


void setup() {
  pinMode(ENAA, OUTPUT);  //Set control pins to be outputs
  pinMode(ENAB, OUTPUT);
  digitalWrite(ENAA, LOW);
  digitalWrite(ENAB, LOW);


  pinMode(BUTTON_CTRL, INPUT);




  // set the speed at 30 rpm:
  myStepper.setSpeed(30);

  // initialize the serial port:
  Serial.begin(9600);
}


void loop() {
  // step one revolution  in one direction:
  if (! digitalRead(BUTTON_CTRL) ) {
    Serial.println("clockwise");
  //  myStepper.step(stepsPerRevolution);
    digitalWrite(ENAA, HIGH);
    digitalWrite(ENAB, HIGH);
    myStepper.step(100*stepsPerGearRevolution);
    digitalWrite(ENAA, LOW);
    digitalWrite(ENAB, LOW);
    delay(500);
  }

}




 

assorted scribbles:

DRIVER.jpg

Hi to all Element14 community members, as you can see in the above title my Internet of Holiday Lighting RoadTest Plus project is "Smartphone Controlled Lighting System", I was one of the 20 lucky people who got selected in this RoadTest, Element14 has provided us all the goodies that we require to make our project, I have received the parts (Arduino UNO, Arduino YUN, and the Infineon RGB Shield).


                                                         10540894_638902612881384_570884470_n.jpg


Sorry for the delay in writing this first blog post, I was busy in a family function. Other contestants are ahead of me, I get a little lazy sometimes and want to take thing slow. My project "Smartphone Controlled Lighting System", is also the result of this laziness, sometimes one does not want to get up from the bed and walk up to the switch board to just switch on or off the lights or something else, especially in the winter, when you just don't want to get out of that blanket ! The idea of this project was in my mind for months and I had started working on it even before this roadtest was announced. The Idea is to make a home automation system which can be controlled by a smartphone ( with Bluetooth ), And also with a simple IR Remote control.


When the road test was announced I made improvements in my original idea, Firstly I included IoT to this Road test, which will make full use of the Arduino YUN and also to include Mood Lighting.


I have started to to test all the hardware individually, and it seems promising, I am also making a LED matrix display from scratch,  and It will also be included in this project if it gets completed in time.


This is going to be my first IoT project, also have not worked with any I2C device in the past, but after messing around with the Infineon Shield and the codes and reading other contestants blogs I have got the hang of it, it is not that hard.


Guys I will need help from all of you, so please do help me out during the course of this road test, more in the next blog post..


In an earlier post i described how i setup a Mosquitto MQTT broker locally. In this post i will introduce you to "Ponte" a brilliant project that's in development at the Eclipse foundation.


What is Ponte


Ponte is a M2M bridge framework that aims to close the gap between M2M interactions and the rest of the Internet. The current implementation is built on top of NodeJs.

architecture.png

 

Image Source: Eclipse.org ponte team.


Why Ponte


Protocols like MQTT and CoAP are playing a major role in standardizing M2M communications. These protocols have been making it easier for building connected devices as we have seen in this RoadTest and elsewhere in several of the design challenges at Element14.


For the vision of Internet of Things to be fully realized, these devices need to be accessible to the world wide web in a language that WWW speaks. WWW and Internet don't speak MQTT or CoAP naturally. They speak HTTP.  For example you cannot easily have your PC or a MAC or smart phone access the information from the MQTT/CoAP bridges without resorting to custom applications that use specific libraries (like the Paho MQTT client Libraries.. kartben introduced the MQTT  Javascript and C library in this example.. Here is an example of using the Java MQTT Library with processing)


That's where a bridge like Ponte becomes extremely useful. It can speak MQTT, CoAP and HTTP.. That makes it imminently suitable for connecting the resource constrained devices with the rest of the world. Also it supports excellent array of storage engines (a.k.a Database) that allow data from the connected things to be stored, analyzed, syndicated and do whatever we do with regular databases.


For example consider the Sudden Impact design challenge currently running on Element 14. Multiple sensors and devices would be sending data to the Ponte bridge using MQTT or CoAP. A Ponte Bridge will allow that data to be collated in one place and analyzed. Web/mobile applications can be easily written using the HTTP bridge on Ponte to present it to users.


For the Holiday lights IoT challenge i will present a small use case later that will demonstrate the power of Ponte over other MQTT bridges.

(Update: Please see the following posts for use cases.

Part 3.2: Reading a MQTT topic with HttpClient On Arduino Yun

Part 3.3: Arduino Uno + ESP8266 + Eclipse Ponte HTTP Bridge = MQTT Magic

)

Installing Ponte


1. If you do not have nodejs already installed, install it from http://nodejs.org/download/

2. Do a  npm update to make sure that node package manager is up to date

3. Install Ponte by running the following:

npm install ponte -g $ ponte


Running Ponte:

1. If you are already running a MQTT broker like mosquitto, stop it. (In windows use the windows services control panel.)

2. then run Ponte from command line (with a verbose flag if you want to see more information as each connection is made):

ponte -v


Here is an output from my PC when i run Ponte in verbose mode:

C:\RnD\nodejs\node_modules>ponte -v
{"name":"ponte","hostname":"MATRIXPC","pid":17440,"service":"MQTT","level":30
,"mqtt":1883,"msg":"server started","time":"2014-12-26T18:25:43.234Z","v":0}
{"name":"ponte","hostname":"MATRIXPC","pid":17440,"service":"HTTP","level":30

,"port":6000,"msg":"server started","time":"2014-12-26T18:25:43.253Z","v":0}
{"name":"ponte","hostname":"MATRIXPC","pid":17440,"service":"CoAP","level":30

,"port":6683,"msg":"server started","time":"2014-12-26T18:25:43.254Z","v":0}


Note the ports at which each of the HTTP, MQTT and CoAP srvers are running. In my machine i edited the HTTP port number and the CoAP port numbers in the Server.js file (found at C:\Users\XXX_User_name\AppData\Roaming\npm\node_modules\ponte\lib)


Note down the port number for HTTP.. It should be 3000 by default.


Accessing MQTT Topics from HTTP:


Each MQTT Topic can be accessed from the Ponte HTTP Endpoint by adding the topic name after resources:


For example: Considering that your "MyHostName" is your host name and the http port for Ponte is 3000, the http URL for the topic "MyFirstTopic" is


http://MyHostName:3000/resources/MyFirstTopic


Now to subscribe to messages from this topic we use "GET" and to publish messages to this topic we use "PUT"


Publishing from HTTP to MQTT


Go to Terminal or command prompt and use curl (On windows i installed curl from http://curl.haxx.se/download.html). Also if you have already installed mosquitto broker as described here, it would have come with a two very handy utilities for publishing and subscribing (mosquitto_pub and mosquitto_sub). I will be using them as well here:


First run mosquitto_sub to listen to messages on all the topics. (This is just for testing and verifying. Typically you will be listening to specific topics in actual client implementations)


mosquitto_sub -v -h localhost -t "#"


Then open another terminal and run curl to "PUT" mqtt message "255,255,0" to topic name "RGB"


curl -X PUT -d "255,255,0" http://localhost:3000/resources/RGB


Now you should see the message popping up on the mosquitto_sub window


Publishing from MQTT to HTTP


use mosquitto_pub to send a test message. Make sure the retain flag ( -r ) is set to ensure the broker retains the message until some client reads the message.

mosquitto_pub -r -h localhost -t FromPC/TestPonte -m "Are you There?" 


use Curl to issue a GET to read the message


Now you should see the message in the curl response.


Resources


Following links provide more information on Ponte:

Ponte - Bringing Things to REST developers

http://eclipse.org/proposals/technology.ponte/

https://github.com/eclipse/ponte

 


Stay tuned for more articles on how i use Ponte bridge in my IoT Holiday lights project.

Update: see here for additional blog entries:

Part 3.2: Reading a MQTT topic with HttpClient On Arduino Yun

Part 3.3: Arduino Uno + ESP8266 + Eclipse Ponte HTTP Bridge = MQTT Magic

)

Between shipping, working, and the holidays, I haven't had a chance to give my roadtest hardware a good going over... until now!

 

The Internet of Holiday Lights RoadTest involves three pieces of hardware: The venerable Arduino Uno, its cousin the Arduino Yun, and Infineon's RGB LED Arduino Shield.

 

arduino uno.jpg

 

Chances are good that if you've spent any reasonable amount of time making things in the past five years or so, you've heard of Arduinos, and have probably used the Arduino Uno. The Arduino Uno is essentially a breakout board for an ATmega328 8bit microcontroller that gives you access to 14 digital i/o lines and 6 analog input lines. Within those digital i/o lines are two pins which allow you to use I2C devices, and two pins which can be used for serial communications.

 

The one real caveat of the device is that the ATmega328 doesn't have native USB support, so communications with it is mediated by another chip (the ATmega16U2 in the latest revision of the board) acting as a USB-to-serial converter. What this means is the Uno will only ever appear as a virtual COM port to your computer.


The Arduino Uno is a long time staple of the maker toolkit, and although it lacks the clock speed or large number of i/o lines of some of the larger Arduinos, it's still quite capable and a good starting point for microcontroller based projects.


arduino yun.jpg


The Yun is a relatively new addition to the Arduino line. It was added just over a year ago, and is an Arduino Leonardo coupled with an Atheros SoC running OpenWRT (for those of you who have never hacked your router - this is a Linux derived firmware designed for embedded networking devices). This means you get the 20 digital i/o lines of a Leonardo (of which, 12 can be used for analog inputs), the native USB support of a Leonardo (which allows the board to appear as a USB HID device or virtual COM port to your computer), and a directly coupled Linux-based network interface that is both wired and wireless.


Just like the Leonardo, the Yun has the same pinout as the Uno, making it compatible with all the same sheilds you may already have bought or developed for the Uno.


Unlike the Leonardo, however, the Yun doesn't have an onboard voltage regulator. This means you can only power it from a 5v source, and exceeding that may damage the board. It also has a microSD slot, which is tied to the Atheros SoC, intended to be used to hold all your settings, served content, and additional packages for use on the web side of your Yun project.


RGB shield.jpg


The last hardware component of the roadtest is the truly unique one: Infineon's RGB LED driver sheild for Arduino. This shield, in the configuration supplied, has one power input, one data input, and one power/command data output. It also comes without any headers, so you can easily add simple male headers, or a stackable female header if you intend to use more than one shield with your Arduino.


The level of soldering skill required to assemble the board is minimal, pin headers are just about the easiest soldering project out there, but you will need a soldering iron and some solder to get the board up and running.

 

The reference manual recommends providing a higher input voltage than what your LEDs' forward voltage requirement is, but it will happily accept anywhere from 12v to 48v as the input. I haven't tested the theory that you may get normal operation by feeding it an input voltage that matches your output voltage, but other members of this roadtest have and seem to have made it work, so your mileage may vary. I'm powering my project off an old HP printer power supply that pushes 36v, so there's more than enough voltage there to run my 12v LED string.

 

One note: When looking at the silkscreen on the board, you (like me) may misread the labeling for the power input. There is a space above the power input terminals for a DMX chip and input, and the silkscreen on the board has handy labels for that input. If you try to use that label to decide which power input terminal is negative, and which is positive, you're going to wire your power in backward and the shield won't work. Luckily, Infineon was smart enough to realize their users may be quite stupid at times, so reversing the voltage input doesn't seem to damage the board.

 

RGB shield assembled.jpg

Examining the shield, you can see it fits snugly into an Arduino Uno (or otherwise compatible) pin header for control signal input. Only the I2C pins, and the ground pin, are used so the rest can safely be passed through to additional shields if your setup requires it.

 

The power input is also quite simple, if you do one better than me and actually manage to read the correct silk screened label. The output is equally simple: There is one pin for the common anode of your LED setup, then one pin each for your red, green, and blue cathodes. It can be used with RGB LED strips or collections of individual LEDs, but it can only drive one color at a time. If you're looking for individually addressable LED control you should look elsewhere.

 

The input power terminals are of the very simple press to insert friction hold type. They seem quite secure, and should be safe to rely on even without providing some sort of strain relief on the wires themselves. The output power terminals are a little more robust, they're spring tensioned friction hold terminals, and they provide a good strong hold on the wires. I was a little concerned when I first saw these, but none of the wires seem interested in coming loose even after repeated insertions.

 

The datasheet says the driver can safely deliver 700mA per color, with a peak safe value of 1 A per color line, so you've got a lot of power to work with here. In my early testing it easily lit an entire 5 meter length of LED strip light without complaint, even when asked to drive the entire roll at full white brightness.

 

There is no Arduino library available for the Infineon board yet, but the development of such a library is an ongoing project associated with this roadtest, so that will likely change soon. Infineon does provide a test program that will walk your lights through a few predetermined colors, and that program is a good resource for understanding how to interact with the board.

 

 

I'll go more into how the Infineon board works in later posts, but essentially all the Arduino has to do is perform I2C writes of the parameters you want the LEDs set to. The Infineon board does the rest. The sorts of parameters you set are the brightness fade time, the walking time for going from one color to another, and the intensity of the red, green, and blue LED channels.

 

So, for example, if you want to make the lights quickly step back and forth between red and green you would set the fade time to zero, the walk time to something very short (say, half a second) in the void setup() phase of your program, then put two items in your main loop(): one setting red to full and everything else to zero, and another setting green to full and everything else to zero.

 

That's it. No worrying about wait or millis statements to get the transition times right, no bothering with pulse width modulation to get a fade between colors, just set your parameters and you're done. I've only begun putting the board through its paces, but already it seems quite slick.

 

The Infineon board can also report back the actual current state of the LEDs it is connected to using I2C reads, giving you a fully closed control loop for your lights and opening up quite a few possibilities beyond the simple web-enabled christmas ornaments I'm currently working on.

 

...next, we'll tackle the software aspect of this roadtest, and begin work on the meat of the project itself. But that's another blog post.

I've only had a few more days to play with my Arduino and I am loving it! This is my very first time with Arduino so it's definitely been baby steps for me. My next step after running a sketch to control the LED on Pin 13 was connecting up a set RGB LED lights that are individually addressable.

Thanks to the help from peteroakes  I was able understand what power requirements I had, and finally got to power something more flashy! I used the Adafruit Neopixel Library and had the lights working in minutes! They are extremely bright and this string of 60 LEDs alone will definitely be able to light up my apartment!

 

Next step is deciding what type of sensors I want to use to trigger my setup The plan is to use a PIR sensor to react to people walking near it and a sound sensor to react to the music!

Hoping to make some progress on this before the new year but was unable to fly any of this hardware away with me for the holiday. I was too worried about getting hastled in customs!

 

 

List of related posts

 

 

The Post!

In my previous post, I had reviewed the Infineon Shield. In this post I just want to present everyone with a christmas present. I converted the Sample Code from the Infineon site into a library and its available for use by anyone. I also provided an example program to get started and I forked some code from Peter Oakes' Post as well but the colors did not match for me so I will tweak it later. Without further ado, the code is available at:

 

https://github.com/inderpreet/infineonrgb_shield

 

The download the zip into the libraries folder of your project and restart the arduino IDE. The library should appear along with the example code.

lib.jpg

 

I have abstracted the functions and have tried to make them human usable.

 

Hope this helps!

 

Happy Holidays Everyone,

Cheers,

IP

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.

In the fourth post I used the Linux part of the Yun to get at the current date and time.


I have now found a stepper motor to drive my wreath's optical filter.

Photo 23-12-14 23 28 16.jpg


The quest for a motor


I have a few dc motors in my scrap parts box,and a small servo motor. I 'm looking for something with a more mechanical look and feel. I want a gearbox in my design.

I opened an old car cassette player and a defect flatbed scanner.

F003_IMG_3460.JPG IMG_3466.JPG


Because I don't have the correct sized Torx driver, I couldn't get at the mechanism without getting medieval. I was more lucky with the scanner.

It 's easy to open (this one particularly because it has been dropped from a few stairs by one of my children a while ago).



I was able to get the motor out with the gear mechanism intact. It's a Neocene stepper motor. There's loads of info available on the internet on this motor and how to drive it.


Driving the stepper motor


I've been looking for several options. I could recover the driver chip from the scanner PCB, or build my own H-Bridge. I had just enough old school transistors available to build a prototype on breadboard.

hbridgeScan 1.jpg

The breadboarded example worked. I then decided to move the circuit over to the smallest protoboard I had available.

And that's when Murphy joined the party

IMG_3476.JPG


You can't see it because of the silkscreen, but this protoboard (the top one on the photo above) is not what it seems. Even though it looks similar to the one on the bottom, the top one has pads connected in groups of 3.
Of course, I didn't spot that while building up my circuit, so it only showed up when I was measuring the circuit before first power on.

The transistors were parts I had recovered from an old tape deck. The pins didn't survive my attempt to desolder them this time.

So I made a shopping list for new components (using European style transistors of the BD13X family).

hbridgeScan2.jpg

This morning I went to the local electronics shop (yes, open the day before xmas eve) with my list.

Turns out that they have a Velleman motor kit available.
The price difference between the kit and a set of loose components with stacking headers was not big.

So I decided to give myself a treat for xmas and bought my own presdent: the KA03 motor kit.

Photo 24-12-14 11 40 49.jpg



I was planning to use spare components as much as possible for the design, but I gave in this time. I'll be able to recover the motor driver for later use.
I'll spend part of my xmas holiday on building a Velleman kit. That's the first time since the mid-80's.

Christmas Sparkle Ball

 

Prelude

 

    With Christmas coming around the corner, our family likes to get together and make a project for fun and games. My sister did this a few years back and challenged me to improve on it. So here is out idea. Take some solo cups from the store. Add some LED's and computer know how to build the Sparkle Light Christmas Ball. This can get the young and the young in heart  working to make this project. Here is a picture of hers she built with the controller (Thanks for the pictures Mary):

 

 

Sister Lights.jpg                                                                                              Sister controller.jpg

 

The Plans

 

    So starting from my sisters build, I am going to use round balls and the Infineon shield to control the lights. This should allow me to control the colors and intensity/warmness of the lights. By connecting the shield through the Yun, remote control should be possible using a mobile phone/computer. I would like to add a mirror or two behind the lights with a sting of lights for effects using the Uno. I will construct it myself. 

Here is the 600 dollar retail version from Amazon:


5139hwrNTsL.jpg


   

    Of course what would Christmas be without a few ornaments? The plan is to build them from cups like these:


                                                      coloring cups.jpg



The Parts

 

    Enter my Santa's helpers. First to show is Donner Yun who loves to dance on clouds:



donner.jpgYun.jpg



         

    The next is Vixen Uno who reads too much:


vixen.jpgUno.jpg



    And finally Dasher Infineon shield who strength carries everyone along :



dasher.jpgRGB.jpg

              

 

Where do you come in?

 

I would like to propose that YOU get involved. Maybe you have done a project you like to share. At some point I will take all ideas added as comments and do a poll to see what the community thinks. So time for the eggnog and Christmas cookies. Let us enjoy the Christmas spirits of giving and thanks for the blessing we have. Also I would like to give a big thank you to Element 14, MCM, Arduino, and Infineon for providing the kits for this roadtest.



          Happy Holidays and a Merry Christmas

          
Hello and thank you to all the competitors in the Internet of Holiday Lights RoadTest Plus. We are now offering a prize for Minion of the New Year, but first...
The Minion of the Holiday Rush
It has been an enormously tough decision to award our first Minion, but after careful consideration, we've given Jerry to Mohan Palanisamy, in particular for this outstanding use of IoT technology in holiday decorations. Many congratulations!
And now...Minion of the New Year:
To step into 2015 with style, we're offering Dancing Dave:
Dancing Dave
The competitor who produces the most informative, entertaining and content rich blog(s) between now and Friday, January 16, 2015 will receive him as a prize.  Hopefully his rhythm will add a salubrious beat to the start of the new year.
Any questions, as ever, please let me know. Happy Holidays!
"Minions" & Despicable Me © 2014 / 2015 Universal Studios. All Rights Reserved.


WELCOME BABY TRINKET

 

Back to the beginning BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights

 

Great news from the Arduino Cartel

 

Senior members of the cartel, Mr and Mrs YUN have a new baby, named Trinket, she is very small and young. as a consequence she has not learned much yet but I wanted to introduce her as she will be at the party so with help from several minions, we will endeavour to train educate her as best we can before the party,

 

She has already learned how to wow the parents with her Big colourful eyes so who knows what else she will learn between now and the party

 

We have not been privy to a full picture of Trinket yet but have seen fragments

 

This is what we have seen of Trinket so far and here is where she was created, oh er I mean born : https://learn.adafruit.com/introducing-trinket/introduction

 

 

 

 

 

 

 

 

 

 

 

It was a perfect creation, with those big colourful eyes


NeoPixel Ring - 16 x WS2812 5050 RGB LED with Integrated Drivers

NeoPixel Ring - 16 x WS2812 5050 RGB LED with Integrated Drivers

 

Not sure about the nostrils though...ugghhh

P1010320.JPG

 

and parents really should think twice about those soother things

189-03.jpg

 

As a further treat I was able to capture some footage of her asleep but we woke here and we had to leave before we got a good look, here is what we captured

 

Here is the current sketch, evolved from the one she came with as she has learned new tricks

 

Trinket is based on an ATTINY85 so IO is limited and so every pin counts

 

I will be using one for the NEOPIXEL rings, one for the PIR and two for the range sensor, that leaves me one pin spare... oh what to do with it , maybe a voice ?????


MQTT Server on the Arduino YUN

 

Back to the beginning BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights


In this episode leading up to the final party of the year we look at running the MQTT Server directly on the YUN, there are numerous posts where this is running on a VM on a PC or on another more capable device but truth be known, it will run perfectly well on the YUN OpenWRT  Linux kernel directly, With the help from Mrs YUN,  ill show you how


A video if you prefer (Oh, and I kept it under a half hour )

 

 

Or the text version for those so inclined to read , you know who you are

 

First thing is to update the Yun, use a wireless device or connect via the Ethernet port

(Wireless you look for the YUN SSID and connect, no code needed, then browse to "arduino")

(Ethernet, browse to the ip address or connect to arduino.local )

log in with the default password "arduino", the following screen is after the upgrade (Sorry, the video contains the original )

click configure and fill in for your local network

Set your time zone (Apparently Canada is part of America... who knew, so to find Toronto you need to select "America, Toronto), you don't need to change the password but do so if you wish

If your planning on using the REST interface and don't want it to be secure (No Password prompt when you try to access the rest interface), then also check "OPEN"

Then click on "Configure & restart"

 

I had to repeat this a few times before it stuck (Or I finally got the WIFI password right, one or the other )

 

anyway, once it is connecting to the local intranet (Home network), you should be able to connect using the url "HTTP://arduino.local", if this does not work, you may need to look at your router so see the IP address assigned to it and connect directly via the IP address "HTTP://192.168.nnn.nnn" or what ever your network is configured for. once you connect you will see a screen similar to that shown above, you may have different IP address of course.

 

After setting up the YUN via the WEB browser to configure it to connect to your local internet connection via WIFI or use the Ethernet port (Where's the fun in that)

 

Given your successful you should be able to SSH into the Linux side of the board. I use a program called PUTTY (Down load from PuTTY: a free telnet/ssh client  ), the screen below show the start screen and how I configure it for my instance of a YUN. Saving the setting makes life so much easier later on

on connection you will be presented with a logon prompt, enter "root" for the logon name followed by "arduino" for the password

 

you should have a screen like the one below but without the mosquitto (MQTT) stuff at the bottom, note the date of the core version

BusyBox v1.19.4 (2014-11-13 19:03:47 CET), if yours is not at this level or newer, you may need to upgrade, I have two YUN's and one would work without upgrade, one would not, neither where at this date revision but all had the same version (v1.19.4) so I guess they don't update the version numbers for over a years worth of updates.so if things don't work and your not at this version, upgrade, it is very painless and I will have a video below (To Follow) to show how easy it is.

 

So once were here we can proceed to install the required software, this is available at the Mosquitto.org website "Mosquitto on OpenWrt | Mosquitto" simply follow the instructions

 

opkg update
opkg install mosquitto mosquitto-client libmosquitto



and your ready to roll, just type "mosquitto" at the command prompt and your broker is ready and running

here is the screen show of those steps

using the samples provided on the mosquitto MQTT site, it is easy to test the servers operation (See here: Documentation | Mosquitto )

once subscribers and publishers start to use the server, it will print messages on the console as shown below

I set up a raspberry pi with MQTT client and published a few events to the YUN as shown here, it also had a second console subscribed to only the humidity topic (Was on temperature to start with)

The YUN console subscribed to a wild card topic using "oakesclan/#" and received every publication as shown (# is a wild card for MQTT topics)

So, there you have it, the Arduino YUN does not need a separate server to support MQTT, it is more than able to host the server itself and have numerous consoles running at the same time, in the next post I will be getting the Arduino side of the YUN to subscribe to the Linux side MQTT server and have it react to commands sent to the MQTT broker, at a later stage I will also try to configure the server to bridge to the Eclipse sandbox, extending the reach of the party.


Now Mrs YUN is ready to relay messages between all the guest who want to talk and those who will listen, now we need radios for the none network connected guests.

Element14.png

List of items:

1)  Arduino Uno or Yún

     + Ethernet Shield W5100 R3 for Arduino Uno

     + MQ2 and MQ135 Smoke Gas Sensor

     + DHT11 Temperature Sensor

     + Flame Firelight Sensor Module

2)  Arduino Yún

     + Infineon Lighting RGB LED Arduino Shield (to connect RGB strip LED)

     + 2-Channel 5V Relay Module for Arduino (to connect lamp)

     + HC-SR04 Ultrasonic Ranging Detector Sensor for Arduino

     + USB webcam

 

 

My idea:

 

My idea is to create a management system for a smart house, in particular as regards the entrance area of the house.

With this system I can go to manage:
a) [1) Arduino Yún + ..] Video surveillance with selective events: when a person approaches the front door, the ultrasonic sensor detects, then Infineon Light RGB LED shield illuminates with white strips inside the room, with relè the external light to illuminate the door, active surveillance taking pictures and / or video recording (streaming), all for a certain time interval.
b) [1) Arduino Yún + ..] if it isn't on a "presence at the door", the LED strips are programmed to create relaxing effects or manifest according shades of blue and red the temperature currently present in the room.
c) [2) Arduino Uno(or Yún) + ..] detect temperature, humidity, presence of harmful gases and flame lit the stove and transmit the data in real time via MQTT.

In this way, with a dedicated web interface I can to have full control of the focal point of my house, checking parameters and real-time operation, guaranteeing me so that everything is in total safety. In fact I can be alerted with push notifications when particular events occur as abnormal temperatures, harmful gases or unexpected visits!

 

For the management of communications between the various nodes of the system will use the protocol MQTT going to take advantage of the wonderful tools provided by the Eclipse IoT Platform as I will list below.




First job preview: I installed in my VPS (Virtual Private Server | running Ubuntu) mosquitto (http://mosquitto.org/) through the following commands:


sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto-ppa


 

The next steps towards the realization of the project in the next post ... see you soon!

The Internet of Holiday Lights

(The Santa monitor & lights -  part-1)



              Hello there "Internet of Holiday Lights" road-testers, kids and enthusiasts! Though i wasn't quite able to make an instant blogging after i've first got the kits, hope it is not too late to start describing my whole idea for the "Internet of Holidays Lights" project now. This part will represent the general presentation of the products i'm going to use for this wonderful and interesting project. I've always wanted to catch and see how Santa Claus looked like (the real deal ), so i've initiated a very sneaky plann with the help of the secret element14 technology, to catch Santa once and for all. Let's see whatcha gonna do now Santa!



The "Trio"

 

2014-12-17 12.34.59.jpg

Arduino YUN, Arduino UNO and Infineon Lighting RGB LED Arduino shield

 




The "Lights"


IMG_0255.JPGIMG_0256.JPGIMG_0257.JPGIMG_0261.JPGIMG_0263.JPGIMG_0262.JPGIMG_0264.JPGIMG_0266.JPG


Just a small demo with Arduino Uno + Infineon + I2C Dave demo program for the Christmas sake.



   



    Just bought three affordable & simple rgb led strips operating at 12V. On a closer inspection, each led was seried with a 561 ohm resistor and each strip used a common "+" and three "-" pins. I got to light the strips easily with a 1 Amp/12V DC transformer that was lying around my desk. All the led's seemed to be ok (no faulty one - though it was of RPC product). These lights will be controlled and triggered by Infineon shield and Arduino YUN/UNO - i will try to make use of IOT Eclipse platform, thanks to kartben's good example.

 

 


The "Hook up"


    Oh man, decisions...decisions. Finally got up to the idea that combining male and female pin headers would be a decent fix for the height issue in Arduino YUN/Infineon shield hook up.


IMG_0250.JPGIMG_0247.JPGIMG_0251.JPGIMG_0252.JPGIMG_0254.JPG




The "Call?"


    No pictures available in this section yet, though the idea is to use sensors to trigger a "melody" when Santa is close to the door and if it snows. I was initially thinking in using a "hohoho" circuit for proximity sensor and a "slow chillout carol" when it starts to snow for the laser/ir sensor. These sensors will be controlled by Arduino UNO. The bad news is that snow will come here by the late of january...hope soon enough to get the demonstration going before final call of the roadtest.



The "Who/Where?"


  First of all i would like to decorate some windows giving the fact that the led strips have sticker tape on them, then an aquarium or a lamp (couldn't find yet a decent priced aquarium - it's possible to go for a vibe lamp if i can't pull that other one off). As for the exact location of the deployment of my project, i'm not quite sure right now, as i have many options to take into account.  Here are some suggestions though:

IMG_0241.JPGIMG_0244.JPGIMG_0242.JPGIMG_0243.JPG







Coming soon: The Santa monitor & lights - (T.I.O.H.L.)part-2

List of related posts

 

 

Prelude

LED stands for Light Emitting Diode and it is a Semiconductor Device which when forward biased, produces light. The LED is predicted to replace all light bulbs etc since it consumes less power and offers a more compact product. The heat produced is also less at the same brightness compared to other sources. But unlike traditional bulbs, the LED cannot be simply plugged into a wall socket. It runs on a lower voltage and in order to elongate its life AND do some brightness control etc, we need a circuit which is called an LED drivers. This document is a review of the Infineon LED driver Shield which can be controlled by an arduino and is useful for a lot of projects.

 

 

LED Driver?

Just like a normal diode, we can plot the current and voltage characteristics of LED. I googled it and came up with the following.

 

diode12.gif

http://www.electronics.dit.ie/staff/tscarff/DT089_Physical_Computing_1/LEDS/LED_Characteristics.gif

 

It is easily seen that after a certain voltage, as the voltage is increased, the current increases drastically. Larger current equal to a larger brightness change..This can also cause heat dissipation by

 

P = R x (I^2) = V x I

 

which means I can blow up my LED quite easily. I need a way to control the current through the LED and keep the current at a constant value. So how can I do that? The simplest way I have been making constant current sources has been the LM317 and the circuit looks like...

 

Image.png

 

The 1.25 is due to the internal reference but I wont go into the details because the problem here is that this circuit is based on a linear regulator and is not very efficient nor does it offer digital control.

So how else can I control the current? The simple answer is PWM.

 

PWM Stands for Pulse Width Modulation and simply put, we switch the LED ON and OFF really quickly for a variable duration of time. The longer we switch it on, the longer the current flows and larger the average current and brighter the LED. Take a look at the image below.

 

diode44.gif

(http://www.electronics-tutorials.ws/diode/diode44.gif)

 

So my arduino can do that by default. There are PWM modules in built right? So whats wrong with that? Well you can switch the LED ON and OFF using the Arduino and you could probably do it using say a 555 in an astable mode too. I have used this circuit for some time now where I need variable brightness of the LEDs

Image.png

For a circuit explanation see the video below

 

 

 

The problem with using the 555 is the switching speed. The slower the switching, the more prone to flicker in the LED. The second problem which is common with the arduino switcher is that we have no way of knowing what current is being drawn. Remember we need a constant current and if say one of the LEDs is shorted out, then we have no way of knowing about it and it might even damage the MOSFET. Yikes!

 

The solution is adding a small resistor say 1 Ohm in series with the LED and then use an Op-AMP to monitor the voltage across it. By Ohms law, if there is a drop of 1 volt across the resistor then there must be 1 amp flowing through it! We can read it using an analog pin and then do that for every LED strip and then... aawwwhh. Thats a lot of work!

 

The LED driver shield simplifies this process.

 

What is the XMC1202?

The XMC1202 is an ARM Cortex-M0 based micro-controller which has a dimming control peripheral for LED lighting applications, known as the Brightness and Colour Control Unit (BCCU). It contains 3 independent dimming engines and 9 independent Pulse Density Modulated (PDM) channels. 1 dimming engine and 6 channels are used in this shield.

 

What!?

 

Its an ARM Cortex-M0 core with some dedicate for control of LEDS and ADCs to measure the currents like I said before. The block diagram of the Chips is given below.

Image.png

Whats the BCCU?

Take a look at this...

Image.png

This is a slide from http://www.infineonic.org/download/index.php?act=down&id=4166 and is a presentation on the BCCU itself. The point here is that the ADC needs to sample current at the right time and needs to be fast enough. The XMC1202 can do a lot more as well but for people who just want to control the LEDs using an arduino, Infineon put the chip on a circuit, write a firmware on the processor and made it an I2C slave.

 

If you want to program the XMC1202 there is great tutorial by shabaz sir at

RGB LED Shield from Infineon - Getting Started Guide

 

The RGB LED Shield

 

The RGB shield has the XMC1202 IC as well as the required circuitry to drive LED successfully. The circuit looks like...

 

Image.png

Not much to talk about here. Its the same circuit I have discussed and the DMX section is something not mounted nor reviewed. What we can discuss is that the shield uses only 4 pins from the arduino which are voltage, GND, I2C_SCL and I2C_SDA and I can even drive this using my BusPirate. There is some ready code for the shield and I have attached the example code below.

 

Understanding the commands

The user guide has a long table of commands that can be used to control the shield and the LEDs attached. We will take a look at a subset of the commands and how to use them. In order to send these commands to the shield we can write our own functions but the demo code has ready functions. These are essentially running the I2C peripheral on the Arduino so I will use them directly. There are a number of reasons why I want to do this.

 

Firstly, these are tested functions so it will reduce my prototying time. Secondly, I will probably wrap these functions in other functions which will have a more simplistic interface. In the days of C based network programming, I was taught to write these wrapper functions to reduce complexity but it has a second advantage. If I decide to change my platform to say a Launchpad, then I will write my own I2C driving code in Code Composer and wrap it with the same function as my arduino code. That way I dont need to modify my calling code and the transition becomes simpler. This is standard practice when writing protocols and I picked it up when I wrote my first MODBus Client on an 8051. Now I do this most of the time since I will change the platform at will depending upon the cost of the final product I am building and this means my code is reusable across products.

 

OK Back to the Commands. The first command is intensity which is intensity...

 

Image.png

Simply put, the intensity is a 12 bit value which can be changed by calling ..

 

Image.png

This is simple enough... so what else?

 

 

Peak Current Control.

This is important when you know your LEDs cannot handle more than a specific current. The system is as follows and is explained as well.

 

Image.png

 

This is means I can set the max current by...

Image.png

Another parameter is the Walk Time which is used to smoothly change the colour intensities. The intensities change linearly over time. Take a look.

 

Image.png

 

The last thing I want to highlight is the dimming level. We discussed intensity but...

 

"The dimming engine in the XMC1202 microcontroller on-board the RGB LED Shield performs dimming along a pseudo-exponential curve so that the change appears natural to the human eye. This compensates for the eye’s logarithmic sensitivity to light." ... "The brightness value of a channel and therefore the brightness of the connected LED string, is the product of the intensity of the respective channel and the dimming level divided by 4096.

The dimming engine which controls the dimming level is separate from the BCCU channels. This enables the RGB LED shield to control the colour of the LED strings separately from the lamp brightness. The brightness level of the lamp can stay the same while its colour changes. Changes in brightness do not affect the colour of the lamp either."

 

FROM THE USER MANUAL...

 

Simply put, intensity and dimming are associated with changing the color without changing the brightness of the RGB LED and vice versa. Pretty neat! I encourage you to explore this concept to actually see the effect in practice.

 

There are some commands to read the values as well but I won't need them unless I am facing some color problems.

 

 

Tests

I did some basic tests with the shield but I need to do a lot more to report something. I am using this in my project which will be submitted soon and you can judge if the shield does a good job or not.

 

I will link up more associated posts here as I get them done. For now enjoy the holidays.

 

Cheers,

IP

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.

My third post was about getting the Arduino Yun up and running.


This time I'm making the Atmel and Linux part work together to get current date information.


datetimelinux.png


Because I'm changing the state of my gizmo based on the advent calendar, I need to know current date info.


Getting the right time from Linux


I've prepped my Arduino Yun to reflect the right date based on my timezone (Belgium).

timezone_1.png

timezone_2.png


Then I refreshed my knowledge of the Linux date command.

I need the following parameters to get the data I need for my design:

       %d     day of month (e.g, 01)


       %H     hour (00..23)


       %m     month (01..12)


       %M     minute (00..59)


       %u     day of week (1..7); 1 is Monday


       %Y     year





 

Command that I'll submit in Linux: date +%Y%m%d%u%H%M

Result: 2014122212306

 

I used the Arduino.cc Time Check example as a starting point to get all info into the sketch.

That wasn't too difficult. Here's the result:

 

datetimeyun.png

 


Previous Posts in the series

 

Prelude

 

Hackers and hobbyists have used the arduino for a diverse number of projects and have made it a very popular. Its simple to use and easy to program. For people who have a slightly 'more' requirement, ARM based single boards came into the market. Initially the ARM boards were tougher to build and program and costlier to make. In order to fully exploit the power of a 32-bit processor, the Linux Kernel was ported to the fanless ARM systems making the Single Board Computers. The OS was stored on either an SD Card or an EEPROM. This new class of boards had the familiar OS system of a regular PC and the digital and analog outputs of the arduino but at a slightly higher cost. Additionally they had varying performance but they started to add something more- peripherals! Keyboard, then Ethernet, then Bluetooth and Wifi- the list goes on. In this article we discuss the Arduino YUN and what exactly it is.

 

 

Single Board Computers Explained

 

Raspberry Pi, BeagleBone Black and the RIOT Board are some of the more popular names. These run Linux or Android and everything runs on top of that. The OS takes care of the memory management as well as peripheral access. The newer kids on the block are the Intel Galileo and the Yun. Thats right! The Arduino Yun runs linux and we will discuss this a little later. For people who want more power and connectivity such as Wifi for IOT applications, we have offerings such as the Texas Instruments CC3200, CC3100 and the CC3000(used in the spark Core). They lack Linux as an OS(CC3200 can have TI RTOS or FREE RTOS though) but have a lot more power than the arduino.

 

Single board computers have come a long way and the linux that runs on them has also shrunk down. Linux tailor-made for a particular Board can go low as 2-10MB in size without support for floating point math. The point it Single board computers make it easy for the IT people and general people to easily get started with a project. The code also becomes a lot more portable because there is an underlying layer of OS which takes care of driving the peripherals like Wi-Fi. This also means that you can start working with languages such as python and do not have to worry about the kernel or C-programming or driving the peripherals. It is simplified into an import statement. On the flip side if you wish to get down into the pits and write your own C-code(or even assembly) you could prefer options such as CC3200 and the like. Its actually not that bad since manufacturers produces a lot of example code and starter projects for these boards. I usually start with the given code and add or delete parts that I need. This increases the prototyping speed as well as the dependability of the code and if you think thats cheating, please feel free to write device drivers for your systems and your own database management systems and let me know

DSC00447.JPG

 

A comparison of the most popular boards is given at https://learn.adafruit.com/embedded-linux-board-comparison/overview and I will do one myself once I get to setting up some tests.

 

Who is the Yun

The word 'YUN' is a Chinese word and means 'Cloud'. That simplifies the purpose of the board right? The Arduino YUN is a modified Arduino with the number of processing elements upped to two. One is the ATmega 32u4 which is directly accessed via USB and the Arduino IDE. The second is the AR9331 which runs linux and can be accessed via the ethernet/Wifi interface or the BRIDGE. The basic block diagram of the system is shown below. The OS is stored on a 16Mb Flash memory and the processor running it is a Atheros AR9331 @400MHz with 64Mb DDR2. Thats pretty good actually.

yun_by_pighixxx-d6qvbq4.png

(Image : http://fc07.deviantart.net/fs71/f/2013/290/a/e/yun_by_pighixxx-d6qvbq4.png))

 

Another thing I want to clarify is that the Arduino Website says that it runs Linino Linux but the banner says OpenWRT. Linino is based off OpenWRT which is a linux distro meant for Embedded devices which are typically wireless routers. Its a completely different animal and is build ground up to be easily modifiable using modules. In short the YUN is a single board computer with a small amount of RAM and Flash which can connect to the Internet and also has an arduino connected on the same board. This gives you two worlds on the same board and if want to build something with the libraries of arduino and have internet applications connected via python or nodejs or the link this is definitely the board for you. If you want something faster and can spend more, the other kid is the Intel Galileo which runs everything on a 32-bit quark processor which runs arduino sketches and everything else on the same core. But thats a different story.

 

 

Getting started with the YUN

 

There are a lot of good tutorials already on the internet and I try to refrain from rebuilding the wheel hence I will link them below. The only thing I want to point out is that the arduino is quite simple to get started with and its not necessary that you go into the nits and grits of the Linux part. Its designed for people who work with the Arduino and want wifi and a few other facilities and do not want to mess with connectors and addons and stuff. Once you are done with the basics, you can start work on python and nodejs and other stuff. But because the RAM and flash is severely limited, you might want to watch your memory usage. Adafruit has a great tutorial on using the YUN as a networked Cam which means that it can take photos from a USB camera(there is USB HOST controller present) and send it over the network. What you do with it depends on your creativity.

 

There is another tutorial on extending your linux space to the SDCARD and you can store a lot of data on the memcard. The link is given below and if I ever get around to that requirement I will make another post and link it here as well. For now I am more interested in seeing how this little peice of tech can be used for IOT Applications.

 

 

Getting a little more started - Enter Temboo

 

The internet of things means connecting devices to the internet and for the beginners this may seem like a daunting task. With the YUN, I recommend visiting temboo.com .  Temboo is a service which generates code for IOT application tasks such as reading twitter, facebook, dropbox and even google services. The generated code can be in your favourite language such as Java, Python or JS and if you go into IOT mode it will generate code for the CC3200 or the YUN! This allows for simplification of some tasks and then you can build your application around it. Temboo has choreos which are essentially steps for performing a task and the system is pretty simple. The basics  are available at

graphic-arduino-howitworks-2.png

 

 

I am still digging at it and my objective is be able to control the YUN using MQTT however I have a Raspberry Pi which is running OpenHAB and an MQTT server hence all messages are to be generate by the PI. No problem since my RPi can run the same Python or NodeJS script as the YUN so I am currently working on formulating a NodeJS/Python script which is a Choreo from Temboo. More on this in the next post since I am still working out some bugs.

 

 

Conclusion

 

The Arduino Yun is easy to use and for those who want to play with IOT and want to be able to use the Arduino IDE, you can use the Arduino Ethernet. For Wifi connectivity there are other options which will be cheaper than the YUN. The YUN is for people who want to start with Single Board Computers, Linux and want to start scripting and move up to more complicated use cases. Arduino cannot do encryption nor the more processor intensive stuff and thats where the YUN steps in. If you want databases and some multimedia stuff, then move upwards to the RPi or the BBB or RIOT but for people working with mid range IOT applications and have the budget for it, the YUN comes highly recommended. Buy one, make a project and see where that goes...

I have received Arduino Yun, Arduino Uno and Infineon RGB LED control shield...

 

I have used REST api style communication link between my android cell and arduino yun... I have merged bridge example of arduino yun and Infineon RGB LED Shield example for this prototype...

 

I am using processing for Android and PC application...

 

My processing sketch works fine with Android as well as widows/linux PC...

 

In my processing app.. two modes are there,

1. fix (fix color)

2. loop (rotate color)

 

Here is my processing sketch....

 

float r_color=127,g_color=127,b_color=127, rot_color;
float r_bar = width/2,g_bar = width/2,b_bar = width/2, rot_bar = width/2;
float r_yun, g_yun, b_yun, rot_yun = 200;
float rot_status = 0;
float fix_status = 1;
color backgroundcolor = color(50, 50, 0);
String url = "http://192.168.43.27/arduino/";
void setup()
{
  orientation(LANDSCAPE);
  textSize(34);
}


void draw()
{
  background(backgroundcolor);
  drawUI();
//  text("IP = "+ip,20,130);
//text(url+str((int)r_yun),20,170);
}




void mousePressed()
{
// int mouse = (int)mouseX;
if (mouseY > height/6 && mouseY < height/6+60)
{
   if( mouseX > width/3 && mouseX < width/3 + width/6)
   {
     rot_status = 1;
     fix_status = 0;
     String json[] = loadStrings(url + "rot/1/" +str((int)rot_yun));
     println(url + "set/1/" + str((int)rot_yun));
     delay(300);
   }
   if( mouseX > width/3 + width/6 && mouseX < 2*width/3)
   {
     rot_status = 0;
     fix_status = 1;
     String json[] = loadStrings(url + "set/1/" + str((int)r_yun));
     println(url + "set/1/" + str((int)r_yun));
     delay(300);
     String json1[] = loadStrings(url + "set/2/" + str((int)g_yun));
     println(url + "set/2/" + str((int)g_yun));
     delay(300);
     String json2[] = loadStrings(url + "set/3/" + str((int)b_yun));
     println(url + "set/3/" + str((int)b_yun));
     delay(300);
  
   }
}

if( mouseX > 50 && mouseX < width-50)
{
  if (mouseY > 2*height/6 && mouseY < 2*height/6+60 && rot_status == 1)
  {
    rot_color = map(mouseX, 50, width-50, 0, 255);
    rot_yun = map(mouseX, 50, width-50, 0, 4090);
    rot_bar = mouseX-50;
    String json[] = loadStrings(url + "rot/1/" + str((int)rot_yun));
    println(url + "rot/1/" + str((int)rot_yun));
  }
  else if (mouseY > 3*height/6 && mouseY < 3*height/6+60 && fix_status == 1)
  {
    r_color = map(mouseX, 50, width-50, 0, 255);
    r_yun = map(mouseX, 50, width-50, 0, 4090);
    r_bar = mouseX-50;
    String json[] = loadStrings(url + "set/1/" + str((int)r_yun));
    println(url + "set/1/" + str((int)r_yun));
  }
  else if (mouseY > 4*height/6 && mouseY < 4*height/6+60 && fix_status == 1)
  {
    g_color = map(mouseX, 50, width-50, 0, 255);
    g_yun = map(mouseX, 50, width-50, 0, 4090);
    g_bar = mouseX-50;
    String json[] = loadStrings(url + "set/2/" + str((int)g_yun));
    println(url + "set/3/" + str((int)g_yun));
  }
  else if (mouseY > 5*height/6 && mouseY < 5*height/6+60 && fix_status == 1)
  {
    b_color = map(mouseX, 50, width-50, 0, 255);
    b_yun = map(mouseX, 50, width-50, 0, 4090);
    b_bar = mouseX-50;
    String json[] = loadStrings(url + "set/3/" + str((int)b_yun));
    println(url + "set/3/" + str((int)b_yun));
  }
}
}




void drawUI()
{
  pushStyle();
  textAlign(CENTER);
  stroke(255);

  //fill(color(r_color,g_color,b_color));
  //rect(width/3, 1*height/6, width/3, 60);

  fill(rot_status * 200);
  rect(width/3, 1*height/6, width/6, 60);

  fill(fix_status * 200);
  rect(width/3 + width/6, 1*height/6, width/6, 60);
  if(rot_status == 1)
  {
  fill(color(100,200,200));
  rect(50, 2*height/6, width-100, 60);

  fill(color(50,100,100));
  rect(50, 2*height/6, rot_bar, 60);

  fill(0);
  text("SPEED", width/2, 2*height/6+43);
  }

  if(fix_status == 1)
  {
  fill(color(r_color,g_color,b_color));
  rect(width/3, 2*height/6, width/3, 60);

  fill(color(255,0,0));
  rect(50, 3*height/6, width-100, 60);
  fill(color(0,255,0));
  rect(50, 4*height/6, width-100, 60);
  fill(color(0,0,255));
  rect(50, 5*height/6, width-100, 60);

  fill(color(r_color,0,0));
  rect(50, 3*height/6, r_bar, 60);
  fill(color(0,g_color,0));
  rect(50, 4*height/6, g_bar, 60);
  fill(color(0,0,b_color));
  rect(50, 5*height/6, b_bar, 60);

  fill(color(255-r_color,255-g_color,255-b_color));
  text("COLOR", width/2, 2*height/6+43);
  }



  fill(255);
  text("IoT Holiday Lights", width/2, 60 );
  fill(0);
  text("LOOP", width/3 + width/12, height/6+43);
  fill(0);
  text("FIX", width/3 + width/6 + width/12 , height/6+43);

  popStyle();
}








 

Here is my arduino yun sketch... Still clean up of code is not done.... Sorry for that...

 

/*
  Arduino Yún Bridge example


This example for the Arduino Yún shows how to use the
Bridge library to access the digital and analog pins
on the board through REST calls. It demonstrates how
you can create your own API when using REST style
calls through the browser.


Possible commands created in this shetch:


* "/arduino/digital/13"     -> digitalRead(13)
* "/arduino/digital/13/1"   -> digitalWrite(13, HIGH)
* "/arduino/analog/2/123"   -> analogWrite(2, 123)
* "/arduino/analog/2"       -> analogRead(2)
* "/arduino/mode/13/input"  -> pinMode(13, INPUT)
* "/arduino/mode/13/output" -> pinMode(13, OUTPUT)


This example code is part of the public domain


 http://arduino.cc/en/Tutorial/Bridge


*/


#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
#define ADDRESS                    0x15EUL

  #define INTENSITY_RED              0x11U
  #define INTENSITY_GREEN            0x12U
  #define INTENSITY_BLUE     0x13U
  #define INTENSITY_RGB              0x14U
  #define CURRENT_RED                0x21U
  #define CURRENT_GREEN              0x22U
  #define CURRENT_BLUE               0x23U
  #define CURRENT_RGB                0x24U
  #define DMXOFF     0x30U
  #define DMXON                 0x31U
  #define DMXSLOT     0x32U
  #define DMX8BIT                    0x33U
  #define DMX16BIT                   0x34U
  #define OFFTIME_RED                0x41U
  #define OFFTIME_GREEN              0x42U
  #define OFFTIME_BLUE     0x43U
  #define WALKTIME                   0x50U
  #define DIMMINGLEVEL               0x60U
  #define FADERATE                   0x61U
  #define _CHANGE_ADDRESS            0x70U

  #define READ_INTENSITY_RED         0x81U
  #define READ_INTENSITY_GREEN       0x82U
  #define READ_INTENSITY_BLUE        0x83U
  #define READ_CURRENT_RED           0x84U
  #define READ_CURRENT_GREEN         0x85U
  #define READ_CURRENT_BLUE          0x86U
  #define READ_OFFTIME_RED           0x87U
  #define READ_OFFTIME_GREEN         0x88U
  #define READ_OFFTIME_BLUE          0x89U
  #define READ_WALKTIME              0x8AU
  #define READ_DIMMINGLEVEL          0x8BU
  #define READ_FADERATE              0x8CU
  #define DIRECTACCESS_READ          0x90U // read twice
  #define DIRECTACCESS_MOVE       0x91U
  #define DIRECTACCESS_AND           0x92U
  #define DIRECTACCESS_OR            0x93U

  #define SAVEPARAMETERS             0xA0U

  #define BCCUMODID                  0x50030008U
  #define CHIPID                     0x40010004U
  #define REDINTS                    0x500300A0U // BCCU_CH5
  #define REDINT                     0x500300A4U
  #define BLUEINTS                   0x50030078U
  #define STARTWALK                  0x50030018U

  #include <Wire.h>

  unsigned int c[2] = {0};
  unsigned int d[4] = {0};
  unsigned int on = 0;
  unsigned int message = 0;
  unsigned long redcurr = 0;
  unsigned long greencurr = 0;
  unsigned long bluecurr = 0;
  unsigned long redoff = 0;
  unsigned long greenoff = 0;
  unsigned long blueoff = 0;
  unsigned long redint = 0x00;
  unsigned long greenint = 0x00;
  unsigned long blueint = 0x00;
  unsigned long fadetime = 0x00;
  unsigned long walk = 0x00;
  unsigned long brightness = 1;

  unsigned int r_send = 2048;
  unsigned int g_send = 2048;
  unsigned int b_send = 2048;
  unsigned int rot = 0, rot_delay = 500;


// Listen on default port 5555, the webserver on the Yún
// will forward there all the HTTP requests for us.
YunServer server;


void setup() {
  Serial.begin(9600);
  Wire.begin();
  Shield_init();
  I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, r_send); // RED
  I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, g_send); // GREEN
  I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, b_send); // BLUE
  // Bridge startup
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  digitalWrite(13, HIGH);
  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  server.listenOnLocalhost();
  server.begin();
}


void loop() {
  // Get clients coming from server
  YunClient client = server.accept();


  // There is a new client?
  if (client) {
    // Process request
    process(client);


    // Close connection and free resources.
    client.stop();
  }
  if(rot==1){led_rotate();}
  delay(20); // Poll every 20ms
}


void process(YunClient client) {
  // read the command
  String command = client.readStringUntil('/');


  // is "digital" command?
  if (command == "set") {
    setCommand(client);
  }


  // is "analog" command?
  if (command == "rot") {
    rotCommand(client);
  }


  // is "mode" command?
  if (command == "mode") {
    modeCommand(client);
  }
}


void setCommand(YunClient client) {
  int set_clr,value;


  // Read color number
  set_clr = client.parseInt();
  // Read intensity
  if (client.read() == '/') {
    value = client.parseInt();
  }
  client.print(F("color="));
  client.print(set_clr);

  if(set_clr == 1){r_send = value;}
  else if(set_clr == 2){g_send = value;}
  else if(set_clr == 3){b_send = value;}
  rot = 0;
  I2CWRITE2BYTES (ADDRESS, WALKTIME, 48);
  I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, r_send); // RED
  I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, g_send); // GREEN
  I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, b_send); // BLUE

  // Send feedback to client


}


void rotCommand(YunClient client) {
  int value;
  // Read pin number
  rot = client.parseInt();
  if (client.read() == '/') {
    value = client.parseInt();
  }
  I2CWRITE2BYTES (ADDRESS, WALKTIME, value/14);
  rot_delay = value;
  // Send feedback to client
  client.print("rotation = ");
  client.print(rot);

}


void modeCommand(YunClient client) {
  int pin;


  // Read pin number
  pin = client.parseInt();


  // If the next character is not a '/' we have a malformed URL
  if (client.read() != '/') {
    client.println(F("error"));
    return;
  }


  String mode = client.readStringUntil('\r');


  if (mode == "input") {
    pinMode(pin, INPUT);
    // Send feedback to client
    client.print(F("Pin D"));
    client.print(pin);
    client.print(F(" configured as INPUT!"));
    return;
  }


  if (mode == "output") {
    pinMode(pin, OUTPUT);
    // Send feedback to client
    client.print(F("Pin D"));
    client.print(pin);
    client.print(F(" configured as OUTPUT!"));
    return;
  }


  client.print(F("error: invalid mode "));
  client.print(mode);
}
void I2CWRITE2BYTES (int Address, int Command, unsigned int Data)
  {
    unsigned int upperByte, lowerByte; // Separate 4 byte data into 2 byte values
    lowerByte = Data;
    upperByte = Data >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // Putting address into correct format
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD)); // Start I2C transmission
    Wire.write(byte(lowerSLAD)); // address lower 8 bits of i2c address
    Wire.write(byte(Command)); // write command
    Wire.write(byte(upperByte)); // write data
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);
   
  }
   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   int Command - Defined I2C Commands i.e. INTENSITY_RGB, CURRENT_RGB
                   unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree - Three 16bit data to be written to slave
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 6 bytes of word to the I2C bus line
  */

  void I2CWRITE6BYTES (unsigned int Address, unsigned int Command, unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree) // DataOne: Red, DataTwo: Green, DataThree: Blue
  {
    unsigned int upperByte, lowerByte; // Split each Data parameter into upper and lower 8 bytes because I2C format sends 8 bytes of data each time
    lowerByte = DataOne;
    upperByte = DataOne >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    lowerByte = DataTwo;
    upperByte = DataTwo >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    lowerByte = DataThree;
    upperByte = DataThree >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);
   
  }

/*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   int Command - Defined I2C Commands i.e. DMX16Bit
                   unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree, usigned int DataFour, unsigned int DataFive - Three 16bit data to be written to slave
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 12 bytes of word to the I2C bus line
  */

  void I2CWRITE12BYTES (unsigned int Address, unsigned int Command, unsigned int DataOne, unsigned int DataTwo, unsigned int DataThree, unsigned int DataFour, unsigned int DataFive, unsigned int DataSix) // DataOne: Red, DataTwo: Green, DataThree: Blue
  {
    unsigned int upperByte, lowerByte;
    lowerByte = DataOne;
    upperByte = DataOne >> 8;

    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command)); // write command
    Wire.write(byte(upperByte)); // write 2 bytes
    Wire.write(byte(lowerByte));

    lowerByte = DataTwo;
    upperByte = DataTwo >> 8;
    Wire.write(byte(upperByte)); // write next two bytes
    Wire.write(byte(lowerByte));

    lowerByte = DataThree;
    upperByte = DataThree >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataFour;
    upperByte = DataFour >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataFive;
    upperByte = DataFive >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));


    lowerByte = DataSix;
    upperByte = DataSix >> 8;
    Wire.write(byte(upperByte));
    Wire.write(byte(lowerByte));
    Wire.endTransmission(true);
   
  }

   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   int Command - Defined read I2C Commands i.e. READ_INTENSITY_RED, READ_INTENSITY_GREEN, READ_INTENSITY_BLUE
  Parameters (OUT): None
  Return Value: Requested data from Shield will be sent back
  Description: This function will request 2 bytes of word from the shield
  */

  unsigned int I2CREAD (unsigned int Address, unsigned int Command) // Returns data sent by slave
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.requestFrom(upperSLAD, 2, true);
    unsigned int data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      message = 1;
      c[i] = Wire.read(); // receive a byte as character
      i++;
   
    }
    Wire.endTransmission(true);

    data = c[1]; // write data to serial monitor. c[1] is higher byte
    data = (data << 8) | c[0];  // shift left and combine with lower byte
    Serial.print("0x");
    if (data < 0x1000)
        Serial.print("0");
    Serial.println(data, HEX);
    return data;
  }

   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   int Command - DIRECTACCESS_READ
  Parameters (OUT): None
  Return Value: Requested data from the Shield will be returned
  Description: This function will request 4 bytes of data from shield.
  */

unsigned long I2CREAD_DIRECTACCESS (unsigned int Address, unsigned int Command, unsigned long registerAddress)
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // sending command + address
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));

    unsigned int firstByte, secondByte, thirdByte, fourthByte;
    firstByte = registerAddress >> 24; // top byte
    secondByte = registerAddress >> 16;
    thirdByte = registerAddress >> 8;
    fourthByte = registerAddress; // bottom byte

    Wire.write(byte(firstByte));
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));

    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD)); // request for read
    Wire.write(byte(lowerSLAD));
    Wire.requestFrom(upperSLAD, 4, true);
    unsigned long data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      d[i] = 0;
      d[i] = Wire.read(); // receive a byte as character
      i++;
    }


    Wire.endTransmission(true);

    data = d[3]; // combining into one variable. Highest byte received first
    data = (data << 8) | d[2];
    data = (data << 8) | d[1];
    data = (data << 8) | d[0];
    Serial.print("0x");
    if (data < 0x10000000)
        Serial.print("0");
    Serial.println(data, HEX);
    return data;
  }
   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   int Command - Defined I2C Commands i.e. DIRECTACCESS_OR, DIRECTACCESS_AND, DIRECTACCESS_MOVE
                   unsigned long registerAddress - address of target register
                   unsigned long Data - 32 bits data to be written to register
  Parameters (OUT): None
  Return Value: None
  Description: This function will write 4 bytes of data to specified register
  */
  void I2CWRITE_DIRECTACCESS (unsigned int Address, unsigned int Command, unsigned long registerAddress, unsigned long Data) // For accessing registers directly
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // sending command + address
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));

    unsigned int firstByte, secondByte, thirdByte, fourthByte; // Send address of register first
    firstByte = registerAddress >> 24; // top byte
    secondByte = registerAddress >> 16;
    thirdByte = registerAddress >> 8;
    fourthByte = registerAddress; // bottom byte

    Wire.write(byte(firstByte));
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));

    firstByte = Data >> 24; // top byte
    secondByte = Data >> 16;
    thirdByte = Data >> 8;
    fourthByte = Data; // bottom byte


    Wire.write(byte(firstByte)); // send 4 bytes of data
    Wire.write(byte(secondByte));
    Wire.write(byte(thirdByte));
    Wire.write(byte(fourthByte));
    Wire.endTransmission(true);

  }
   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   unsigned int newAddress - Address the shield should change to
  Parameters (OUT): None
  Return Value: None
  Description: This function will change the I2C address of the slave
  */

  void CHANGEADDRESS (unsigned int Address, unsigned int newAddress)
  {
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79; // First 5 bits 11110 and last bit '1' for a write
  
    Wire.beginTransmission(byte(upperSLAD)); // Red
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(0x70)); // Command to change address
    lowerSLAD = (unsigned int) (newAddress & 0x00FF);
    upperSLAD = newAddress >> 7; // Split address into 2 bytes
    upperSLAD |= 0xF0; // 10 bit addressing: First 5 bits have to be 11110.
    upperSLAD &= 0xFE;
    Wire.write(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.endTransmission(true);
  }

   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
                   unsigned int Command - DMXON, DMXOFF
  Parameters (OUT): None
  Return Value: None
  Description: This function will enable or disable DMX512 control on shield
  */

  void I2CDMX (unsigned int Address, unsigned int Command) // Switch off / on the DMX
  {
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF); // Putting address into correct format
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD)); // Start I2C transmission
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(Command));
    Wire.endTransmission(true);

  }
   /*
  Parameters (IN): int Address - Address of RGB LED Shield, Default 0x15E
  Parameters (OUT): None
  Return Value: None
  Description: This function will request the shield to save configurations to flash memory
  */

  void I2CSAVEPARAM (unsigned int Address)
  {
    int i = 0;
    unsigned int lowerSLAD = (unsigned int) (Address & 0x00FF);
    unsigned int upperSLAD = Address >> 8;
    upperSLAD |= 0x79;

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD));
    Wire.write(byte(SAVEPARAMETERS)); // write SAVEPARAMETERS command
    Wire.endTransmission(false); // false for Repeated Start

    Wire.beginTransmission(byte(upperSLAD));
    Wire.write(byte(lowerSLAD)); // write to address lower 8 bits of slave address
    Wire.requestFrom(upperSLAD, 2, true);  // send READ request with upper slave address
    unsigned int data = 0;

    while(Wire.available())    // slave may send less than requested. Print out received data byte
    {
      message = 1;
      c[i] = Wire.read(); // receive a byte as character
      i++;
    }
    Wire.endTransmission(true); // STOP condition

    data = c[1]; // print the data on serial monitor
    data = (data << 8) | c[0];
    Serial.print("0x");
    if (data < 0x1000)
        Serial.print("0");
    Serial.println(data, HEX);

  }


  void Shield_init()
  { 
    //while(!Serial);
    while (on != 1) // Wait for shield to respond
    {
      I2CDMX (ADDRESS, DMXOFF); // disable DMX
      I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Immediate fade
      I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // 0% brightness level
      on = I2CREAD(ADDRESS, READ_DIMMINGLEVEL); // Request for brightness level
      if (message == 1 && on == 0) // If message received and brightness level = 9%
      {
        message = 0;
        on = 1; // break out of loop
      }
    }

    while (redcurr != 0x15 || greencurr != 0x15 || bluecurr != 0x15 || redoff != 0x38 || greenoff != 0x39 || blueoff != 0x38 || brightness != 0)
    {
        I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0000, 0x000, 0x0000); // Off Light
  // Ensure that parameters are set up correctly. Read back and check. If wrong, write and read again.
        redcurr = I2CREAD (ADDRESS, READ_CURRENT_RED); // Read the red current intensity
  greencurr = I2CREAD (ADDRESS, READ_CURRENT_GREEN); // Read the green current intensity
  bluecurr = I2CREAD (ADDRESS, READ_CURRENT_BLUE); // Read the blue current intensity
  redoff = I2CREAD (ADDRESS, READ_OFFTIME_RED); // Read the off-time of the red channel
  greenoff = I2CREAD (ADDRESS, READ_OFFTIME_GREEN); // Read the off-time of the green channel
  blueoff = I2CREAD (ADDRESS, READ_OFFTIME_BLUE); // Read the off-time of the blue channel
  brightness = I2CREAD (ADDRESS, READ_DIMMINGLEVEL); // Read the dimming level
     
        I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
  I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x39); // Set off-time of green channel to 0x39
  I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
  I2CWRITE2BYTES (ADDRESS, CURRENT_RED, 0x15); // Set current intensity of red channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_GREEN, 0x15); // Set current intensity of green channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_BLUE, 0x15); // Set current intensity of blue channel to 0x15
  I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000);
    }

    delay(100);
    I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0014); // Fade Rate --> 0.7s
    I2CWRITE2BYTES (ADDRESS, WALKTIME, 0x000F);
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0555, 0x0555, 0x0555); // White Light
    I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0FFF); // Maximum Brightness


    delay(2000); // wait 2 sec
    // change lamp colour to red
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0FFF); // change red colour intensity to 0xFFF
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000); // change green colour intensity to 0x000
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); // change blue colour intensity to 0x000
    delay(1000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0FFF);
    delay(1000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000);
    I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0FFF);

    delay(1000); // Read back values from slave


    I2CWRITE2BYTES (ADDRESS, WALKTIME, 24); // set walk-time 240ms
}
void led_rotate()
{
I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0fff); // RED
  I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000); // GREEN
  I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); // BLUE
  delay(rot_delay);
  I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000); // RED
  I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0fff); // GREEN
  I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0000); // BLUE
  delay(rot_delay);
  I2CWRITE2BYTES (ADDRESS, INTENSITY_RED, 0x0000); // RED
  I2CWRITE2BYTES (ADDRESS, INTENSITY_GREEN, 0x0000); // GREEN
  I2CWRITE2BYTES (ADDRESS, INTENSITY_BLUE, 0x0fff); // BLUE
  delay(rot_delay);
}



 

 

Here is video of this prototype....

 

 

 

 

 

 

 

my 12V DC supply for LED strip is only capable of delivering 300mA so I have connected only few LEDs... I am finding some powerful 12V DC supply to drive 2amp load of 5m LED strip...

This is just initial prototype ... I will be modifying hardware and software to make it extremely user friendly...

 

Thanks..

 

Madhuri

https://www.kickstarter.com/projects/rabidprototypes/pixelduino-the-arduino-with-an-awesome-oled-displa

 

The Pixelduino is an Arduino-compatible microcontroller that features a 1.5" 128x128 pixel color OLED screen and a MicroSD slot!

 

There are lots of things you can do with a device like this. You can create wearables like a watch, bracelet, pendant, or buckle that displays color images, attach sensors and display data in text or visual form, display debug information, create a graphics user interface, or even make simple retro games!

 

38b8d459cbcc9d68788765f71921f9ba_large.png?1418102264

 

9e0e86e12eab457883a78438de6273fe_large.png?1418080183

 

Features / specifications

  • Processor : Atmel Atmega328P @ 5V / 16MHz
  • IO pins : 14 digital, 6 analog
  • Memory : 32K flash, 2K RAM
  • Voltage regulator : TPS61202 5V boost converter
  • Input voltage : 1.5 - 5.5V recommended
  • Supply current : 100mA @ 0.5V, 1A @ 3V, 1.3A @ 3.7V
  • Power connector : JST PH (standard for small LiPo cells) 
  • Display : 128x128 16-bit color 1.5" (38mm) OLED w/ SSD1351 driver
  • PCB Size : 1.7" x 1.7" (43 x 43mm)

 

 

Check out the video here:

 

https://www.kickstarter.com/projects/rabidprototypes/pixelduino-the-arduino-with-an-awesome-oled-displa

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities.

In my second post I made a paper prototype.


This time I'm setting up the Arduino Yún.

There's an easter egg in this post.


IMG_3432.JPG


Software Setup


Well, that was easy. I already had Arduino IDE1.5.8 installed. The Yún requires 1.5.6 or higher, so that was ok.

The next package needed is Apple Bonjour. The IDE uses that to find the Arduino Yún on the wifi network. I simply installed it and didn't look into it any further.


Getting the Yún connected to the home wifi


That was simple too . I followed the arduino.cc instructions, and that worked for me without too much hassle.



Any hick-ups during the setup were due to my own mistakes. If you follow the guide step by step you should be good.

The only tests I've done at this moment are to load a sketch via wifi (worked!) and ssh/telnet into the linux shell (works too!).


PuTTY Setup

I have a PuTTY installed on my pc. That 'll do for the moment.
The arduino.cc instructions explain that you need to submit two commands in PuTTY to connect to the Yún, but it's simpler than that.

You just have to set the following settings and save them for later use, and you'll be fine:


Session:

Host name or IP address: <your Yún name>.local
Port: 22
Connection Type: SSH
Saved session name: Yún

pty1.jpg

Connection:Data:

Auto-login user name: root

pty2.jpg

go back to the Session category, and press Save.

pty3.jpg

You now have all the settings to get you connected via SSH and have a session into linux as root.

When you <Open> the session and enter the password on the linux prompt, you're in:

puttyshell_2a.jpg

 

This is another step for me to get closer to the Christmas Wreath of Things. I can't wait to start diving into the Eclipse IoT services...

After receiving the hardware from Element 14 for the IOT Holiday lights challenge, i have completed the touch enabled minion ornaments for my christmas tree to go along with the minion sound generation i described in the earlier blog post.

 

 

 

Components used:

 

1. Arduino Yun

2. Adafruit 12-key capacitive touch sensor breakout - MPR121

3. Eclipse Paho MQTT Library

4. Home made minion ornaments

5. Conductive Thread for wrapping around any christmas ornament

 

Here is a high level diagram of how it all works.

touche-minions.png

Pictures:

 

1. Home made Minion ornaments ready to be tested. I couldn't find the minion ornaments in the local stores. So I just used aluminum foil from the kitchen to wrap around piece of cardboard. And stuck the minion stickers on them.

Notice the last christmas ornament. This is wrapped around with conductive thread. This is what i originally intended to do if i get the actual minion ornaments. This works well too.

minions_pre.jpg

 

2. Wiring:

Arduino Yun is connected to the Adafruit MPR121 touch sensor break out. Since this is a temporary arrangement i didn't solder the fires to the break out. The break out speaks I2C. On Yun the SDA and SCL are on the digital pins 2 and 3.

minions_wired.jpg

 

3. Yun connected to tree. (Officially becoming a WiFi Tree)

The small breadboard had a 3m sticker on the back. So i was able to peel it off and attach it to the base of the tree. So this tree is going to be a bread boarded tree forever. In the years to come i hope this bread board gets used for other projects. I just kept the Yun in one of the shipment boxes for now. Later when other parts of the WiFi christmas tree project is done i will plan for an enclosure.

Yun_wiredto_tree.jpg

4. Minion Ornaments on the Tree

I was really happy once it all worked on as planned and the look on my 5 year old son's face was priceless when he touched one of the minions for the first time and it went "whaaaaaaaaaaaaat"

minions_on_tree.jpg

 

The Code:

I have used the code from Adafruit for Capactive touch and the MQTT example from the MQTT C library linked by kartben in an earlier blog post on MQTT. I have modified both code to suit my purposes.

 

This sketch contains three files. I abstracted away the MQTT functionality in to a MQTTHelper class in the arduino coding style to keep my main arduino sketch cleaner. This mqtt helper class just contains a MQTT Publish functionality only. I will add the subscribe functionality later as i continue to work on other parts of the project.

 

ToucheMinions Arduino Sketch

//Created By: Mohan Palanisamy for Holiday Lights IoT project at Element 14
//http://www.element14.com/community/groups/arduino/blog/2014/12/11/intro-interactive-wifi-christmas-tree
//Thanks to Adafruit, Benjamin Cabe, Eclipse Paho for their sample code and Libraries
//You can find them here:
//Adafruit MPR121 Library: https://github.com/adafruit/Adafruit_MPR121_Library
//Benjamin Cabe: http://www.element14.com/community/groups/arduino/blog/2014/11/25/controlling-holiday-lights-using-mqtt-and-the-arduino-yún
#include <Wire.h>
#include <SPI.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#include "MQTTHelper.h"
#include "Adafruit_MPR121.h"


char* mqttBroker ="192.168.1.217"; //mqtt broker running on windows pc
int port = 1883;
char* topic = "WiFiTree/FromController/MinionSound";


uint16_t lasttouched = 0;
uint16_t currtouched = 0;


MQTTHelper mqttHelper=MQTTHelper();
Adafruit_MPR121 minionSensor = Adafruit_MPR121();


void setup() {


  Serial.begin(9600);
  Bridge.begin();
  minionSensor.begin(0x5A);
  mqttHelper.begin(mqttBroker,port);


}


void loop() {

  currtouched = minionSensor.touched();


  for (uint8_t i=0; i<12; i++) {
      if ((currtouched & (1 << i)) && !(lasttouched & (1 << i)) ) {
            char msgbuf[2];
            sprintf(msgbuf,"%d",i);
            mqttHelper.sendMessage(topic,(char *) msgbuf);
        }
  }


  lasttouched = currtouched;

  delay(100);
}






 

MQTTHelper.cpp

//Created By: Mohan Palanisamy for Holiday Lights IoT project at Element 14
//http://www.element14.com/community/groups/arduino/blog/2014/12/11/intro-interactive-wifi-christmas-tree
//Uses source from Benjamin Cabe of eclipse foundation.


#include "MQTTHelper.h"


YunClient c;
  IPStack ipstack(c);
MQTT::Client<IPStack, Countdown> client=MQTT::Client<IPStack, Countdown>(ipstack);


MQTTHelper::MQTTHelper() {
}


void MQTTHelper::begin(char* hostname, int port) {


//MQTT client setup
  ipstack.connect(hostname, port);
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
  data.clientID.cstring = (char*)"wifitree-555";
  client.connect(data);

  Serial.println("MQTT connected");
}


void MQTTHelper::sendMessage(char* topic, char* msgbuf)
{
  MQTT::Message message;


  if (!client.isConnected())
    return;


  Serial.println(msgbuf);
  message.qos = MQTT::QOS0;
  message.retained = false;
  message.dup = false;
  message.payload = (void*)msgbuf;
  message.payloadlen = strlen(msgbuf)+1;
  client.publish(topic, message);
}






 

MQTTHelper.h

//Created By: Mohan Palanisamy for Holiday Lights IoT project at Element 14
//http://www.element14.com/community/groups/arduino/blog/2014/12/11/intro-interactive-wifi-christmas-tree


#include <Wire.h>
#include <SPI.h>
#include <Bridge.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>


class MQTTHelper {
public:

  MQTTHelper(void);


  void begin(char* hostname, int port); // to abstract connection setup arduino style
  void sendMessage(char* topic, char* msgbuf);
};






 

 

 

Future adjustments:

On Chuck i should be able to create shreds to make tingling sounds with the proper scale. Then it would be easy to make a very musical christmas tree when the ornaments are touched.

 

Hope you enjoyed this and try this out for your self. Merry Christmas and Happy Holidays every one!!!

In the last blog post, i installed node js on my Arduino Yun. Then when i tried to install some more node packages using node package manager (npm) i ran in to "out of memory" issue.

 

FATAL ERROR: Evacuation Allocation failed - process out of memory

Aborted

 

At some point of time when you are running some process on the OpenWrt-Yun Linux side of the Arduino Yun, you are bound to face this error.  Note that even when you are running a sketch on the Arduino side, if you happen to use any of the Bridge libraries, you are in essence running a process on the linux side. So inadvertently you might run a process that consumes more RAM than available on the linux side.  For a reference here is the linux memory footprints on the Yun

Type of Memory

Linux Microprocessor

Comments

Flash Memory

16 MB (9MB used by OpenWrt-Yun)

The linux flash memory can be expanded by using the SD Card to load more disk space as explained here.

RAM

64 MB

About 18 to 20 MB of this will be free for you to run other process.

 

So when you run out of this 18+ MB free memory in RAM, we will run in to fatal error above.

 

To avoid this you should set up a swap file or a swap partition for the Linux side of the Yun. When you expand disk space as described here, the YunDiskSpaceExpander sketch doesn’t set up a swap partition by default.  So we have to create a swap file that can be used by openwrt-yun to avoid running out of RAM memory. (Later when i have some time i will see if i can enhance the script to set up a swap partition by default)

 

Verifying Free Memory

 

Connect to Yun using ssh  (i.e. by running "ssh root@youryun.local” from terminal). Then run:

free -m

This should show your current Free memory.. On mine its this:

             total         used         free       shared      buffers
Mem:         61116        43556        17560            0         9612
-/+ buffers:              33944        27172
Swap:            0            0            0

Note the Swap.. Its 0.

So now that i have confirmed that there is no swap file, I tried and set that swap file up on my Yun. The process involves 4 steps.

 

Step 1: Create an empty file to act as a swap file:

 

While connected to the Yun through the ssh terminal, run: (Note that this line will create a 512 MB swap file named yunswapfile in folder "/swap"and fill it with zero

dd if=/dev/zero of=/swap/yunswapfile bs=1M count=512

 

This should run for a bit and provide output like this:

512+0 records in

512+0 records out

 

Step 2: Designate the file as a Swap file:

The step above just created an empty file. To make sure it can be used as a swap file, run this from the shell:

mkswap /swap/yunswapfile

 

You should get output like this:

Setting up swapspace version 1, size = 524284 KiB
no label, UUID=e3e63fad-e6f7-4d4e-a32a-a326bbe48e8c


Step 3: Load the swap file for verifying

To verify that the swap file is good, try to load it by running this:

swapon /swap/yunswapfile

 

This will not provide any output if everything is cool. So verify by checking free memory.

free -m

 

             total         used         free       shared      buffers

Mem:         61116        28644        32472            0         4888

-/+ buffers:              23756        37360

Swap:       524284            0       524284

 

Viola!!! Now you can notice that a swap file is available for use by the RAM. Its not finished yet. Make sure you do step 4 below.

 

Step 4: Load the swap file as part of boot sequence

 

If you stop with Step 3, next time when you restart your Yun (linux part..either through power off/on or the Linux reset button near the LEDs) the swap file will not have been loaded. So to make sure that its gets loaded every time, you need to set the swap file as part of boot sequence.

 

Warning: The steps are fairly simple. But if you the steps are not executed fully you might leave a inconsistent boot config and Linux part of Yun may not load properly. Well this is Arduino. So you can reset the whole thing easily and try again. So please execute the following cleanly after understanding them.


//1. add swap config entry to fstab

root@youryun:/# uci add fstab swap


//2. set device config entry to swap. make sure you provide your full swap file name

root@youryun:/# uci set fstab.@swap[0].device=/swap/yunswapfile

//3. set swap is enabled

root@youryun:/# uci set fstab.@swap[0].enabled=1

//4. set file system type as "swap"

root@youryun:/# uci set fstab.@swap[0].fstype=swap


//5. set options to default

root@youryun:/# uci set fstab.@swap[0].options=default


//6. set fsck to 0

root@youryun:/# uci set fstab.@swap[0].enabled_fsck=0

 

//7. Commit the config changes. if you don't run commit, the config changes will not be added. So make sure the changes are commited.

root@youryun:/# uci commit


That's it. Done. Restart the Linux part of Yun (reset button near LEDs). After reboot, if you run "free -m" you should see the Swap file loaded. You have successfully expanded the RAM on your Arduino Yun's linux side.

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

My first blog post was a brain dump of possibilities. I'm a tiny step further now.

And I have received the ingredients.

 

IMG_3424.JPG

 

The paper prototype

 

Before diving into the electronics part, I want to have a tangible proto. Arts and crafts is not my forte, so don't expect too much.

I made a paper wreath and a paper filter gizzmo. It allows me to dry-run the mechanism.

 

What's next

 

I have no experience with the Yún. so that will be the first firmware topic that I'm planning to master.

I've watched Controlling Holiday Lights using MQTT and the Arduino Yún. I'll now try to follow the Yún tutorials first, learn the eclipse IoT solution,  and then make a service that knows what phase of advent I'm in.

 

Next is selecting an actuator for the filter. I've got a tiny dc motor and a servo motor. That will be the first things I'll turn to.

 

If the dc motor works best, I might need a position detector and brake mechanism. If I use the servo, the challenges will be more mechanical: how do I translate the limited movement into a circular movement.

 

I'll also see how I'm going to use the LED shield. My functional requirements for the shield are non-existing. That means I 'll have to find a creative purpose for the driver.

 

Photo 19-12-14 17 18 15.jpg

Link to previous post

[Dynamic Living-room Lights] Description

 

Brief

The basic idea is to connect living room lighting to the internet and make them work together with holiday lighting so that the entire system functions as a whole. In this post I discuss the structure of the system.

 

Straight to the system

 

The system is quite simple. I drew up a diagram for the basic functionality which looks like...

iot lights.jpg

 

The center

 

The center piece is the Raspberry Pi which has an existing install of OpenHAB. It also has an MQTT Broker running so that if we loose internet connectivity, the system can still function manually. It has the Infeneon Shield and an LED strip which illuminates the room's back wall. This provides the mood lighting and the software control is explained briefly in the previous post.

 

Submodule 1

 

The Shelf panel is also lit up to create a lighting system that does not need to be taken down after the holidays and is controlled via IR. I bought some ready to install lights but redid the shelves and wall.(Pics coming soon.)

 

 

Submodule 2

 

The Arduino Uno is connected to the Yun via either a cable or a 433MHz RF link. The decision will depend on the distances and locations at the time. I have started work on the tree which is near the back wall and hence for the sake or cost reduction, I might kick out the RF bit to be on the simpler side. The christmas tree has RGB LEDs which can be made to glow in any pattern and are controller by the UNO and the system uses a string of RGB LEDS for this.

14%2B-%2B1

 

Submodule 3

We have a santa doll which is also preprogrammed with jingles. Instead of making my own, I am getting one from the toy store and installing an IR trigger which can be controller via the YUN. The functionality is that everytime someone tweets or emails me seasons greetings, santa will let us know.

 

 

Sound input

I thought about this a lot and came up with a simple solution. I have an FM radio connected to the YUN's input and the frequency is fixed. I hacked an old radio from my junk bucket and it works! Next I made a small FM transmitter which can be tuned to transmit to the rx. Now I have the sound input movable across the room. It can be placed in front of the sound system or on the table.

 

 

Mystery module.

More on this IF the rest gets done in time

 

Progress

 

The tree is a work in progress and I am doing the walls. The place looked pretty dull and is getting a once over. I am waiting for some LED trips to show up and experimenting with the YUN.

 

The openHAB system has been running for sometime and I will integrate with it directly which should be simpler.

As i get to understand more about the capabilities of Yun, i did some basic house keeping work on the Yun.

 

  1. Expanded Disk Space with micro SD card

          The openwrt-yun os running on Yun takes about 9MB of the available 16 MB. So its essential to expand disc space if you want to add more files and packages.Following the instructions here i expanded the memory with an 8 GB micro SD card. Please note that once you expand the disk space, if you ssh in to your you will see a folder called  /mnt/sda1/arduino/www

Anything you put in to this folder will be served as a static web page. To be able to copy multiple files you would need sftp on the yun. See below.

 

   2. Installed SFTP

          Copying files to Yun would be a pain if you have to do it one by one or by swapping the SD card between computer and yun. So i installed sftp by running the package manager through shell..(By the way Secure shell (ssh) is going to be your best friend when you are working with Yun.Get familiar with it if you are not already). Here is how to install sftp

          1. On Mac Os X open Terminal.

          2. ssh root@youryun.local

          3. provide password and then update opkg package manager before installing sftp

          4. opkg update

          5. opkg install openssh-sftp-server

    

          That should allow you to SFTP in to yun and copy multiple files.Here is a reference to using sftp.

 

     3. Install node js

            I am not a python developer. I wanted the flexibility of javascript. So i wanted nodejs. I installed it by running this command to install nodejs.

opkg install node




 

     4. Upgraded the OpenWrt-Yun image

Please note that if you upgrade the openwrt-yun image, you will be erasing all your setting. I did this and ended up erasing all my configuration and redoing everything again.

    1. This is necessary only if you want to keep up with the latest releases. Otherwise you might be perfectly fine with OpenWrt-Yun that came pre-installed on your yun.
    2. The default configuration dashboard you get when you access the yun using http://youryoun.local provides you a minimal configuration screen. But If you want to see the advanced openwrt-yun dashboard and the configure certain other features on your yun access the it by clicking the "advanced configuration panel(luci)" link that you will see on the top of the "Configure" screen.
    3. There are lot of configuration features here. i was even able to make the leds on the board blink by just updating some config entries.
    4. You can note the latest firmware version. It should be "OpenWRTYun Attitude Adjustment 1 / LucCI 0.11 Branch (0.11 + svn9964)" .. If you follow the upgrade steps below, you might see that last part get updated to svn10537 or some such based on the current version.
    5. I used the instructions from here to upgrade the OpenWrt-Yun, http://arduino.cc/en/Tutorial/YunSysupgrade

           6. Update: One thing to be aware of after upgrading the openwrt-yun image is that the host key for the Yun would have changed. If you didn't change the name of your Yun, then when you try to establish an  ssh connection to the updated yun, your computer may not be able to connect. For example in Mac OS X i got the following error:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
a4:84:3f:ff:e3:e5:95:59:23:d0:fd:08:8d:5b:f7:03.
Please contact your system administrator.
Add correct host key in /Users/yourusername/.ssh/known_hosts to get rid of this message.

 

All you have to do is edit the known_hosts file at and remove the entire entry belonging to your old yun name.

/Users/mohankrr/.ssh/known_hosts

 

In later posts i intend to show how i use the nodejs in my WiFi christmas tree project

For those creating projects with the RGB LED ShieldRGB LED Shield, hopefully these images can come in handy.

 

infineon-rgb-shield-white-background.png

arduino-white-background.png

They are attached to the bottom of this post in two versions - white background and transparent background.

I can't take credit for the Arduino Uno diagram, I found that on the Internet (not sure of the original source, it was in many places - and just edited it slightly).

Note: This is part one of a three-part guide.

Part 1 - Getting Started Guide for the Infineon RGB LED Shield (you are here!)

Part 2 - Building a White LED Lamp

Part 3 - Building a Full Color Lamp

 

Introduction

Infineon have produced an Arduino shield for LED dimming and lightingArduino shield for LED dimming and lighting, and it is quite impressive.  It is supplied ready-to-use, just solder up some pin headers, connect up LEDs using the spring connectors, plug it onto the Arduino and give the boards some power. Example Arduino code is supplied too.

 

The board actually contains an ARM Cortex-M processor but you could use it without realizing it. The processor does explode the ways of using it and amount of possibilities that one can use this shield for.

 

This post investigates how to make the most of the shield, to help the Internet of Holiday Lights challenge contestants. Also, if you want to build home LED lighting and need a fairly powerful board to control it, then the LED shield from Infineon is likely to be a very good option.

shield-arduino-annotated.jpg

 

What is the RGB LED Shield?

The RGB LED Shield is a board from Infineon that is designed to be plugged on top of Arduino boards such as the Arduino Uno and others. It has connections for up to three chains of LEDs; the idea is that the three channels could be chains of red, green and blue (e.g. color LEDs). Here is a typical scenario that you could use the shield for:

example-application-led-shield.png

 

The shield is is plugged onto an Arduino, and is used to control four RGB LEDs in the example above (it is not necessary to use integrated RGB LEDs of course; separate red, green and blue LEDs could be used, or in fact any color including white). The maximum amount of LEDs that can be controlled in this manner depends on the forward voltage of the LEDs, which typically may be about 2V but varies greatly, from around 1.6V to 4V (check the LED datasheets). Furthermore some LEDs may internally have several LED dies [i.e. chips] inside, and their forward voltage may be a multiple of the ballpark that is mentioned above. Since the LEDs are in series, the supply voltage needed will be a minimum of Vf x N where N is the number of LEDs (or LED dies) in a channel. The shield accepts up to 48V, so close to a dozen or more LEDs of high power should be possible, at up to 700mA current per channel. This could result in a huge amount of light capable of greatly illuminating a room!

 

Typical power LEDs (the variety which require heatsinks) are often available in 350mA and 700mA versions, and both are suitable for this LED shield. Check out part 2 of this blog post which uses the shield to control high power LEDs.

 

The shield is great for lighting effects too, because it contains 12-bit resolution brightness control per channel. Some low-cost options (e.g. Neopixels) only offer 8bit resolution, and transition/dimming effects have visible flaws; a minimum of 10-bit resolution is highly useful, and 12-bit is exceptional.

 

Note that no series resistor is required because the LED shield provides a constant current (which is programmable in software).

 

Getting Started with the Arduino

Download the PDF quick start guide and  user guide and the example Arduino code from the Infineon website (scroll down to the 'GETTING STARTED – XMC1100 BOOT KIT and ARDUINO UNO R3' section and the file you want is titled Getting Started Examples . When run, it will extract into a folder.

 

If you’ve never used an Arduino before (like me), then before you plug anything in, go to the Arduino site, download and install the software, and then plug in the Arduino board into your PC. Once you know which COM port the Arduino was assigned by your PC (if you are not sure, check using Device Manager in Windows; for other operating systems, the Arduino site can be checked). Next, in the Arduino software, select Tools->Serial Port and choose that port. Select File->Open and navigate to the Arduino_Getting_Started_Examples/Arduino Uno R3/RGBLED_2_SAFE folder and select the file inside there (called RGBLED_2_SAFE.ino).

 

Click the ‘Verify’ icon (looks like a check-mark) and after a few seconds you’ll see some text saying ‘Binary sketch size’ at the bottom of the window. Now click on the ‘upload’ icon (looks like an arrow pointing right).

verify-upload.png

 

The process is complete when the text says ‘Done uploading’ as shown here:

done_uploading.png

 

Unplug the Arduino from the PC, and then connect up the LED shield.

I didn’t have any RGB LEDs but I had some high power white LEDs, so I connected two in series to a single channel, just to test out the board. With the demo code, the LEDs must be rated to support at least 300mA and the combined forward voltage for a channel must be at least 6V.

 

The LEDs need heatsinking, so I used the nearest heatsink I could find (extremely oversized, but it was what I had handy). Really these LEDs should be soldered to a PCB, however I used thermally conductive tape for the test:

test-setup.jpg

 

Plug in the USB cable into the Arduino (either to a PC, or to any USB 5V supply). The white LEDs had an approximate 3.6V forward voltage each, so I used a 9V DC supply to power the two LEDs. The LEDs dimmed in and out (this is what the demo program does). Clearly with RGB LEDs the result would be more interesting!

 

It would be a simple step to now begin to modify the Arduino code to suit your project, and use with LED chains of your choice.

 

How Does It Work?

The LED shield contains a buck converter topology per channel. Each channel contains a MOSFET which is turned on by the Infineon integrated circuit. Current begins to flow through the LEDs in series with an inductor. Because of this, the current rises over time. Because there is also a small fixed resistance in series with this circuit, the current can be measured because it will produce a voltage across the resistor. In other words, the circuit current path consists of LED-inductor-MOSFET-resistor (where the MOSFET and resistor have a low resistance).

 

The Infineon device (XMC1202) measures the current (by measuring the tiny voltage across the resistor) and powers off the MOSFET once a certain current is reached. At this point, the energy that was stored in the inductor during the time the MOSFET was on continues to flow through a diode (as a result of back-EMF as the magnetic field collapses).

 

The oscilloscope traces below show the voltage across the resistor. It can be seen to rise until the MOSFET switches off and disconnects the resistor from the remainder circuit (LED-inductor-flywheel diode).

 

The XMC1202 has been programmed to have a short delay before it switches the MOSFET back on, and this is clearly visible in the oscilloscope traces too (a delay of about 1usec). The first trace was captured using a 9V supply:

with9v.png

 

The second trace used the same LEDs, but a 24V supply:

with24v.png

 

The XMC1202 was programmed to switch off the MOSFET at 25mV, but it can be seen that the peaks exceed this. This is normal because of comparator and processing delays. Even at 24V, the peak current is lower than 300mA (I=V/R and the resistor is 0.2 ohms). The design could be optimised by adjusting the peak current and the delay values once suitable LEDs and a supply voltage has been selected. The default values in the code are “safe” values for the worst-case scenario (48V input, and LED chain forward voltage total of 6V). Even without optimisation the operation is good enough to begin to create projects.

 

The XMC1202 contains a microcontroller inside it, based on an ARM Cortex-M core. It is programmed to operate as an I2C slave. There are very few connections between the LED shield and the Arduino:

led-shield-pinout.png

 

The very few connections means that it is very easy to swap the Arduino for a different board if desired (see the next section below).

 

The XMC1202 has been programmed with quite a rich command set. The user guide explains what values to program to achieve a desired result. The Arduino code was self-explanatory.

 

Adjusting the Desired Current

In the code, the peak current value at which the XMC1202 begins to switch off the MOSFET can be adjusted by setting this value:

I2CWRITE2BYTES(ADDRESS, CURRENT_RED, x); (and repeat for the other two channels)

where x is an integer, x= I*163.84 (this was based on the formula in the user docs, I just calculated it for the current sense resistor [0.2 ohms] on the LED shield board). As an example, to set the value to 200mA, x would be 32.

 

However, due to delays in detecting the peak value, the current can exceed this, so it should be checked on a scope, or use an integer smaller than this initially. See the oscilloscope screenshots above (in the How Does it Work section) for the traces to expect. With the demo code, the peak value in the traces there can be seen to be around 40mV and 60mV (for source supply voltage 9V and 24V respectively which were the values I tested with), which corresponds to 200mA to 300mA through the LED(and this looks correct, since this is with the 'safe' demo settings).

 

There is another setting per channel (parameter OFFTIME_RED, OFFTIME_GREEN, OFFTIME_BLUE), which also needs adjusting when trimming with a scope, the safe default will be a higher value than an optimised value. See the user documentation for more details. If you're not sure, or do not have a means to check, then it is advised to only use 350mA or higher rated LEDs and use the default demo settings since these are safe for 350mA rated LEDs.

 

Experimenting with FRDM boards

Since the LED shield on top of the Arduino Uno feels top-heavy, it was decided to replace the Arduino with a FRDM board from Freescale. If you’ve not used these boards before, you are missing out. I selected the FRDM-K22F boardFRDM-K22F board, but the better board for beginners is the FRDM-KL25ZFRDM-KL25Z because it has the most examples/demos.

frdm-boards.jpg

 

The FRDM boards have 3.3V logic unlike the 5V logic levels of the Arduino Uno. In the case of the LED shield, it pulls up the I2C lines to 5V, however it was decided to go with this. The Freescale processor contains protection diodes, and according to the specification can tolerate 3mA when the voltage exceeds the rated values. The LED shield has 10k resistors as pull-ups, so the 3mA level is not exceeded. If you don’t feel comfortable with this, then the LED shield’s 10k resistors would need to be removed (or the track to the 5V pin would need to be cut) and the I2C pins pulled up to 3.3V instead, with a custom modification.

 

To test the LED shield, the two built-in buttons on the FRDM board were used to switch on/off the LEDs by sending the appropriate I2C commands. The code is attached to this post.

 

Creating Your Own XMC1202 Applications

Since the processor inside the XMC1202 is accessible, it becomes possible to create your own applications for it. For example, the I2C instruction set could be extended. Alternatively a complete application could be written for it so that it doesn’t need to behave as an I2C slave. This would allow the LED shield to be used on its own, unplugged from any Arduino or FRDM board. As another example the I2C address could be modified, so that multiple LED shields could be stacked on top of each other (might need very long headers for that, to overcome the height of the connectors on the LED shield).

 

To program the LED shield, there is a tiny (1.27mm pitch) DIL header already soldered on the board. Cables for this are expensive. An alternative approach is to solder on a 2.54mm header in the space adjacent to the smaller connector, as shown here:

debug-connector-closeup-marked.jpg

 

You’ll also need a J-Link emulatorJ-Link emulator or Infineon’s other development board (code KIT_XMC12_BOOT_001). I used a Segger J-Link emulator. It comes in various versions including an educational versioneducational version too.

 

The first step is to download the development environment, called DAVE, from the Infineon website and install it (this will also install Segger J-Link software). When DAVE is run, let it auto-update itself.  Select a folder to act as a workspace for all your projects. Something like C:\projects\DAVE_work would be fine.

 

Next, download the source code for the default software that is running on the LED shield as shipped. It is at the Infineon website, scroll to the bottom, in the section RGB LED Lighting Shield – XMC1202, titled RGB LED Lighting Shield – XMC1202 Source Code.

 

Once installed, select File->Import->Infineon->DAVE Project and choose the root directory to be the folder RGB_LED_Shield_v5, and then it should appear in the Project List. Select Copy Projects into Workspace and then click Finish.


You should now have a folder RGB_LED_Shield_v5 in your workspace folder (c:\projects\DAVE_work).

 

Now you can observe the code and make changes! For example if you wish the LED shield to start up with the red channel at full brightness (i.e. standalone, regardless of if it is plugged into an Arduino or not, but still allow for the Arduino to subsequently control it), then in the main.c file it can be clearly seen where the red intensity and dimming levels are configured, and they can be modified:

 

Lamphandle.Intensity_Red = 0xfff;
BCCUDIM01_AbortDimming(&BCCUDIM01_Handle0, GET_CHANNEL_DIM_MASK(BCCUDIM01_Handle0.DE_Num)); // Abort previous dimming
  BCCUDIM01_SetDimLvl(&BCCUDIM01_Handle0, 0xfff); // dimming engine 2
  BCCUDIM01_StartDimming(&BCCUDIM01_Handle0, GET_CHANNEL_DIM_MASK(BCCUDIM01_Handle0.DE_Num));






 

The code snippet above will set the red channel to full brightness before the code starts up the I2C slave function. See the screenshot below for where to insert this code.

 

To compile the code, click on the ‘build all’ icon (highlighted in the screenshot) or go to Project->Build All. The console output should indicate that the code was built successfully, as shown in the screenshot too.

building-code.png

 

After DAVE has been installed, you are ready to connect up the J-Link device to your board. Four connections are needed, as shown here:

jlink-pinout.jpg

 

Writing code, and testing it are two separate ‘views’ in DAVE, so you’ll need to go into the ‘TASKING Debug Perspective’ to run the code (a ‘view’ is just a collection of windows that makes sense for the task at hand). You can select that from the top-right (if you can’t see it, you may have to drag the curvy tab left to bring it into view). Now click on the bug icon (highlighted below). Once you do that, you’ll see the stack trace, and the program waiting at the main() entry point. Click the ‘play-shaped’ button to run the code (or you could single-step as desired) and the LED should light up! The code is now programmed into the XMC1202, so after you have finished with the debug session and disconnected the J-Link and power-cycled the LED shield, the new code will still function. You can go back to the code view by clicking on ‘DAVE CE’ at the top-right.

debug-view.png

 

Summary

The RGB LED Shield from Infineon is a nice, high quality way of controlling LED lighting. It is extremely easy to use with an Arduino. With some adjustments, it is possible to fine-tune the output to get the maximum output from LEDs safely. The shield can also be used with any other microcontroller board (e.g. FRDM board, RPI etc) because it is controlled by the standard I2C interface. The I2C commands are extensive and are listed in the user guide. The Arduino code is easy-to-follow. The LED shield was tested on a Freescale board too.

 

If desired, the software running on the LED shield itself can be easily modified too; this is not essential since the built-in commands are extremely flexible but it allows for the shield to run stand-alone if desired, or with additional custom commands to meet user needs as an example.

 

If you’re looking to use the RGB shield, then it is also worth purchasing headers, an Arduino or perhaps a FRDM board, lots of LEDs!, a 24V or 48V power supply and also a JTAG emulator if you want to modify the code on the LED shield.

 

Click here for part two to build a practical LED lamp.

My entry for the Internet of Holiday Lights is an electro-mechanical wreath.

 

For those new to the subject: in Belgium, a wreath comes with four candles. Each advent Sunday we lit one of the candles.

The last Sunday of advent, all four candles are lit. The ceremony is documented on Wikipedia.

 

My electro-mechanical concept is going to be semi-intelligent, semi-dumb.

The candles will be leds or bulbs, and they won't have a clue about what week of the advent period it is. They will always be lit.

The lights will be hidden from the spectator's view by an opaque filter. The filter is fitting above the wreath and will be motor driven.

It has openings in it. These openings are positioned in such a way that either one, two, tree or four lamps are visible.

 

The smart part will be in the motor and its logic. Each day of the advent matches with a particular position of the filter. The motor driver will have to know what to do to put the motor in that given position.

 

The IoT magic takes care that the wreath knows what day it is. It's going to use a calendar service to get the date.

I don't know how to deal with time zones yet. Maybe solder in a particular resistor depending on what zone the owner is in?

 

In fact I don't know anything about te design yet. It's just an idea at this moment.

You'll find out together with me how it materializes.

Thanks to Element 14 i got my Arduino Yun today. The first thing i noticed was the power supply. No barrel jack. So it has to be powered through Micro USB. That's fine when connected to a computer. But if you are powering it from wall wart or from batteries then it has to be the right specification because of the lack of built in regulator.

 

Arduino Yun getting started guide spells this out:

 

There is no built in 5V regulator. If you power your Yún with more than 5V, you will likely damage it. If you are not powering the Yún from the micro-USB connection, you can apply power to the VIN and 5V pins on the board. If using the VIN pin, you cannot provide more than 5V, it will damage your board. It is recommended to power the Yún from the USB connection whenever possible.


So i tried out a 5v-0.7A wall wart used to charge a cellphone and i was able to power the Yun untethered to computer.

power.png

 

One thing i am not clear is this: "There is no built in 5v regulator." Does this apply only to the Vin Pin or even the micro USB as well? Need to research further.

 

I am still not sure about the battery powered sources. Just putting together a bunch of Alkaline batteries to power this thing is not going to work. The linux part of the board and the Wifi should be drawing lot of power. So Lipo batteries might be needed. Along with a proper 5v regulation circuit.

 

I am starting a discussion here so that the community can post what kind of power sources they use to power their Arduino Yun so it might be of use to others.

I recently signed up for an electronics "road test" and was grateful to be selected along with 19 other participants to create a holiday lighting project, with help of the following hardware, thanks to Element14, Infineon, and MCM Electronics:

 

  • Arduino Uno R3
  • Arduino Yún
  • Infineon Lighting RGB LED Shield

 

Today I finally got my hands on the following hardware (it had been waiting in an UPS store since Friday) and was able to unbox it.

 

First impressions

Arduino Uno R3

I know this is the bread and butter of micro computing, and I'm excited to finally have one. The board comes clean and free from fingerprints or leftover flux. It has "Made in Italy" proudly stamped on it, as a testament to it's legitimacy. In my very first sketch ever, I tried out the basic blinking sketch. I then found a Morse Code sketch which writes messages by blinking the onboard LED at pin 13. Works great for me because I still have a lot of hardware to buy!

 

Arduino Yún

The Yún looks quite like the Uno except for it's Ethernet port. This board arrived dirtiest of the bunch, with noticeable leftover flux and fingerprints on the metal shield which covers the WiFi chip and the Atheros chip that runs Linux OpenWrt. It is made in Taiwan, which is supposed to have significantly better electronics quality than China so I am not overly worried about the flux and fingerprints.

 

I will use this board to have some amount of interfacing via the Internet, as per the Internet of Things theme of this Element14 road test.

 

Infineon RGB LED Lighting Shield

This shield is a brilliant beautiful shade of something between dark orange and red, and I am very excited to get started with this board as well. I was talking to peteroakes and he pointed out that I cannot power my 5V NeoPixel esque light strip on this board, because it is more suited to loads that are 6V and higher. He suggested I check out some other LEDs with larger voltages that will make use of this board. My NeoPixel strip is best powered with a wall adapter power supply that can push 5V with about 3-5A of current, and I will likely power these directly of my Uno.

 

One initial note when handling the Infineon is that I realized that this shield does not arrive with the interfacing pins required to mount this on this on the Uno or Yún. That means unless you have the means and ability to solder well, this is not a beginner board.

 

One key advantage to the Infineon is that it is able to control current flow, allowing quick prototyping of LEDs. It will take a bit of learning for me to actually put this shield to use!

 

Unwrapping the package yields some beautiful little packages with bright colouring. I can't wait!


Here are all three of the products

 

The Arduino Uno R3


The Arduino Yun

 

The Infineon RGB LED Lighting Shield. Note the lack of interfacing pins, meaning that you have to solder!

 

Here are all 3 of the products

 

This is my second sketch - the Uno is writing my name in Morse code

Party Message Board

 

Back to the beginning BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights

 

I hope your all finding the information useful so far, this is proving to be a fun packed challenge

 

For today I have chosen to test out the 16*32 panels I bought from Adafruit, they arrived today (yaaa, so many presents already ), these are not really meant for UNOs and the like, there really for massive street signs and ideally driven by powerful FPGA based systems but the great folks at adafruit have done a superb job of writing some libraries to allow them to be driven by even an UNO or a Mega with plenty of room to spare for other code, these displays have to be driven as a matrix actively by the UNO (There not neo pixels) so a fair percentage of cpu time needs to be used to scan the images onto the panel

 

This is what you get:

P1010331.jpg

 

You can find all the code and wiring details here: http://www.adafruit.com/product/420 and believe me, these things are awesome, wire them up as instructed, apply power and a test sketch and it just works, It was even working before I connected the correct supply to the panel (Albeit a bit dimly)

 

My plan it to have Mr UNO or Mrs Yun drive this and possibly another to display web messages of cheer from a web site or twitter feed, may need moderation though or a menu of messages to select from, but for now I wanted to test how easy it is to use and send a holiday greeting to my companion competitors and eager followers

 

so here is the video of this working, and I have to say, these things are AWESOME



WARNING:

While I'm on the subject of testing, I did discover an annoying feature of the Infineon RGB Board (Or more specifically the Yun and its compatibility with Shields) , It wont fit on the Yun without using a set of Stacking headers (The kind you get if your making your own shields)

 

Here is what happens without

P1010332.jpg

As you can see, the board barely makes contact with the sockets and it is already hitting the top of the Ethernet port, nothing that a set of stacking headers cant fix, but of course you need the headers, also available from Adafruit

 

Now it works (The stacking header pins are long, they are well and truly inserted)

P1010334.jpg

 

OK, that's it for this update, with luck more goodies will arrive tomorrow and I will share more details of how to connect up and where to get libraries

ACKme_1.png          element14_teal_orange.JPG


15 December 2014, London, Farnell element14 has announced that it will be profiling the ACKme Networks product portfolio of compact, pre-certified, ultra-low power wireless modules for the embedded “IoT” market space.

ACKme Network’s modules, test boards, software framework, and cloud services accelerate design time-to-market and greatly reduces risk in security, certification, and compatibility.

Engineers and developers can transform their products into connected devices using ACKme’s complete Silicon-to-Cloud™ connectivity solutions.

AMW006-A02.3_med-res.jpg

Above: ACKme's Mantis Development board for Shield Enthusiasts

AMW006-A02 - ACKME NETWORKS - WIFI SHIELD, AMW006 EMBED WIRELESS N/W | Farnell element14 UK

ACKme’s SDConnect™ is an IoT software framework that vastly reduces time-to-market and eliminates expensive development costs through the use of a simple to use SDCommand Set API.  WiConnect™ also includes highly secure over-the-air firmware updates, on-board file systems, wireless services, network services, cloud services, failsafe boot-loading, TLS security and peripheral management.

The final solution in the portfolio includes both production cloud OEM services for devices through sensors.com and free cloud prototyping services at goHACK.me (gHm).  All ACKme modules are gHm and sensors.com ready allowing customers to create cloud based sensor and control applications quickly.

“The ACKme portfolio accelerates the time to market complimenting Farnell element14’s strategy to help in reducing product design cycles.  Following the successful cloud and IoT focussed webinar earlier this year we decided to add the ACKme Network products to our portfolio.” said Richard Curtin, Global Director of Strategic Alliance, element14

“Farnell element14 has a loyal following of individuals from pure hobbyists to engineers alike, all looking for strong technical solutions”, commented ACKme’s Nick Dutton, VP for Business Development, “Farnell element14’s customer recognition of ACKme’s hardware, firmware and cloud solutions are an enormous compliment.”

ACKme Network’s products are available from Farnell element14 in Europe, Newark element14 in North America and element14 in Asia Pacific with same day dispatch and next day delivery available. Data sheets and application notes can be found on the product pages together with a range of associated accessories, and 24/5 live tech support is available for any queries. The new development kit is the latest in element14’s diverse variety of solutions ranging from starter kits to complete development boards, including the newest releases and exclusive bundles from the greatest range of development kits available globally from one single source.

 

About the Premier Farnell Group

Premier Farnell plc (LSE:pfl) is a global leader in high service distribution of technology products and solutions for electronic system design, production, maintenance and repair. It trades as Farnell element14 in Europe, Newark element14 in North America and element14 across Asia Pacific. With sales last year of £968m, the Group is supported by a global supply chain of more than 3,500 suppliers and an inventory profile developed to anticipate and meet its customers’ needs.



Premier Farnell works with key strategic suppliers to bring to market development kits in a variety of applications, enabling it to support the customer from design concept through to production.

The latest products, software, services and solutions from trusted supplier partners are all available through 43 local language transactional websites, with customer support provided by degreed engineers. The element14 Community allows buyers and engineers to access a wide range of independent technical information, tools and the latest resources.

For news updates from Premier Farnell and element14 visit:

Premier Farnell News Centre – www.premierfarnell.com/media-centre
Twitter - @element14news; @element14
YouTube – element14
Facebook – facebook.com/element14page

Email: pressoffice@premierfarnell.com

 

 

Premier Farnell Key facts

  • Operations in 36 different countries
  • More than 4,300 employees
  • More than 3,500 leading suppliers
  • More than 500,000 products stocked with access to over four million more on demand

·        Leaders in providing information on REACH, Conflict Minerals and EU RoHS legislation

I seem to be a bit behind the curve compared to other testers, my hardware hasn't shown up quite yet (tracking predicts it'll show up today, so maybe I can get it unboxed and plugged together this evening - we shall see). But that doesn't mean I've been sitting back doing nothing. There's more to my project than just electronics after all!

 

After playing with the necessary 3D design, and printing one unfortunate failure, I realized I was taking the wrong approach to wrapping a flat string of LEDs around a spherical object. A spiral pattern just wasn't going to work given the LED strip's inability to bend along its thin edge. Being the intrepid rapid prototyper that I am, I mulled it over, and decided to give longitudinal mounting a try instead.

 

Here's attempt number two, printing away:

2014-12-14 22.50.08.jpg

 

With a little bit of math, and a little more 3D modeling, I came up with a working design. Each channel is essentially made up of 11mm wide strips of a 40mm radius sphere incised into a 42mm radius sphere, that channel is then rotated 72 degrees around the center line of the sphere, and the process is repeated until there are a total of five channels. That may sound a little confusing, but the practical upshot of this you get five channels that will hold the LED strip and that are sized specifically to fit two segments of the strip (i.e. six LEDs per strip, and 30 LEDs per ornament).

 

My hope is this will give a relatively even lighting effect on the final ornament. But we will see.

 

2014-12-14 23.17.52.jpg

You can see that in addition to the incised channels, the inner sphere has five raised nubs at points 45 degrees up the arc of the sphere. These will provide additional clearance between the inner sphere and the outer shell of the ornament to make for easier mounting of the LED strips and wiring.

2014-12-15 00.53.59.jpg

Each 6 LED segment will have to be wired to its neighbors, and then each ornament will have two sets of wires coming out of it. One to hook to the supply (or the previous ornament) and one to hook to the next ornament. The holes in the top and bottom of the core will be useful for wire routing to keep the surface clear of stray wires.

 

One thing I discovered, but wasn't surprised about, is that the sticky 3M backing on the LED strips seems to be all but worthless. If there's anything it will stick effectively to, PLA plastic isn't it. I'll probably end up having to tack the strips down with hot glue or odorless silicon or something.

2014-12-15 01.01.06 small.jpg

The only thing missing from the ornament now is the outer shroud. It's mostly designed, but not quite finished, and will be printed in nylon for a nice white diffuser layer that has a nice smooth texture to it.

 

Now... if only my hardware would show up I could put it through its paces and make a glowing ball...

Good morning and thank you to all the competitors in the Internet of Holiday Lights RoadTest Plus; we are delighted that the Internet of Things and Holiday decorations are proving to be so well matched.
As we did with the Forget Me Not Challenge we hope to inspire even greater effort by offering an additional prize. Without further ado, meet Jerry -
Minion Jerry
The competitor who produces the most content-rich, inspiring and informative blog(s) between now and December 24th will receive a Jerry action figure to sit on their desk or workbench; hopefully his lullabys will help soothe after a hectic holiday period.
Not selected? Want to join in?
Many people have expressed interest in this particular RoadTest Plus: if you weren't selected, no problem, just purchase an Infineon LED shield, couple it to a suitable Arduino (we recommend the Yún) and the Eclipse IoT Platform and you’re in! Be sure to blog about your project on the Arduino area, and tag your posts with iot_holidaylights.
Any questions, as ever, please let me know.
"Minions" & Despicable Me © 2014 Universal Studios. All Rights Reserved.

Back to the beginning BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights

 

OK, so one thing I could not find in all the searching was a Library for the infineon Board so I made one from the sample code, it is not 100% complete yet (More features to add) but its all working so I thought I would share it with you all so you can use it if you so desire

 

I have moved all the functions into a library called "Infineon"

 

Added a function to directly set colours "SETCOLOUR(RED)" for example, so far it only has a few colours defined but If i can get a list of RGB values for LED colours 12 bit per colour then I will be happy to add them to this

 

Colours are White, Silver, Gray, Black, Red, Maroon, Yellow, Olive, Lime, Green, Aqua, Teal, Blue, Navy, Fuchsia, Purple but of course some dont look right on LEDS so i need to refine it over time, if you have some good colour definitions please contribute

 

This is the modified main loop so you can see how much cleaner it is, it of course can be improved further but this is just a test

 

  // the loop routine runs over and over again forever:
  void loop() {

    // change lamp colour to red
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0, 0x0, 0x0); // all off
    delay(500); // wait 1000ms
    // change lamp colour to green
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x03ff, 0x03FF, 0x03FF); // 25%
    delay(500);
    // change lamp colour to blue
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x07ff, 0x07ff, 0x07ff); // Blue
    delay(500);
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0bff, 0x0bff, 0x0bff); // Blue
    delay(500);
    RGBLEDS.I2CWRITE6BYTES(ADDRESS, INTENSITY_RGB, 0x0fff, 0x0fff, 0x0fff); // Blue
    delay(500);
  // White, Silver, Gray, Black, Red, Maroon, Yellow, Olive, Lime, Green, Aqua, Teal, Blue, Navy, Fuchsia, Purple
    RGBLEDS.SETCOLOUR( White);
    delay(500);
    RGBLEDS.SETCOLOUR(Silver );
    delay(500);
    RGBLEDS.SETCOLOUR(Gray );
    delay(500);
    RGBLEDS.SETCOLOUR(Black );
    delay(500);
    RGBLEDS.SETCOLOUR(Red );
    delay(500);
    RGBLEDS.SETCOLOUR(Maroon );
    delay(500);
    RGBLEDS.SETCOLOUR(Yellow );
    delay(500);
    RGBLEDS.SETCOLOUR(Olive );
    delay(500);
    RGBLEDS.SETCOLOUR(Lime );
    delay(500);
    RGBLEDS.SETCOLOUR(Green );
    delay(500);
    RGBLEDS.SETCOLOUR(Aqua );
    delay(500);
    RGBLEDS.SETCOLOUR( Teal);
    delay(500);
    RGBLEDS.SETCOLOUR(Blue );
    delay(500);
    RGBLEDS.SETCOLOUR(Navy );
    delay(500);
    RGBLEDS.SETCOLOUR(Fuchsia );
    delay(500);
    RGBLEDS.SETCOLOUR(Purple );
    delay(500);
  }


 

 

The cycle looks like this

 

 

Code is attached for your pleasure

Back to Master Blog BYOB Party #1, "Bring you own Bulbs" - The Internet of Holiday Lights

 

Hi Everyone

If your taking part on this challenge, I hope like me your now in possession of your parts to begin the fun

 

The first thing I wanted to do was evaluate the Infineon with a regular 12V RGB led strip, the kind that comes from China in rolls of 5M (60LEDs / Meter)

 

Well mine was partly used (Lighting for my bench project DIY LAB Bench with Shelves pt2, the Shelves ) for the under shelve lighting but there's enough left for this project

 

So I hooked it up only to find the output was rather disappointing..Time to investigate

 

VIDEO TO GO HERE

 

So it seems the default configuration for the Infineon board allows for 300mA and up to 48V supply for driving strings of at least 6V based on the manual here http://www.infineon.com/dgdl/Infineon-Board_Manual_-_XMC1202_-_RGB_LED_Lighting_Shield_with_XMC1202_for_Arduino_-_v1_0-U…. or does it.

 

The PDF  describes the parameters as follows (The safe Parameters)

 

300mA LED Current

6 - 48V forward current (Depending on supply of course)

 

Here is the output schematic of the output stage of the Infineon (This is the green channel but there all the same)

The LEDs are of course the ones you will or may add

I_Peak_Green is a tap to the ADC

Put_Green goes to another ADC but does not appear to get used

 

The circuit is repeated for RED and Blue and basically works like a buck regulator, with the control being in the hands of the ARM Cortex CPU

 

The settings in the code are as follows and in summary I will provide explanations


PEAK Current Setting 0x15

The ADC has a max volts of 5V and a max digital range of 0xFFF = 1.22mV/Cnt, and this into a 200mOhm resistor amounts to about 6mA per count with a max allowed count being 0x80 (0.156mV) or 780mA max. This setting is used to measure the current flowing through the LEDS, once it is exceeded the MOSFET is turned off and the Inductor will continue the current flowing but slowly diminishing, a setting of 0x15 equates to about 120mA according to the math but the text says 300mA. They may be referring loosely to the total string current ? but the math says 120mA per string. Also note that due to latency in sensing the peak and turning off the fet will cause some overshoot

PEAK CURRENT can be set individually for each channel

Fade Rate 0x14

The fade rate is the time it takes to fade from one dimming level to another, this is not the same as changing the intensity of the separate colours, it is also an exponential scale to match the eyes response to intensity change sensitivity so going from 0-50% will be quicker than from 50  - 100 %, there is a great graph in the manual to explain this pictorially , the count is not simple to calculate on the fly so experiment and read the manual

FADE RATE is global to all channels

WALK Time 0x30

The time it takes to change from one colour to another, not to be confused with changing intensity, A single count is shown as 10.24mS per so the value of 48 should approximate 480mS

WALK TIME is global to all channels

DIM Level 0xFFF

This is the method of changing the intensity of the overall output of the LEDs without changing the colour, if a colour setting involves a very low value of a particular channel, reducing the intensity of each individual channel can result in changing the colour, using the dimming control does not have this side affect

DIMMING LEVEL is global to all channels

Off Time 0x38

When the peak current is reached, the fet is turned off and a counter started this is the time before the fet is turned on again and effectively determines how much ripple will be seen in the LEDs, don't make this too short as the latency between detecting the peak current and turning it off needs to be less than this parameter, 0x38 equates to about 873nS (1uS) as each count is 15.6nS

OFF TIME can be set for each channel

Intensity between 000 and 0xFFF

The intensity allows you to control the individual brightness of each RGB channel with relationship to the others allowing millions of colours to be created (4096*4096*4096), the MAX value for each channel being 0xFFF or 4096 and equates to 100% brightness for that channel but is multiplied by the Dimming value to get the LED/BULB intensity so if you set 4096 (100%) for the channel but the dimming is set to 2048 (50%) then the LED/Bulb will only be on 50%, this allows you to set a colour and change the overall intensity with out affecting the colour

 

So now we know what the settings do (I ignore the DMX ones as we don't have DMX available so their meaningless )

 

Measuring the LEDs I have, I get a current of approximately 800mA per string, this means the i_PEAK will need to be MAX or 0xFFF

the off time can be left alone or reduced a bit if you feel the need, but test first

for my initial testing to see the affects I changed the FADE and WALK times to zero for instant changes

I also changed the script to simple show white and change the intensity of each LED vs using the dimming control so I can capture the signals on my Tektronix  MDO3054MDO3054 oscilloscope for analysis and conformation of the settings

 

For your use, here is the changed sketch for the arduino

 

  // Infineon RGB_LED_Shield_Master_Tester
  // by Michelle Chia
// adjusted by Peter Oakes to test changes required for 12V 700mA/Color RGB LED Strip and ignore DMX

  // Demonstrates I2C communication with the RGB LED Shield for safe configuration. Tested at 48Vin, 6V forward voltage LED. LED current up to 350mA.
  // Modified 13 August 2014

  #define ADDRESS                    0x15EUL

  #define INTENSITY_RED              0x11U
  #define INTENSITY_GREEN            0x12U
  #define INTENSITY_BLUE     0x13U
  #define INTENSITY_RGB              0x14U
  #define CURRENT_RED                0x21U
  #define CURRENT_GREEN              0x22U
  #define CURRENT_BLUE               0x23U
  #define CURRENT_RGB                0x24U
  #define OFFTIME_RED                0x41U
  #define OFFTIME_GREEN              0x42U
  #define OFFTIME_BLUE     0x43U
  #define WALKTIME                   0x50U
  #define DIMMINGLEVEL               0x60U
  #define FADERATE                   0x61U
  #define READ_INTENSITY_RED         0x81U
  #define READ_INTENSITY_GREEN       0x82U
  #define READ_INTENSITY_BLUE        0x83U
  #define READ_CURRENT_RED           0x84U
  #define READ_CURRENT_GREEN         0x85U
  #define READ_CURRENT_BLUE          0x86U
  #define READ_OFFTIME_RED           0x87U
  #define READ_OFFTIME_GREEN         0x88U
  #define READ_OFFTIME_BLUE          0x89U
  #define READ_WALKTIME              0x8AU
  #define READ_DIMMINGLEVEL          0x8BU
  #define READ_FADERATE              0x8CU
  #define SAVEPARAMETERS             0xA0U
  #define BCCUMODID                  0x50030008U
  #define CHIPID                     0x40010004U
  #define REDINTS                    0x500300A0U // BCCU_CH5
  #define REDINT                     0x500300A4U
  #define BLUEINTS                   0x50030078U
  #define STARTWALK                  0x50030018U

  #include <Wire.h>

  unsigned int c[2] = {0};
  unsigned int d[4] = {0};
  unsigned int on = 0;
  unsigned int message = 0;
  unsigned long redcurr = 0;
  unsigned long greencurr = 0;
  unsigned long bluecurr = 0;
  unsigned long redoff = 0;
  unsigned long greenoff = 0;
  unsigned long blueoff = 0;
  unsigned long redint = 0x00;
  unsigned long greenint = 0x00;
  unsigned long blueint = 0x00;
  unsigned long fadetime = 0x00;
  unsigned long walk = 0x00;
  unsigned long brightness = 1;

void setup() {            
    Serial.begin(9600);
    Wire.begin();
    while (on != 1) // Wait for shield to respond, keep setting the values till it does
    {
      I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Immediate fade
      I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // 0% brightness level
      on = I2CREAD(ADDRESS, READ_DIMMINGLEVEL); // Request for brightness level
      if (message == 1 && on == 0) // If message received and dimming level = 0%, "message" is set in the I2CREAD function
      {
        message = 0;
        on = 1; // break out of loop
      }
    }
    // now we will chane the values again and wait till there being red back
    while (redcurr != 0x15 || greencurr != 0x15 || bluecurr != 0x15 || redoff != 0x38 || greenoff != 0x39 || blueoff != 0x38 || brightness != 0)
    {
   I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0000, 0x000, 0x0000); // Off Light
  // Ensure that parameters are set up correctly. Read back and check. If wrong, write and read again.
  redcurr = I2CREAD (ADDRESS, READ_CURRENT_RED); // Read the red current intensity
  greencurr = I2CREAD (ADDRESS, READ_CURRENT_GREEN); // Read the green current intensity
  bluecurr = I2CREAD (ADDRESS, READ_CURRENT_BLUE); // Read the blue current intensity
  redoff = I2CREAD (ADDRESS, READ_OFFTIME_RED); // Read the off-time of the red channel
  greenoff = I2CREAD (ADDRESS, READ_OFFTIME_GREEN); // Read the off-time of the green channel
  blueoff = I2CREAD (ADDRESS, READ_OFFTIME_BLUE); // Read the off-time of the blue channel
  brightness = I2CREAD (ADDRESS, READ_DIMMINGLEVEL); // Read the dimming level   
  I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
  I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x39); // Set off-time of green channel to 0x39
  I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
  I2CWRITE2BYTES (ADDRESS, CURRENT_RED, 0x15); // Set current intensity of red channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_GREEN, 0x15); // Set current intensity of green channel to 0x15
  I2CWRITE2BYTES (ADDRESS, CURRENT_BLUE, 0x15); // Set current intensity of blue channel to 0x15
  I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0000); // LEDs all off as any intensity * 0 will = 0
    }

    delay(100); // OK, so were getting response from the infineon so read back values from slave and print them
    Serial.print("Red Int: ");     redint = I2CREAD (ADDRESS, READ_INTENSITY_RED); // request from shield red colour intensity
    Serial.print("Green Int: ");   greenint = I2CREAD (ADDRESS, READ_INTENSITY_GREEN); // request from shield green colour intensity
    Serial.print("Blue Int: ");    blueint = I2CREAD (ADDRESS, READ_INTENSITY_BLUE); // request from shield blue colour intensity
    Serial.print("Red Curr: ");    redcurr = I2CREAD (ADDRESS, READ_CURRENT_RED); // request from shield peak current reference of red channel
    Serial.print("Green Curr ");   greencurr = I2CREAD (ADDRESS, READ_CURRENT_GREEN); // request from shield peak current reference of green channel
    Serial.print("Blue Curr: ");   bluecurr = I2CREAD (ADDRESS, READ_CURRENT_BLUE); // request from shield peak current reference of blue channel
    Serial.print("Red PWM: ");     redoff = I2CREAD (ADDRESS, READ_OFFTIME_RED); // request from shield off-time of red channel
    Serial.print("Green PWM: ");   greenoff = I2CREAD (ADDRESS, READ_OFFTIME_GREEN); // request from shield off-time of green channel
    Serial.print("Blue PWM: ");    blueoff = I2CREAD (ADDRESS, READ_OFFTIME_BLUE); // request from shield off-time of blue channel
    Serial.print("Walk: ");        walk = I2CREAD (ADDRESS, READ_WALKTIME); // request from shield walk-time
    Serial.print("Brightness: ");  brightness = I2CREAD (ADDRESS, READ_DIMMINGLEVEL); // request from shield brightness level
    Serial.print("FadeTime: ");    fadetime = I2CREAD (ADDRESS, READ_FADERATE); // request from shield fade rate

    // now setup for test
    I2CWRITE2BYTES (ADDRESS, OFFTIME_RED, 0x38); // Set off-time of red channel to 0x38
    I2CWRITE2BYTES (ADDRESS, OFFTIME_GREEN, 0x39); // Set off-time of green channel to 0x39
    I2CWRITE2BYTES (ADDRESS, OFFTIME_BLUE, 0x38); // Set off-time of blue channel to 0x38
    I2CWRITE6BYTES (ADDRESS, CURRENT_RGB, 0x80, 0x80, 0x80); // Set current of red channel to 0x80 = 780mA
    I2CWRITE2BYTES (ADDRESS, FADERATE, 0x0000); // Fade Rate between intensities --> 0.0s
    I2CWRITE2BYTES (ADDRESS, WALKTIME, 0x0000); // walk time between colors = 0s
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0555, 0x0555, 0x0555); // low level White Light
    I2CWRITE2BYTES (ADDRESS, DIMMINGLEVEL, 0x0FFF); // Maximum dimming level means inensity settings are directly used
}

  // the loop routine runs over and over again forever:
  void loop() {
    // change lamp colour to red
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0, 0x0, 0x0); // all off
    delay(1000); // wait 1000ms
    // change lamp colour to green
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x03ff, 0x03FF, 0x03FF); // 25%
    delay(1000);
    // change lamp colour to blue
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x07ff, 0x07ff, 0x07ff); // Blue
    delay(1000);
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0bff, 0x0bff, 0x0bff); // Blue
    delay(1000);
    I2CWRITE6BYTES (ADDRESS, INTENSITY_RGB, 0x0fff, 0x0fff, 0x0fff); // Blue
    delay(1000);
  }



//INFINEON FUNCTIONS NOT INCLUDED SA THERE UN CHANGED, SEE ATTACHMENT

Thanks to Element 14 and the sponsors for the Internet of Holiday Lights contest.

 

While I'm waiting for my components to arrive, I'll lay out my plan.

element14.jpg

 

Part 1:  Control of lights

I'll be using MQTT to control the lights attached to the Arduino Yun.  The Yun will subscribe to a MQTT server on the Raspberry Pi.  Also sitting on the Pi is an installation of OpenHAB.  Using the OpenHAB mobile phone app, you can remotely select the color/pattern/on/off of your home lighting - whether that lighting is for windows or trees.  The Yun subscribes to a MQTT topic for the lighting request.  OpenHAB publishes to this MQTT topic to tell the Yun how to operate the lights.

 

Part 2:  Sensor Control

I'd also like to use the lights as an interactive element.  Using a wireless PIR sensor, I'd like to set off different lighting events when someone approaches the door or driveway.  The PIR sensor will initiate an MQTT topic to OpenHAB, which relays the lighting changes based on time of day, whether or not the behavior is desired (via GUI selection).

 

Part 3:  Coordinated Lighting Show

It would be neat if the lighting can be coordinated with a couple of neighbors.  I don't have the funds for a complete demo of this, but I'd like to work out the technique to use MQTT to coordinate many Yuns so that lighting at several near-by houses can be coordinated.  Imagine if you walk up the drive way of one house, and all the houses around you flash in response.  The neighborhood Yuns could connect to a single master MQTT broker to achieve this effect.  And neighbors can control each other's lighting or neighborhood lighting via the OpenHAB app.

Well, since I've to wait for sometime before getting the boards, I decided to test out a few lighting patterns and the corresponding logic needed to run them. I've used 8 leds and a PIC controller to test out my patterns...I'll port the code to the arduino once I get the board. Even though I am showing eight LEDs, these actually represent the eight bulbs which will be driven by the arduino.... Phase control is a later part which I'll try to incorporate sooner...

 

I've embedded a link below from my first experiment

 

I need start out with the phase control and led strips .... Meanwhile I am fiddling with the RGB strips, audio and the Wi-fi.....I'll post the updates and details sooner..........  C U again ..................

I have been a fan of the audio programming language Chuck ever since i came across it few months ago. Its used by the Laptop Orchestras from the Princeton University and Stanford. For tinkerers like us its a wonderful tool to mix the hardware hacking with computer synthesized sound. I can’t play any instruments. But i can code. I understand math. So this tool frees me to apply my programming skills to create new sounds.

 

I intended to use Chuck in the Holiday Lights Road Test to add music and sound effects. With all the references to Minions through out element14 community, today it struck me that this is a great opportunity to give voice to them.

 

Installing and using chuck is as simple as using Arduino. So go ahead. Download. Install. Check out the tutorial. Play around. Integrate with your awesome projects.

 

Now here is how my part of it works.

Part2-Flow.png

 

For now i am creating the MQTT message through mosquitto_pub which i described in an earlier post. Once i get my shipment of components, my wireless controllers will generate the message. Actually i am going to add capacitive touch to the minion christmas ornaments  and when any one touches the ornaments a MQTT message will be sent out resulting in Chuck generating the sound. (Update Dec 20.. Built it.. See here.. ).. Oops..I forgot.. peteroakes got those minions. Now i have to go shopping for some minions.. Unless Santa doctorcdf has surprised us with some minion ornaments in our package.

 

Screencast showing the software pieces in action:

 

 

 

Chuck Program for Minions (Called a Shred) (Minion.ck)

 

Note: This is a very simple use of sound buffer to load minion wav files. There are more powerful tools in Chuck to create and experiment with new sounds right from scratch. One of my todo list of projects is to create a DIY Drum kit from everyday objects and use chuck to generate actual sound.

 

You can copy this code in to miniAudicle, save it to a folder and drop the sound files in to a wav folder.I have attached the minion wav files for any one to use.

// OSC receiver
OscIn oin;
// OSC message
OscMsg msg;

// this is listening on port 6449 for OSC messages
6449 => oin.port;

// My address is this and i am waiting for a value of type integer
oin.addAddress( "/WiFiTree/Minion/Sound, i" );

//define sound buffer and chuck it to dac
SndBuf buf => dac;

// load the file paths into an array
[
me.dir() + "/wav/Aww.wav",
me.dir() + "/wav/bottom.wav",
me.dir() + "/wav/conv.wav",
me.dir() + "/wav/fight.wav",
me.dir() + "/wav/laugh.wav",
me.dir() + "/wav/ok.wav",
me.dir() + "/wav/what.wav",
me.dir() + "/wav/yay.wav",
me.dir() + "/wav/yell.wav"
] @=> string filePaths[];



while ( true )
{
    // waiting for OSC event
    oin => now;

    // when the message arrived
    while ( oin.recv(msg) != 0 )
    {
        // getInt fetches the expected int
        msg.getInt(0) => int soundIndex;
          <<< "got (via OSC):",soundIndex >>>;
  
          if(soundIndex >= 0 && soundIndex <9)
          {
          filePaths[soundIndex] => buf.read;
          }
        // print
        // set play pointer to beginning
        0 => buf.pos;
    }
}






 

MQTT Subscriber and OSC Message Sender

 

In Part 2.1 i described how i set up MQTT client libraries in Processing. Here, i created the following MQTT Subscriber for listening for those messages. Once the messages are received, I translate them to generate Open Sound Control (OSC) messages to pass them to Chuck.

OscMQTTSubscriber.java:

import org.eclipse.paho.client.mqttv3.*;
import oscP5.*;
import netP5.*;


public class OscMqttSubscriber implements MqttCallback {


OscP5 oscClient;
NetAddress chuckAddress;


public OscMqttSubscriber(OscP5 oscClient,NetAddress chuckAddress) {


    this.oscClient=oscClient;
    this.chuckAddress=chuckAddress;
}


@Override
public void messageArrived(String topic, MqttMessage message)
        throws Exception {
    println(message.toString());
    this.SendOscMessage(message.toString());
}


private void SendOscMessage(String message)
{
    //Create Osc message for address
    OscMessage minionSound = new OscMessage("/WiFiTree/Minion/Sound");

    minionSound.add(Integer.parseInt(message));


    oscClient.send(minionSound, chuckAddress);

    println("messsage sent");
}


@Override
public void connectionLost(Throwable cause) {
    //TODO: handle connection loss scenario
}




@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
}



 

minonsmic.pde

import oscP5.*;
import netP5.*;


OscP5 oscClient;
NetAddress chuckAddress;
MqttClient mqttClient;


void setup()
{
  setupOSCClient(); //set OSC Client first
  setupMQTTClient();
}


void setupOSCClient()
{
  //This sketch is listening for OSC packets as well at port 12000
  //Not necessary in this example but the library doesn't allow just a client creating
   oscClient=new OscP5(this,12000);
   chuckAddress = new NetAddress("127.0.0.1",6449);
}


void setupMQTTClient()
{
  try{
     mqttClient=new MqttClient("tcp://localhost:1883", "ProcessingTestClient");
     mqttClient.connect();

     OscMqttSubscriber oscMqttSub=new OscMqttSubscriber(oscClient,chuckAddress);
     mqttClient.setCallback(oscMqttSub);

     mqttClient.subscribe("WiFiTree/FromController/MinionSound");
  }catch(Exception ex)
  {
    println(ex.getMessage());
  }
}


void draw()
{
}



 

 

Hope this post helps some one to add a new tool to their kit.

Index of all the blog posts related to the Wifi Interactive Christmas Tree project is here.

 

While waiting for my Arduino Yun to arrive for my WiFi Christmas Tree hardware build, i decided to complete as many software components as possible.

I am planning to use my PC and Mac for all the music and sound generation. They will be MQTT subscribers. So first i decided to setup MQTT client on Processing.

 

MQTT Java Client Libraries

 

Since Processing uses Java runtime, i got the Java client libraries from Eclipse foundation web site. I needed just the jar file.

http://repo.eclipse.org/content/repositories/paho-releases/org/eclipse/paho/mqtt-client/0.4.0/mqtt-client-0.4.0.jar

 

MQTT Library Setup in Processing

 

I wanted to set up the MQTT library for future use as well. So i installed it in the main Library folder so that it appears in the processing import library menu. Even if you are installing it in the contributed libraries folder, you will still have to follow the naming conventions described below. Otherwise processing won’t recognize it.

 

On a Windows PC

Find the installation directory of processing in your machine and navigate down to the Libraries folder.  On my machine its at

C:\processing-2.2.1\modes\java\libraries



 

On a Mac

 

Open Finder. Go to Applications. Find Processing. Right click and choose “Show Package Contents"

Contents > Java > modes > java > libraries



 

This is important. Processing doesn’t recognize the libraries if they are not setup in a particular way and the names do not match. So i had to be precise in the following steps to get it recognized by processing.

  1. Created a folder named “mqtt"
  2. Within this folder created another folder named “library"
  3. Copied the downloaded mqtt-client-0.4.0.jar file to this folder.
  4. Renamed the jar file to “mqtt.jar” (the jar file cannot have hyphens or it cannot be different from the folder name. Hence the renaming)
  5. Closed all Processing IDE windows and reopened

 

Now i could see the mqtt library appearing in the Sketch>Import Library Menu

 

Testing the MQTT Library setup

I created a new sketch and ran this code. I could see my MQTT messages from processing are retrieved by the mosquitto_sub client.

import org.eclipse.paho.client.mqttv3.*;


void setup()
{
    String broker   = "tcp://localhost:1883";
    String topic    = "WiFiTree/FromProcessing/RGBTest";
    String payload  = "255,232,233";

        try {
            MqttClient myClient = new MqttClient(broker, MqttClient.generateClientId());
            MqttMessage message ;
         
            myClient.connect();
         
            for(int i=0;i<10;i++)
            {
                message = new MqttMessage((payload+ ", Test Msg " + i).getBytes());
                myClient.publish(topic, message);
            }
            myClient.disconnect();


        } catch(MqttException mex) {

            System.out.println("Error: "+mex.getMessage());
            mex.printStackTrace();
        }
}



 

Results from mosquitto_sub

fromProcessing.png

 

MQTT Subscriber

 

In Part 2 of this post, i will show how i used the processing sketch as a subscriber and sent OSC messages to Chuck to make the minions speak.

Thanks to Element14 and MCM Electronics, Infineon for Selecting my proposal for my Cool Holiday Lightings...


Here is my project idea...


My IOT Holiday Lightings…

 

Introduction:

In this roadtest I would love to design IOT based color lightings using Infineon Lightning RGB LED Arduino Shield and Arduino yun.

In my application I will use simple RGB LED strip to create variable brightness effects and NeoPixel RGB LED Strip which create awesome lightning pattern(Waves, running light etc..), which is controlled from internet or intranet using Android/IoS smart phoneapplication.

 

Description:

Hardware:

Infineon Lightning RGB LED Arduino Shield: Used for control RGB LED strip.

Arduino yun : Used for communicating to internet/intranet over WiFi . It also controls RGB LED Strip via Infineon Lightning RGB LED Arduino Shield and NeoPixel LED Strip via I2C.

5V DC Supply: To drive arduino Yun and Neo Pixel LED Strip.

12V DC Supply: Infineon Lightning RGB LED Arduino Shield.

 

Software:

Android/IoS application will be designed for control LED brightness and patterns over internet.

Some common pattern like running lights, Wave effects etc will be control via widgets on application.

 

Detailed block diagram of my road test application is given below...

 

 

Untitled.png

About Me:

I am software engineer and working as professor in Marwadi Education Foundation Rajkot, INDIA. Also I am Electronic Hobbyist and I likes to play with Arduino, Raspberry Pi. I am applying for this roadtest because, LED lightings amaze me and I would love to create such maazing lighting application.. Looking forward for lots of fun while design this if selected..

 

Thanks,

Madhuri

dragonstyne

Holiday Lights

Posted by dragonstyne Top Member Dec 12, 2014

Greetings Everyone,

 

With Holiday season upon us and in celebration of the Element14

The Internet of Holiday Lights Road Test


I thought I would share my experience with using the Arduino Uno R3 in creating a holiday light display as well as adding the Infineon RGB Lighting Shield with XMC1202 for The Arduino to the mix.


First, Here is a display I did using an Arduino Uno Rev3 and GE G35 Christmas lights.

 


This is what we will start with and go from there.



Don't Get Me Started

 

There are a plethora of possibilities for control of LEDs.

 

The first thing to consider is what type of LEDs you wish to control:

 

Single fixed color LEDs

Single RGB multicolor LEDs

Tape or String of fixed color LEDs

Tape or String of multiple fixed color LED arrays

Tape or String of RGB multicolor LEDs

Finally, last but definitely not least, the individually addressable RGB Pixels (My display was constructed with these)

 

The type you choose will determine how they are controlled.

 

The second thing is how you want to control:

 

PIC

Arduino

Infineon

RPI

Pack Mule

Etc...

 

The possibilities are literally endless. Each one has its own method and, in some cases, colorful language that is required for effective control.

 

I hope to be able to address these as we go along.

 

 

Here are my lights for 2014

 

 


-Steve




Hi everyone,

 

I was thinking of creating an easier way for users to program their ATmega328p MCU's, so I purchased an Arduino Uno and made an ATmega328p Shield for it. While I keep seeing people popping their MCU's out of their boards, I wanted to try to provide a solution to where they wouldn't have to keep removing their MCU's from their Arduino kits in order to program a circuit.

 

I spent the night soldering getting things working on the prototype shield, and drafted up the sketch firmware in about an hour or two sending over a basic Blink program in binary mode over to the ATmega328p Shield frpom the Arduino Uno.

 

Here is a video of the prototype Arduino Shield in working action: http://youtu.be/SdATQFxE6kM

 

I also attached the sketch the prototype board is using, documentation about the firmware commands and a full programming guide to help users get their hex file data onto the MCU's.

Likewise, users can just select the MCU's as is an access the EEPROM for data storage very easily if they don't want to utilize the MCU Flash.

 

Basically, the firmware allows the user to select the MCU as an SPI device in Slave mode. Based on 16 commands, some unallocated to leave room for improvement from other users, the board has an indicator LED, pin 13 to traditionally show the user when the MCU is selected.

 

I gave examples in the documentation I have provided, which is pretty interesting. It seemingly uses an interpreted scheme converting user defined data entry in direct executable operation, kinda like the Parallax series does.

 

Hope you guys enjoy,

 

Feel free to write back, I'd be happy to help contribute to the community and believe this device would help many people out.

This way the users won't have to disassemble their Arduino units anymore. They can write to it with the ATmega328p Shield.

 

Then they can remove the newly programmed MCU from the Shield to put in circuit.

 

Thanks!

IMG_4028.jpgIMG_4040.jpg

I also created some HEX2MCU software which loads in program and bootloader hex files, converts them over to firmware commands and then the Arduino programs the MCU on the shield based on those instructions that were converted from hex to firmware commands.

ATmega328pHEX2MCUsoftware.PNG

 

So far, I have 0% error in data transfer rate making this very efficient.

What are the available modules that connects with an Arduino to send voltage data over the Mobile network?

Need some advice here. If not what other GSM/GPRS+GPS Module can work?

Prelude

The holidays mean different things to different people. To kids it means gifts, to teens it means time off, to the professional its a time to be away from the stress of daily life, to the mother it means a display of culinary skill and to the elderly it means a time when lots of people visit. Whatever may be means, the end result is a fun time and sharing of happiness. This proposal is based on a couple of problems in mind.

 

The Proposal

Our living room is neither very big nor very 'fashionable' but its the place where we entertain all our guests. The entire plan is divided into three parts and is explained as follows:

 

A. First the mood:

As stated before, the lighting is responsible for creating the right mood. Additionally, the requirement is for the entire setup to have a grand feel hence I planned to line the entire window site with RGB LED lights!. They will be of higher intensity such that they make the entire curtain system glow in the mood light. This has the additional advantage that they will be visible from the outside as well which will give the windows a good look from the outside. 

The lights will have two modes explained as follows:

     a. These lights will be connected to the Internet and their color can be manually controlled using anything with a web browser.

     b. There is an automatic mode which allows the lights to be connected to the Internet such that they will respond to

          - The weather and temperature retrieved from the Internet. If its colder outside, the lights will become a warmer shade of yellow so as to produce a cosy feel.

          - greetings exchanged over social media. E.g The lights will also cycle through shades of the above mentioned color when someone tweets seasons greetings like 'happy new year' or 'merry xmas' etc.

     c. Audio Mode which uses a microphone to detect loud sound beats and make the mood lights act as dance music.

These lights are expected to be waterproof strips of RGB LEDs which can simple blend into the BG and allow them to remain fixed around the year.

 

Second - the decoration:

We need a decoration which is not necessarily a Christmas tree. The concept here is to populate the wall with decorations that blend in as well as pop up. The simplest way to do that is to use wall mount decor with RGB LEDs in the decor. Our requirement is wall mounted which means the part of the wall near the windows will have to be decorated with custom ornaments, hangings and electronics.

 

The IOT end of the decor is again RGB LEDs which are connected to the Internet. Instead of using strips, of LEDs, I plan to use RGB LED chains. I got some already and tested them out. Each RGB LED is addressable like Adafruit's Neo Pixels

 

Functionality is similar to the Mood lights but has one difference.

     - Game mode: The noisy mode will use the sound sensor to detect loud noises made by kids and will randomly shuffle through the colors. Then will select a color depending on the noise input. This will act as a game for kids to play with and keep them preoccupied for some time. I am still working on this one and it will probably evolve with time.

 

Third- IOT Santa

It won't be much of a christmas without Santa. I plan to have either a small Santa doll or a picture with Santa Clause Drawn on it. In the figure's hand will be a bell- a real bell and the hand will be connected to a servo motor. The system will also be connected to the internet and actions controlled by event on social media. When someone tweets or posts on facebook with seasons greetings, Santa will ring the bell. This adds the sound element to the light element of the mood lights. I will also try and get those cheap ICs with stored christmas carrols and hook it up to santa as well.

 

Part four- The Christmas tree

The tree is an individual unit and can be packed up for storage. The concept is simple. Have a tree with lights. The difference is to have the LEDs controlled by sound and a timer! The lights to be used here are chainable RGB LEDs which glow randomly through out the day. The smart light functionality is as follows:

- On christmas eve the lights will all glow white. As Christmas nears, the LEDs will start turning Red starting from the base, rising to the top while blinking. Slowly the entire tree will look like it is "Charging up with Christmas Magic" and at the stroke of midnight, the Start on Top will glow brighter with the different colors.

The tree will only be connecting to the internet for time and the rest will be taken care of by the arduino itself.

 

This challenge is not just about using technology but creating something aesthetic. The expriment will be done in our living room so it better be good or else

 

Lets see how it goes...

As i mentioned in the introduction i am waiting for parts to arrive. Meanwhile i started to set up my MQTT infrastructure.

 

My initial plan was to use the sandboxed MQTT Broker available at iot.eclipse.org at port 1883. Then i decided to explore more about the MQTT Broker and wanted to run one locally on my PC and use it as the MQTT gateway for all my needs. Since the Mosquitto broker allows bridging, it should be possible for me to selectively choose “topics” to forward to one or more of sandboxes available on the internet.

 

Installation


The sandboxed MQTT broker above is running the Open Source Mosquitto broker in its version 1.3.1. So i got the broker for windows downloaded from http://mosquitto.org/download/ and installed. After the installation is complete, I could see the Mosquitto Broker services in the control panel. I found that the service is not started by default so i started the service.

I also went ahead and installed the Mosquitto broker on my Mac. This way i can test the bridge functionalities locally. In addition this allows me to make my PCs as MQTT Publishers and subscribers. The audio elements in my project will run from my Mac or PC by subscribing to the appropriate MQTT topic.

When i get my Arduino Yun, it should be possible for me to run the Mosquitto broker on the Yun as well since a OpenWrt version is available at the same download url.

 

Verifying the Install


In the install directory, there were two handy utilities that were available.

  • mosquitto_sub  — A command line utility for subscribing to Topics
  • mosquitto_pub  — A command line utility for publishing simple messages one at a time

 

On Mac these were available at:

/usr/local/opt/mosquitto/bin


 

On PC these were available at:

C:\Program Files (x86)\mosquitto


 

Running mosquitto_sub

 

First i ran the mosquitto_sub with the wild card “#” for the topic name in one terminal window. This allowed me to watch every message that is being sent to my gateway. This will be very useful if i run into issues later in the project and need to debug.

mosquitto_sub -h localhost -v -t "#"

-v is for making the output verbose. This will print the Topic name as well along with the actual message payload.

 

Running mosquitto_pub

Then i opened another terminal window and ran the mosquitto_pub to send some test messages out.

mosquitto_pub -t WiFiTree/RGB -m "210,230,0"

mosquitto_pub -t WiFiTree/RGB -m "0,0,0"

mosquitto_pub -t WiFiTree/Sound -m "0.2"


I could see that the setup is working correctly when the outputs started appearing in the subscriber window. Here are the screen shots for both Subscriber and publisher.

 

Mac OSX

mac1.png

 

Windows

PC1.png

 

Setting up the Bridge on Mac to forward certain topics to MQTT Bridge on PC

 

Before setting up the bridge to sandbox brokers on the net, i wanted to set up the bridge between my broker on Mac and PC. This would allow me to bring these machines also in to my holiday project infrastructure to play sound and other things that i have not thought of yet. There isn’t any specific need for me to run multiple brokers. But i just wanted to test out the capability because some day it might come handy.

 

So on Mac i modified the well documented mosquitto configuration file at

/usr/local/etc/mosquitto/mosquitto.conf

 

and added the following:

connection mywindowsmqttbroker
address 192.168.1.217
topic WiFiTree/ForWindowsPC/Test

 

This configuration should enable the MQTT broker on Mac to forward only the MQTT messages with the topic  "WiFiTree/ForWindowsPC/Test” to my windows PC.

 

After the configuration change I restarted my mosquito demon and sent out some test messages from my mac:

mosquitto_pub -t WiFiTree/ForWindowsPC/Test -m "Test MQTT bridge message for Windows From Mac"

 

Success!!!. i was able to see that my Windows PC was receiving only those topics from mac.

PC2.png

 

Now that my MQTT brokers are set up the way i want, each of the modules of my WiFi Christmas Tree project can be individually tested and put together.

 

Some thought for future exploration

 

As many of you might have already done, the routers can be modified to run OpenWrt. Since a openWrt version of MQTT broker is available, the router might be the right place to run a home specific MQTT broker. I hope someday router manufacturers by default will put a MQTT broker on their products making it easier for deploying connected devices. My router is not modified to run openWrt. One day i will get around to do that.

 

Document Links

http://mosquitto.org/documentation/

I am excited to be selected as one of the finalists for the Internet of Holiday Lights RoadTest Plus! Thanks Element14 and Christian!!!


I hope to learn and share as many things as possible along the way as i begin my build. As of now i have the following outline for the blog posts. I will link them as i complete each section of my build.



Since the stakes are high looking at the incredible proposals i see from every other finalist, i have updated my proposal to include as many elements as possible and i will add to it as i go along depending on the time constraint.


Update Jan 1 2015: Here is an updated list of modules. The LDR control and the Twitter are pending. The touch enabled minion ornaments and the color catching glove were not in my thoughts when i applied for this road test. Those evolved during the contest and i have ended up completing them before the LDR based RGB controlled. Not sure if i will have the time to build those as i will have travel away for work the next two weeks.

Copy of WiFi Christmas Tree V3 - New Page-2.png


I am leaving the original diagram here for historical purposes.


WiFi Christmas Tree V2 - New Page-2.png



I am constrained by the number of WiFi enabled devices that i have. I might resort to running some of the elements in a wired mode.

Update Jan1 2015: The ESP8266 has removed the WiFI enabled device constraint.


As i teach myself electronics, i hope to learn more and share as much as possible with this wonderful community.


I have ordered some more parts and light strips. I am waiting for the package from element 14. Meanwhile i will start building up the modules that don't need any of the parts. Probably i will do the builds without WiFi and add them once i get them.


Good luck every one.

This is part II of a three part post.

Please read Part I QLab Midi Controller for an introduction to the project.

 

Parts Required

1x Teensy 3.1 - https://www.pjrc.com/store/teensy31.html

1x 60mm Illuminated Arcade Button - http://www.arcadeworlduk.com/products/High-Profile-60mm-Arcade-Button.html

1x Rectangular Arcade Button - http://www.arcadeworlduk.com/products/Rectangular-Illuminated-Arcade-Button.html

1x Triangular Arcade Button - http://www.arcadeworlduk.com/products/Triangular-Arcade-Button.html

5x 5V Wedge Base LEDs - http://www.arcadeworlduk.com/products/awuk-5v-10mm-wedge-base-led.html

1x Hammond Instrument Enclosure - http://uk.farnell.com/hammond/1456fg4bkbu/enclosure-aluminium-instrument/dp/1415246

1x USB A TO MINI B PLUG - http://uk.farnell.com/bulgin/px0441-2m00/cable-usb-a-plug-to-usb-mini-b/dp/1229677

1x USB B RECEPTACLE (PANEL) - http://uk.farnell.com/bulgin/px0443/connector-usb-b-receptacle-panel/dp/1229685

1x Sacrificial Micro-USB cable

 

Schematic

The wiring for the controller is very simple. Internal pull-ups negate the need to resistors on the switches. I’ve put together a very rough schematic in Fritzing. Please let me know if you have any questions, comments or suggestions.

schematic.png

 

Operation

 

When powered up all three of the buttons will illuminate.

 

The Go button is intended to fire the currently selected cue. To do this it sends a MIDI note to the computer when the button is pressed, and turns the note off when the button is released. During this time the go button will blink 3 times.

 

The next button will send a different note to the computer when pressed. The LED on this button will extinguish while the button is pressed.

 

The Stop button has two functions. QLab will fade all active cues when the ‘Panic’ button is pressed. The time of this fade can be modified in the preferences. If the button is pressed a second time the track will stop immediately. To reflect this, the first press of the stop button will cause the button to flash for three seconds. the second press will cancel the flash and re-illuminate the button.

 

 

 

Construction

The enclosure front was cut to accommodate the three buttons, the rear face was cut to accept the panel mounted USB receptacle (apologies for the lack of photos). Each of the Buttons was installed and four cables were run to each of them. The Teensy and wire ends were then mounted onto a piece of strip-board

IMG_1335.JPGIMG_1336.JPGIMG_1339.JPG

 

The inclusion of the specific Bulgin connectors are purely optional, I chose them because the USB cable can be ‘locked’ in place, and a standard Mini USB can also be accepted.

 

 

The QLab MIDI Controller Arduino code will follow in part III.

This project is still work in progress. Comments, questions, and suggestions are welcome.

gadget.iom

QLab Midi Controller

Posted by gadget.iom Top Member Dec 10, 2014

This is my first blog post on Element 14. I have recently completed a small electronics project and wanted to share it with anybody who may wish to make on of their own. But first some background....

 

 

What is QLab?

Any Mac user with a reasonable footing in theatre sound production has probably heard of QLab already. For those who haven't it is an application that allows you to control music and/or video for live productions. There is also a great deal of integration possibilities for advanced show control. More information about QLab can be found here: Figure 53 | QLab | Live Show Control for Mac OS X

 

Why this project?

I was approached by a colleague a few months ago who who had seen an online tutorial for creating a QLab remote from a dismantled keyboard. The membrane was connected to buttons that were used to simulate keypresses that activated hotkeys within the software. We immediately thought that we could do something more elaborate. After a brief initial consideration of using an Adafruit Trinket to emulate keyboard presses we changed the design entirely and decided to use MIDI instead.

 

 

MIDI Control

The free edition of QLab allows remote control via MIDI. The primary advantage of MIDI is that the activation of cues would no longer be dependent on the application having "focus". We looked into reprogramming the Trinket to output MIDI and then employed a MIDI to USB convertor with mixed results. This was mostly due to the quality of the usb device.

midi2usb.jpg

What we really needed was native MIDI over USB support which the trinket (while capable of performing keyboard emulation) did not appear to support, and so we looked into alternative micro-controllers.

 

 

The Teensy 3.1

PJRC had recently released version 3.1 of their Teensy Development Board and a quick investigation indicated that it was capable of outputting MIDI over USB. Full details of the USB MIDI capabilities can be found here: https://www.pjrc.com/teensy/td_midi.html

 

 

The Build

Our intention was to keep the unit as simple to operate as possible. After a fair bit of consideration a design featuring only three buttons was created. These give the operator the ability to 'Go', 'Panic' (Stop), and advance down to the next cue. This was added so that unnecessary cues (such as fades) could be skipped if required.

 

We elected to use some heavy duty LED backlit buttons from Arcade World, in addition to being virtually bullet proof, we were also able to insert legends indicating the function of each button.

 

 

Full build details are available in Part II QLab MIDI Controller - The Build.