Friday, May 22, 2020

ATOM Matrix: Using an I2C Keyboard

Besides supporting analog sensors, the ATOM's Grove port can also be used to interface with I2C sensors. This post demonstrates how to do this using an I2C keyboard. First we read keyboard input into a character array. In the second application we filter and transform incoming characters. Finally, we combine that with the scrolling text message code from an earlier post.

The first two applications should work almost unchanged on regular ESP32 (or even ESP8266) dev boards.

Experimenting (i.e. playing) with the keyboard, there is a problem: the Sym + "." key does NOT return the ">" character.


Store Keyboard Input into a Character Array

The CardKB is handy method of getting user input, but for getting sequences of characters, we must build the result one keypress at a time. The following application does that, and in addition:

  • The maximum length of the character array is enforced
  • When the backspace key is pressed, the last character of the array is removed
  • When the escape key is pressed, the character array is cleared
  • When the return key is pressed, input is "finalized" in that no additional characters are added to the result

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
 * CardKB-Keyboard-00.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Read input from an I2C keyboard and store
 * result in a character array
 * 
 * Demonstrates basic char array usage
 * 
 * See post on patriot-geek.blogspot.com
 * for details
 */

#include "M5Atom.h"

#define CARDKB_ADDR 0x5F

#define BKSP 8
#define CR 13
#define ESC 27

const int maxMessageLength = 16;
char msg[maxMessageLength];
uint8_t charIndex = 0;
bool messageEntered = false;

void setup() 
{
  M5.begin(true, true, true);
  delay(20);
  Wire.begin(26, 32);
  Serial.println("");
}

void loop() 
{
  Wire.requestFrom(CARDKB_ADDR, 1);

  while(Wire.available() && !messageEntered)
  {
    char c = Wire.read();
    
    if(c != 0)
    {
      Serial.print(c);
      Serial.print(F(" - "));
      Serial.println(c, DEC);

      if(charIndex >= 0 && charIndex < maxMessageLength || c == BKSP || c == CR || c == ESC)
      {
        if(c != BKSP && c != CR && c != ESC)
        {
          msg[charIndex++] = c;
        }
        else if(c == BKSP && charIndex > 0)
        {
          msg[--charIndex] = '\0';
          Serial.print(F("Backspace! "));
        }
        else if(c == ESC)
        {
          charIndex = 0;
          memset(msg, 0, sizeof(msg));
          Serial.print(F("Resetting input! "));
        }
        else if(c == CR)
        {
          messageEntered = true;
          Serial.print(F("Done! "));
        }
      }
      else
      {
        Serial.print(F("Maximum message length reached! "));
      }

      Serial.print(F("msg = "));
      Serial.println(msg);
      Serial.print(F("charIndex = "));
      Serial.println(charIndex);
    }
  }
}

First thing to notice is that Wire.h is apparently not included. As it goes, when the second argument of the M5.begin command is true (line 31), the M5 API includes Wire.h for us. Here's a line-by-line explanation of the code:

Line Comment
18 I2C bus address of the CardKB
20 - 22 ASCII code for backspace, enter key, and escape key
25 Array of characters, with length specified in line above
26 Current character (think of it as a cursor position)
27 When messageEntered becomes true, we are done getting input!
31 Second argument is true, so Wire.h will be included
33 Initialize the Wire library using pins 26 and 32 for SCL and SDA, respectively
41 If messageEntered is false
43 Read one byte as a character
45 If we have a non-zero character
47 - 49 Print it in the serial monitor
51 Enforce max length requirement, but let BKSP, CR, and ESC through
53 If character is not one of those three
55 Increment charIndex and add c to end of the char array
57 If incoming character is a backspace
59 Decrement charIndex and fill with null terminator
62 If it is the escape character
64 Reset charIndex
65 Empty out the msg char array
68 - 72 If character is carriage return, we are done!
76 Ignore incoming character as msg is as long as we allow
79 - 82 Display the msg and the charIndex after each keypress


Filtering and Transforming Keyboard Input

In order to display the message entered by the keyboard, we must do the following:

  • Lower-case letters are converted to upper case letters (since that is what the 5 x 5 font has available)
  • Characters other than letters and digits are ignored (for the same reason)

