Hello! We are attempting to use a Nano to drive an RGB LED strip, using analogWrite on pins 9, 10, 11, which drive a MOSFET allowing 12V power to the LEDs. The Nano receives an RGB string through serial, such as "255,0,0", which would indicate that the red pin should be fully on, and green and blue should be turned off.
The code below works fine as long as I use 255 and 0 only (all the way on or all the way off). However, if I have any other input (e.g. (120,120,0)), the Serial stops accepting new input.
Based on my research, it seems to have something to do with PWM and the interrupts required for Serial to work, but I'm a little at a loss as to how to proceed, given that driving the LEDs using PWM is a requirement.
Code is included below. Thanks for your help!
int redPin = 9, greenPin = 10, bluePin = 11;
int allPins[3] = {redPin, greenPin, bluePin};
void setup() {
for (byte i = 0; i < 3; i++) {
pinMode(allPins[i], OUTPUT);
}
Serial.begin(115200);
Serial.setTimeout(20);
for (byte i = 0; i < 3; i++) {
analogWrite(allPins[i], 0);
}
}
void loop() {
checkRgb();
}
void checkRgb() {
if (Serial.available() == 0) return; //wait for data available
String teststr = Serial.readString(); //read until timeout
teststr.trim(); // remove any \r \n whitespace at the end of the String
handleRgbString(teststr);
}
bool handleRgbString(String teststr) {
int strLen = teststr.length() + 1;
char char_array[strLen];
teststr.toCharArray(char_array, strLen);
char delimiters[] = ",";
char* valPosition;
String redString = strtok(char_array, delimiters);
if (!isValidNumber(redString)) return false;
String greenString = strtok(NULL, delimiters);
if (!isValidNumber(greenString)) return false;
String blueString = strtok(NULL, delimiters);
if (!isValidNumber(blueString)) return false;
analogWrite(redPin, redString.toInt());
analogWrite(greenPin, greenString.toInt());
analogWrite(bluePin, blueString.toInt());
return true;
}
boolean isValidNumber(String str) { //TEST THIS LOGIC
for (byte i = 0; i < str.length(); i++)
{
if (!isDigit(str.charAt(i))) return false;
}
return true;
}