-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslave.ino
139 lines (114 loc) · 2.77 KB
/
slave.ino
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
/**
* Run this code on the ATtiny85 to control LEDs
* @author Danny Buonocore, BitBuddies LLC
*/
#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>
#include "hsv.h"
#define RX 3
#define TX 4
#define LED 1
#define PATTERN_SOLID 1
#define PATTERN_FADE 2
#define PATTERN_RAINBOW 3
#define NUM_PATTERNS 3
#define MAXHUE 256 * 6
#define NUM_LEDS 24
SoftwareSerial link(RX, TX);
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_LEDS, LED, NEO_GRB + NEO_KHZ800);
int pattern = PATTERN_SOLID;
byte brightness = 5;
byte red = 0;
byte green = 0;
byte blue = 0;
unsigned long previousMillis = 0;
int t = 0;
int hue = 0;
bool receivedData = false;
void setup() {
pinMode(LED, OUTPUT);
link.begin(9600);
pixels.begin();
}
void loop() {
if (link.available() >= 2) {
if (link.read() == 0xFF) {
byte len = link.read();
while (link.available() < len + 1);
byte cmd[len];
for (int i = 0; i < len; i++) {
cmd[i] = link.read();
if (cmd[i] == 0xFE) {
return;
}
}
// Process command
if (link.read() == 0xFE) {
receivedData = true;
// Acknowledge the command has been received
link.write(0x06);
// Brightness
if (cmd[0] == 'b') {
int b = cmd[1];
if (b > 0 && b <= 16) {
brightness = b;
}
}
// Color
if (cmd[0] == 'c') {
red = cmd[1] == 1 ? 0 : cmd[1];
green = cmd[2] == 1 ? 0 : cmd[2];
blue = cmd[3] == 1 ? 0 : cmd[3];
}
// Pattern
if (cmd[0] == 'p') {
byte p = cmd[1];
if (p > 0 && p <= NUM_PATTERNS) {
pattern = p;
}
}
}
}
}
if (receivedData) {
unsigned long maxMillis = 40;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= maxMillis) {
previousMillis = currentMillis;
updatePixels();
}
}
}
void updatePixels() {
float multiplier = brightness / 16.0;
for (int i = 0; i < NUM_LEDS; i++) {
if (pattern == PATTERN_RAINBOW) {
pixels.setPixelColor(
(i + t) % NUM_LEDS,
getPixelColorHsv(i, i * (MAXHUE / NUM_LEDS), 100, int(255 * multiplier))
);
} else if (pattern == PATTERN_FADE) {
pixels.setPixelColor(
(i + t) % NUM_LEDS,
getPixelColorHsv(i, hue, 255, int(255 * multiplier))
);
} else {
int r = red * multiplier;
int g = green * multiplier;
int b = blue * multiplier;
pixels.setPixelColor(i, r, g, b);
}
}
pixels.show();
if (pattern != PATTERN_SOLID) {
hue += 2;
hue %= MAXHUE;
}
t++;
t %= NUM_LEDS;
}
int clamp(int i) {
if (i < 0) return NUM_LEDS - i;
if (i > NUM_LEDS - 1) return i - NUM_LEDS;
return i;
}