It makes sense to do these just before the incoming character is added to the msg char array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
 * CardKB-Keyboard-01.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Read input from an I2C keyboard, filter and 
 * transform it
 * 
 * See post on patriot-geek.blogspot.com
 * for details
 */

#include "M5Atom.h"

#define CARDKB_ADDR 0x5F

#define BKSP 8
#define CR 13
#define ESC 27

const int maxMessageLength = 16;
char msg[maxMessageLength];
uint8_t charIndex = 0;
bool messageEntered = false;

void setup() 
{
  M5.begin(true, true, true);
  delay(20);
  Wire.begin(26, 32);
  Serial.println("");
}

void loop() 
{
  Wire.requestFrom(CARDKB_ADDR, 1);

  while(Wire.available() && !messageEntered)
  {
    char c = Wire.read();
    
    if(c != 0)
    {
      Serial.print(c);
      Serial.print(F(" - "));
      Serial.println(c, DEC);

      if(charIndex >= 0 && charIndex < maxMessageLength || c == BKSP || c == CR || c == ESC)
      {
        if(c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c == ' ')
        {
          msg[charIndex++] = c;
        }
        else if(c >= 'a' && c <= 'z')
        {
          msg[charIndex++] = c - 32;
        }
        else if(c == BKSP && charIndex > 0)
        {
          msg[--charIndex] = '\0';
          Serial.print(F("Backspace! "));
        }
        else if(c == ESC)
        {
          charIndex = 0;
          memset(msg, 0, sizeof(msg));
          Serial.print(F("Resetting input! "));
        }
        else if(c == CR)
        {
          messageEntered = true;
          Serial.print(F("Done! "));
        }
      }
      else
      {
        Serial.print(F("Maximum message length reached! "));
      }

      Serial.print(F("msg = "));
      Serial.println(msg);
      Serial.print(F("charIndex = "));
      Serial.println(charIndex);
    }
  }
}

The only real difference between this code and the previous app's is that instead of indiscriminately adding the incoming character to the end of msg (lines 53-56 in first application) we do the following:

Line Comment
51 If the incoming character is either a digit, an upper-case letter, or a space
53 Increment charIndex and add it to the end of msg
55 Else if the incoming character is a lower-case letter
57 Increment charIndex, convert it to uppercase, and add it to the end of msg


Displaying Input

This last application combines the above keyboard input code with the code for displaying scrolling text from an earlier post, each wrapped in its own function.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/*
 * CardKB-Keyboard-02.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Read input from an I2C keyboard and display it!
 * 
 * See post on patriot-geek.blogspot.com
 * for details
 */

#include "M5Atom.h"
#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>

#define DISPLAY_PIN 27
#define CARDKB_ADDR 0x5F

#define BKSP 8
#define CR 13
#define ESC 27

int directionAndOrientation = NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS;
int pixelType = NEO_GRB + NEO_KHZ800;

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(5, 5, DISPLAY_PIN,
  directionAndOrientation + NEO_MATRIX_PROGRESSIVE,
  pixelType);

int xPos  = matrix.width();

const int maxMessageLength = 16;
char msg[maxMessageLength];
uint8_t charIndex = 0;
bool messageEntered = false;

void setup() 
{
  M5.begin(true, true, true);
  delay(20);
  Wire.begin(26, 32);
  Serial.println("");

  matrix.begin();
  matrix.setTextWrap(false);
  matrix.setBrightness(60);
  matrix.setTextColor(matrix.Color(80, 0, 80));
}

void loop()
{
  if(!messageEntered)
  {
    getMessageFromCardKB();
  }
  else
  {
    displayMessage(msg);
  }
}


