Skip to content

Instantly share code, notes, and snippets.

@greggjaskiewicz
Created December 7, 2021 20:45
Show Gist options
  • Save greggjaskiewicz/669ec867c824a30f5734073800e74fb1 to your computer and use it in GitHub Desktop.
Save greggjaskiewicz/669ec867c824a30f5734073800e74fb1 to your computer and use it in GitHub Desktop.
ESP32 FreeRTOS blinker
const byte ledPins[] = { 15, 2, 0, 4, 5, 18, 19, 21, 22, 23}; // define led pins
const byte chns[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // define the pwm channels
const int dutys[] = {
1023, 512, 256, 128, 64, 32, 16, 8, 4, 2, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}; //define the pwm dutys
int ledCounts; //
const int delayTimes = 100; //flowing speed ,the smaller, the faster
struct LEDTaskDescription {
int channel;
int dutyIndex;
int direction;
};
void ledTask(void *ledTaskDescription) {
LEDTaskDescription *description = (LEDTaskDescription *)ledTaskDescription;
const int maxSize = (sizeof(dutys)/sizeof(typeof(dutys[0])));
for(;;) {
int duty = dutys[description->dutyIndex];
ledcWrite(description->channel, duty);
description->dutyIndex += description->direction;
if (description->dutyIndex >= maxSize) {
description->dutyIndex = maxSize-1;
description->direction = -1;
} else if (description->dutyIndex <= 0) {
description->dutyIndex = 0;
description->direction = 1;
}
vTaskDelay(delayTimes/portTICK_PERIOD_MS);
}
}
void setup() {
Serial.begin(115200);
ledCounts = sizeof(ledPins); //get the led counts
for (int i = 0; i < ledCounts; i++) { //setup the pwm channels
ledcSetup(chns[i], 1000, 10);
ledcAttachPin(ledPins[i], chns[i]);
BaseType_t xReturned;
LEDTaskDescription *desc = new LEDTaskDescription;
desc->channel = chns[i];
desc->dutyIndex = i;
desc->direction = 1;
char name[1024] = "";
sprintf(name, "blink %d", i);
xReturned = xTaskCreate(
ledTask,
name,
768,
( void * )desc,
2,
NULL );
if( xReturned != pdPASS )
{
Serial.print("task create fail, error: ");
Serial.println(xReturned);
while(1){};
}
Serial.print("task created: ");
Serial.println(name);
}
Serial.print("setup() is running on core ");
Serial.println(xPortGetCoreID());
}
void loop() {
yield();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment