-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmy06_LED_onboard_setRGB.ino
101 lines (77 loc) · 2.51 KB
/
my06_LED_onboard_setRGB.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
/*
* LED_onboard_setRGB
* creates an AnalogWrite for each on-board LED using the Portenta H7
* This is needed since the onboard LED's are reverse set for LOW and HIGH to protect the board
* The long function name helps with auto-fill if ever used with the new Arduino Pro IDE.
*
* July 27th, 2020
* by Jeremy Ellis
* Twitter @rocksetta
* Website https://www.rocksetta.com
*
* setRGB idea by Daniel Danaie
*
* example usage
* LED_onboard_setRGB(255, 0, 0); // set LED to red
*
* or
*
* LED_onboard_analogWrite(LEDB, 0, previousMillisB, ledStateB); Turns the onBoard Blue LED fully off
* LED_onboard_analogWrite(LEDB, 255, previousMillisB, ledStateB); Turns the onBoard Blue LED fully on
*
* Note because of the sensitive timer used you can not use this code with delay(1000);
*
*/
unsigned long myTimer = millis();
// These variable must be global
unsigned long previousMillisR;
int ledStateR = HIGH;
int myAmountR;
unsigned long previousMillisG;
int ledStateG = HIGH;
int myAmountG;
unsigned long previousMillisB;
int ledStateB = HIGH;
int myAmountB;
void setup() {
Serial.begin(9600);
pinMode(LEDB, OUTPUT);
pinMode(LEDG, OUTPUT); // same as LED_BUILTIN
pinMode(LEDR, OUTPUT);
randomSeed(analogRead(A0));
}
void loop() {
unsigned long myNow = millis();
// LED_onboard_setRGB(25, 25, 255); // example blue
if (myNow - myTimer >= 1000){ // color change delay 1000 = 1 second
myTimer = myNow;
myAmountR = rand()% 256;
myAmountG = rand()% 256;
myAmountB = rand()% 256;
Serial.println("Red:"+String(myAmountR) + ", Green:"+ String(myAmountG) + ", Blue:"+ String(myAmountB));
}
LED_onboard_setRGB( myAmountR, myAmountG, myAmountB);
}
void LED_onboard_setRGB(int colorR, int colorG, int colorB){
LED_onboard_analogWrite(LEDR, colorR, previousMillisR, ledStateR);
LED_onboard_analogWrite(LEDG, colorG, previousMillisG, ledStateG);
LED_onboard_analogWrite(LEDB, colorB, previousMillisB, ledStateB);
}
void LED_onboard_analogWrite(int myPin, int myPWM, unsigned long &myMillis, int &myState){
unsigned long currentMillis = micros();
if (myPWM > 255){myPWM = 255;}
if (myPWM < 0){myPWM = 0;}
if (myState == LOW){
if(currentMillis - myMillis >= myPWM){
myState = HIGH;
digitalWrite(myPin, myState);
myMillis = currentMillis;
}
} else {
if(currentMillis - myMillis >= 255-myPWM){
myState = LOW;
digitalWrite(myPin, myState);
myMillis = currentMillis;
}
}
}