void getMessageFromCardKB() 
{
  Wire.requestFrom(CARDKB_ADDR, 1);

  while(Wire.available() && !messageEntered)
  {
    char c = Wire.read();
    
    if(c != 0)
    {
      Serial.print(c);
      Serial.print(F(" - "));
      Serial.println(c, DEC);

      if(charIndex >= 0 && charIndex < maxMessageLength || c == BKSP || c == CR || c == ESC)
      {
        if(c >= '0' && c <= '9' || c >= 'A' && c <= 'Z' || c == ' ')
        {
          msg[charIndex++] = c;
        }
        else if(c >= 'a' && c <= 'z')
        {
          msg[charIndex++] = c - 32;
        }
        else if(c == BKSP && charIndex > 0)
        {
          msg[--charIndex] = '\0';
          Serial.print(F("Backspace! "));
        }
        else if(c == ESC)
        {
          charIndex = 0;
          memset(msg, 0, sizeof(msg));
          Serial.print(F("Resetting input! "));
        }
        else if(c == CR)
        {
          messageEntered = true;
          Serial.print(F("Done! "));
        }
      }
      else
      {
        Serial.print(F("Maximum message length reached! "));
      }

      Serial.print(F("msg = "));
      Serial.println(msg);
      Serial.print(F("charIndex = "));
      Serial.println(charIndex);
    }

    delay(1);
  }
}


void displayMessage(char message[])
{
  Serial.print("Displaying ");
  Serial.println(msg);

  String msgString = String(message);
  int msgLength = msgString.length();
  int charWidth = 5;
  int numTrailingSpaces = 3;
  int maxLeftPosition = (msgLength + numTrailingSpaces) * (charWidth + 1);
  
  int scrollDelay = 100;

  while(true)
  {
    matrix.fillScreen(0);
    matrix.setCursor(xPos, 0);
    matrix.print(msgString);
  
    if(--xPos < -maxLeftPosition)
    {
      xPos = matrix.width();
    }
    
    matrix.show();
    delay(scrollDelay);
  }
}

Click here to go to the table of contents for this series.

ATOM Matrix: Grove Digital and Analog Sensors

The Grove system is a standardized connection system that allows users to avoid breadboards, jumper wires, or soldiering in order to rapidly build prototypes. The connectors all use four wires: GND, VCC, plus two signal wires. These connectors connect a processor (Arduino, Raspberry Pi, ESP32, etc.) to a Grove module. These modules typically address a single function. The information in this section is based off of the Seeedstudio wiki page.

Grove modules come in four types:

  • Digital
  • Analog
  • I2C
  • UART

The functions of the 4 wires for each type of module are as follows:

Type Pin 1 (Yellow) Pin 2 (White) Pin 3 (Red) Pin 4 (Black)
Digital Primary Digital I/O Secondary Digital I/O VCC 5V or 3.3V GND
Analog Primary Analog I/O Secondary Analog I/O VCC 5V or 3.3V GND
I2C SCL SDA VCC 5V or 3.3V GND
UART RX TX VCC 5V or 3.3V GND

Two modules will be used in this post, a Passive IR (PIR) sensor (digital) and a potentiometer (analog). The code for each is trivial and so is presented without comments.

With the exception of the display, all of the code here can be used for other ESP32 or ESP8266 boards with minimal changes.


Digital Grove Sensor: PIR Motion Sensor

This application reads the PIR sensor, and when motion is detected, the display will be red, otherwise it will be green.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * Grove-Motion-Sensor.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Demonstrates how to read values from a PIR motion sensor
 * 
 * See post on patriot-geek.blogspot.com
 * for details
 */

#include "M5Atom.h"

int GRB_COLOR_WHITE = 0xffffff;
int GRB_COLOR_BLACK = 0x000000;
int GRB_COLOR_RED = 0x00ff00;
int GRB_COLOR_ORANGE = 0xa5ff00;
int GRB_COLOR_YELLOW = 0xffff00;
int GRB_COLOR_GREEN = 0xff0000;
int GRB_COLOR_BLUE = 0x0000ff;
int GRB_COLOR_PURPLE = 0x008080;

int sensorPin = 32;
int currentValue = 0;

void setup() 
{
  M5.begin(true, false, true);
  delay(20);
  
  pinMode(sensorPin, INPUT);
}

void loop() 
{
  currentValue = digitalRead(sensorPin);
  
  if(currentValue)
  {
    displayColor(GRB_COLOR_RED, 25);
  }
  else
  {
    displayColor(GRB_COLOR_GREEN, 25);
  }

  delay(100);
  M5.update();
}


void displayColor(int activeColor, int brightness)
{
  M5.dis.clear();
  M5.dis.setBrightness(brightness);
  
  for(int i = 0; i < 25; i++)
  {
      M5.dis.drawpix(i, activeColor);
  }
}


Analog Grove Sensor: Potentiometer

Here, the ATOM Matrix reads from a potentiometer and displays the data. The potentiometer returns values in the range 0 to 4095, except that the high value is returned when the knob is turned all the way to the left! We reverse this in lines 43 - 45.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
67
68
69
/*
 * Grove-Angle-Sensor.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Demonstrates how to read values from a Grove potentiometer
 * 
 * See post on patriot-geek.blogspot.com
 * for details
 */

#include "M5Atom.h"

int GRB_COLOR_WHITE = 0xffffff;
int GRB_COLOR_BLACK = 0x000000;
int GRB_COLOR_RED = 0x00ff00;
int GRB_COLOR_ORANGE = 0xa5ff00;
int GRB_COLOR_YELLOW = 0xffff00;
int GRB_COLOR_GREEN = 0xff0000;
int GRB_COLOR_BLUE = 0x0000ff;
int GRB_COLOR_PURPLE = 0x008080;

int activeColor = GRB_COLOR_GREEN;

int sensorPin = 32;

int lastValue = 0;
int currentValue = 0;

void setup() 
{
  M5.begin(true, false, true);
  delay(20);
  
  pinMode(sensorPin, INPUT);
}

void loop() 
{
  currentValue = analogRead(sensorPin);

  int mappedCurrentValue = map(currentValue, 0, 4095, 25, 0);
  int mappedPreviousValue = map(lastValue, 0, 4095, 25, 0);
  int brightness = map(currentValue, 0, 4095, 25, 0);

  if(mappedCurrentValue != mappedPreviousValue)
  {
    displayValue(mappedCurrentValue, brightness, activeColor);
    Serial.print(currentValue);
    Serial.print(" -> ");
    Serial.println(mappedCurrentValue);
    lastValue = currentValue;
  }
  
  delay(50);
  M5.update();
}

void displayValue(int val, int brightness, int desiredColor)
{
  M5.dis.clear();
  M5.dis.setBrightness(brightness);
  
  for(int i = 0; i < val; i++)
  {
      M5.dis.drawpix(i, desiredColor);
  }
}

In the next post in this series we use the Grove IR Remote module to reverse engineer a DVD remote! See you then, intrepid reader - same blog time, same blog channel!

Click here to go to the table of contents for this series.

ATOM Matrix: Advanced Display Usage

As we saw in a previous tutorial, the ATOM Matrix's display is nothing but an array of WS2812B LEDs, commonly called NeoPixels. As such, we can use various libraries developed by Adafruit.

First, install the following libraries using the Arduino IDE's Library Manager:

  • Adafruit GFX Library - foundation of the other graphics libraries
  • Adafruit NeoPixel - for controlling NeoPixel strips
  • Adafruit NeoMatrix - for controlling NeoPixel grids
  • FastLED - includes various effect and noise functions for making interesting animations

These libraries all come with examples, especially the FastLED library. Before examining those examples, here is an example of displaying strings.


Scrolling Text Messages

To display text messages, we must first have a font! The Adafruit GFX library includes many fonts (found in the Adafruit_GFX/Fonts folder, which on the Mac is at ~/Documents/Arduino/libraries/Adafruit_GFX/Fonts), unfortunately they are all of size 8 x 8. A 5 x 5 font can be found in Lucasmaximus89's Github page at https://github.com/lukasmaximus89/M5Atom-Resources. The specific URL for the font is https://github.com/lukasmaximus89/M5Atom-Resources/blob/master/glcdfont.c. This font has character definitions for uppercase letters and digits, plus other characters - but those other characters are mostly unreadable.

Download this font and move it into the Adafruit_GFX/Fonts folder. By default, the GFX library looks for a file called "glcfont.c" for the fonts, so there is no need to specify that file in our code.

Note: when updating the GFX library, the glcfont.c file will be overwritten with the default 8 x 8 font!

Documentation for the three Adafruit libraries can be found at:

The methods in the NeoMatrix library we'll be using are mostly self explanatory, the exception being the constructor, which looks like this:
Adafruit_NeoMatrix(width, height, dataPin, matrixType, neoPixelType)

width and height
size of display, so in our case those numbers will be 5 and 5
dataPin
the pin that the NeoPixel display uses for data, which is 27 for the ATOM Matrix
matrixType
what is the physical position of the pixel at (0, 0), and are the subsequent pixels arranged in rows or columns
neoPixelType
the color order (GRB) and data rate

As we'll see, the library contains constants that make specifying the last two arguments easy.

The whole trick is to imagine the display to be a "window" showing part of the the text. The scrolling results by moving the window, not moving the message. Here is the code, with explanation below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Text-Display-01.ino
 * 
 * By: Mike Klepper
 * Date: 26 April 2020
 * 
 * Displays text on the M5 ATOM Matrix using the Adafruit GFX library
 */

#include <Adafruit_GFX.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_NeoPixel.h>

#define DISPLAY_PIN 27

String msg = F("MAKE AMERICA GREAT AGAIN");
int msgLength = msg.length();
int charWidth = 5;
int numTrailingSpaces = 3;
int maxLeftPosition = (msgLength + numTrailingSpaces) * (charWidth + 1);

int scrollDelay = 100;

// Horizontal, left to right with bottom closest to USB-C port
int directionAndOrientation = NEO_MATRIX_TOP + NEO_MATRIX_LEFT + NEO_MATRIX_ROWS;

// Vertical, top to bottom with top closest to reset button
// int directionAndOrientation = NEO_MATRIX_TOP + NEO_MATRIX_RIGHT + NEO_MATRIX_COLUMNS;

int pixelType = NEO_GRB + NEO_KHZ800;

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(5, 5, DISPLAY_PIN,
  directionAndOrientation + NEO_MATRIX_PROGRESSIVE,
  pixelType);

int xPos  = matrix.width();

void setup() 
{
  matrix.begin();
  matrix.setTextWrap(false);
  matrix.setBrightness(40);
  matrix.setTextColor(matrix.Color(80, 0, 80));
}

void loop() 
{
  matrix.fillScreen(0);
  matrix.setCursor(xPos, 0);
  matrix.print(msg);

  if(--xPos < -maxLeftPosition)
  {
    xPos = matrix.width();
  }
  
  matrix.show();
  delay(scrollDelay);
}


Line Comment
14 The dataPin, which will be third argument of the constructor (line 30)
16 The message that will be displayed
17 Number of characters in the message
18 How wide each character in our fixed-width font is
19 These trailing spaces result in a delay between the end of the message and the start of the next cycle
20 The total width of the message (including trailing spaces) in pixels
25 (0, 0) is located at the top-left, and the subsequent pixels are arranged in rows
28 Uncomment this line (and comment line 25) for a different scroll direction
30 The NeoPixels use GRB color order, with data rate of 800 KHz
32 The constructor!
33 NEO_MATRIX_PROGRESSIVE means that the pixels in the rows all have same order (as opposed to zig-zag)
36 How much the "window" is offset
38 Start of the setup function; all this is self explanatory, except...
43 The matrix.Color method takes values in RGB order, so in this case the text will be purple
49 Set the position of the "window"
50 Draw the message
52 Move the window to the left by one; if the window has moved pass the end of the message...
54 Reset the window to the right edge of the display


Animation Effects

The FastLED library contains numerous examples that were, I believe, originally intended for NeoPixel strips instead of matrices. They still look good, however!

To use the examples, the following three changes must be made to the code:

  • Set the data pin to 27
  • The number of LEDs must be set to 25
  • The brightness should be set to a lower value, like 60, for example.
The ATOM Matrix product description page recommends a max brightness of 20, but higher numbers seem harmless.

Here is one of the examples, called "Fire2012WithPalette," with the above three modifications made. Comments from the original are retained.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 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
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <FastLED.h>

#define LED_PIN     27
#define COLOR_ORDER GRB
#define CHIPSET     WS2811
#define NUM_LEDS    25

#define BRIGHTNESS  60
#define FRAMES_PER_SECOND 60

bool gReverseDirection = false;

CRGB leds[NUM_LEDS];

// Fire2012 with programmable Color Palette
//
// This code is the same fire simulation as the original "Fire2012",
// but each heat cell's temperature is translated to color through a FastLED
// programmable color palette, instead of through the "HeatColor(...)" function.
//
// Four different static color palettes are provided here, plus one dynamic one.
// 
// The three static ones are: 
//   1. the FastLED built-in HeatColors_p -- this is the default, and it looks
//      pretty much exactly like the original Fire2012.
//
//  To use any of the other palettes below, just "uncomment" the corresponding code.
//
//   2. a gradient from black to red to yellow to white, which is
//      visually similar to the HeatColors_p, and helps to illustrate
//      what the 'heat colors' palette is actually doing,
//   3. a similar gradient, but in blue colors rather than red ones,
//      i.e. from black to blue to aqua to white, which results in
//      an "icy blue" fire effect,
//   4. a simplified three-step gradient, from black to red to white, just to show
//      that these gradients need not have four components; two or
//      three are possible, too, even if they don't look quite as nice for fire.
//
// The dynamic palette shows how you can change the basic 'hue' of the
// color palette every time through the loop, producing "rainbow fire".

CRGBPalette16 gPal;

void setup() {
  delay(3000); // sanity delay
  FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
  FastLED.setBrightness( BRIGHTNESS );

  // This first palette is the basic 'black body radiation' colors,
  // which run from black to red to bright yellow to white.
  gPal = HeatColors_p;
  
  // These are other ways to set up the color palette for the 'fire'.
  // First, a gradient from black to red to yellow to white -- similar to HeatColors_p
  //   gPal = CRGBPalette16( CRGB::Black, CRGB::Red, CRGB::Yellow, CRGB::White);
  
  // Second, this palette is like the heat colors, but blue/aqua instead of red/yellow
  //   gPal = CRGBPalette16( CRGB::Black, CRGB::Blue, CRGB::Aqua,  CRGB::White);
  
  // Third, here's a simpler, three-step gradient, from black to red to white
  //   gPal = CRGBPalette16( CRGB::Black, CRGB::Red, CRGB::White);

}

void loop()
{
  // Add entropy to random number generator; we use a lot of it.
  random16_add_entropy( rand());

  // Fourth, the most sophisticated: this one sets up a new palette every
  // time through the loop, based on a hue that changes every time.
  // The palette is a gradient from black, to a dark color based on the hue,
  // to a light color based on the hue, to white.
  //
  //   static uint8_t hue = 0;
  //   hue++;
  //   CRGB darkcolor  = CHSV(hue,255,192); // pure hue, three-quarters brightness
  //   CRGB lightcolor = CHSV(hue,128,255); // half 'whitened', full brightness
  //   gPal = CRGBPalette16( CRGB::Black, darkcolor, lightcolor, CRGB::White);


  Fire2012WithPalette(); // run simulation frame, using palette colors
  
  FastLED.show(); // display this frame
  FastLED.delay(1000 / FRAMES_PER_SECOND);
}


// Fire2012 by Mark Kriegsman, July 2012
// as part of "Five Elements" shown here: http://youtu.be/knWiGsmgycY
//// 
// This basic one-dimensional 'fire' simulation works roughly as follows:
// There's a underlying array of 'heat' cells, that model the temperature
// at each point along the line.  Every cycle through the simulation, 
// four steps are performed:
//  1) All cells cool down a little bit, losing heat to the air
//  2) The heat from each cell drifts 'up' and diffuses a little
//  3) Sometimes randomly new 'sparks' of heat are added at the bottom
//  4) The heat from each cell is rendered as a color into the leds array
//     The heat-to-color mapping uses a black-body radiation approximation.
//
// Temperature is in arbitrary units from 0 (cold black) to 255 (white hot).
//
// This simulation scales it self a bit depending on NUM_LEDS; it should look
// "OK" on anywhere from 20 to 100 LEDs without too much tweaking. 
//
// I recommend running this simulation at anywhere from 30-100 frames per second,
// meaning an interframe delay of about 10-35 milliseconds.
//
// Looks best on a high-density LED setup (60+ pixels/meter).
//
//
// There are two main parameters you can play with to control the look and
// feel of your fire: COOLING (used in step 1 above), and SPARKING (used
// in step 3 above).
//
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames.  More cooling = shorter flames.
// Default 55, suggested range 20-100 
#define COOLING  55

// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire.  Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
#define SPARKING 120


void Fire2012WithPalette()
{
// Array of temperature readings at each simulation cell
  static byte heat[NUM_LEDS];

  // Step 1.  Cool down every cell a little
    for( int i = 0; i < NUM_LEDS; i++) {
      heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
    }
  
    // Step 2.  Heat from each cell drifts 'up' and diffuses a little
    for( int k= NUM_LEDS - 1; k >= 2; k--) {
      heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
    }
    
    // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
    if( random8() < SPARKING ) {
      int y = random8(7);
      heat[y] = qadd8( heat[y], random8(160,255) );
    }

    // Step 4.  Map from heat cells to LED colors
    for( int j = 0; j < NUM_LEDS; j++) {
      // Scale the heat value from 0-255 down to 0-240
      // for best results with color palettes.
      byte colorindex = scale8( heat[j], 240);
      CRGB color = ColorFromPalette( gPal, colorindex);
      int pixelnumber;
      if( gReverseDirection ) {
        pixelnumber = (NUM_LEDS-1) - j;
      } else {
        pixelnumber = j;
      }
      leds[pixelnumber] = color;
    }
}



Application: Controlling a NeoPixel Strip

The same FireLED examples can be used to control an external NeoPixel strip.

In order to connect a strip to the Atom's Grove port, Dupont jumper wires cannot be used - the pins are too close! Instead, use the type with the thinner ends. Connect ground to ground, power to power, and (for example) G32 to the data line on the NeoPixel strip.

The spacing between the pins on the back of the ATOM Matrix is sufficient to use ordinary Dupont jumpers.

Ordinary NeoPixel strips can operate at full brightness (255), but the other two changes (dataPin and number of pixels) must still be made. Here is a FastLED example called "Pride2015," with original comments in place.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "FastLED.h"

// Pride2015
// Animated, ever-changing rainbows.
// by Mark Kriegsman

#if FASTLED_VERSION < 3001000
#error "Requires FastLED 3.1 or later; check github for latest code."
#endif

#define DATA_PIN    32
//#define CLK_PIN   4
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS    30
#define BRIGHTNESS  255

CRGB leds[NUM_LEDS];


void setup() {
  delay(3000); // 3 second delay for recovery
  
  // tell FastLED about the LED strip configuration
  FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS)
    .setCorrection(TypicalLEDStrip)
    .setDither(BRIGHTNESS < 255);

  // set master brightness control
  FastLED.setBrightness(BRIGHTNESS);
}


void loop()
{
  pride();
  FastLED.show();  
}


// This function draws rainbows with an ever-changing,
// widely-varying set of parameters.
void pride() 
{
  static uint16_t sPseudotime = 0;
  static uint16_t sLastMillis = 0;
  static uint16_t sHue16 = 0;
 
  uint8_t sat8 = beatsin88( 87, 220, 250);
  uint8_t brightdepth = beatsin88( 341, 96, 224);
  uint16_t brightnessthetainc16 = beatsin88( 203, (25 * 256), (40 * 256));
  uint8_t msmultiplier = beatsin88(147, 23, 60);

  uint16_t hue16 = sHue16;//gHue * 256;
  uint16_t hueinc16 = beatsin88(113, 1, 3000);
  
  uint16_t ms = millis();
  uint16_t deltams = ms - sLastMillis ;
  sLastMillis  = ms;
  sPseudotime += deltams * msmultiplier;
  sHue16 += deltams * beatsin88( 400, 5,9);
  uint16_t brightnesstheta16 = sPseudotime;
  
  for( uint16_t i = 0 ; i < NUM_LEDS; i++) {
    hue16 += hueinc16;
    uint8_t hue8 = hue16 / 256;

    brightnesstheta16  += brightnessthetainc16;
    uint16_t b16 = sin16( brightnesstheta16  ) + 32768;

    uint16_t bri16 = (uint32_t)((uint32_t)b16 * (uint32_t)b16) / 65536;
    uint8_t bri8 = (uint32_t)(((uint32_t)bri16) * brightdepth) / 65536;
    bri8 += (255 - brightdepth);
    
    CRGB newcolor = CHSV( hue8, sat8, bri8);
    
    uint16_t pixelnumber = i;
    pixelnumber = (NUM_LEDS-1) - pixelnumber;
    
    nblend( leds[pixelnumber], newcolor, 64);
  }
}


Click here to go to the table of contents for this series.