1 /* 2 // 多线程基于FreeRTOS,可以多个任务并行处理; 3 // ESP32具有两个32位Tensilica Xtensa LX6微处理器; 4 // 实际上我们用Arduino进行编程时只使用到了第一个核(大核),第0核并没有使用 5 // 多线程可以指定在那个核运行; 6 */ 7 8 #include <Arduino.h> 9 #define USE_MULTCORE 1 10 11 void xTaskOne(void *xTask1) 12 { 13 while (1) 14 { 15 Serial.printf("Task1 \r\n"); 16 delay(500); 17 } 18 } 19 20 void xTaskTwo(void *xTask2) 21 { 22 while (1) 23 { 24 Serial.printf("Task2 \r\n"); 25 delay(1000); 26 } 27 } 28 29 void setup() 30 { 31 Serial.begin(115200); 32 delay(10); 33 34 } 35 36 void loop() 37 { 38 39 #if !USE_MULTCORE 40 41 xTaskCreate( 42 xTaskOne, /* Task function. */ 43 "TaskOne", /* String with name of task. */ 44 4096, /* Stack size in bytes. */ 45 NULL, /* Parameter passed as input of the task */ 46 1, /* Priority of the task.(configMAX_PRIORITIES - 1 being the highest, and 0 being the lowest.) */ 47 NULL); /* Task handle. */ 48 49 xTaskCreate( 50 xTaskTwo, /* Task function. */ 51 "TaskTwo", /* String with name of task. */ 52 4096, /* Stack size in bytes. */ 53 NULL, /* Parameter passed as input of the task */ 54 2, /* Priority of the task.(configMAX_PRIORITIES - 1 being the highest, and 0 being the lowest.) */ 55 NULL); /* Task handle. */ 56 57 #else 58 59 //最后一个参数至关重要,决定这个任务创建在哪个核上.PRO_CPU 为 0, APP_CPU 为 1,或者 tskNO_AFFINITY 允许任务在两者上运行. 60 xTaskCreatePinnedToCore(xTaskOne, "TaskOne", 4096, NULL, 1, NULL, 0); 61 xTaskCreatePinnedToCore(xTaskTwo, "TaskTwo", 4096, NULL, 2, NULL, 1); 62 63 #endif 64 65 while (1) 66 { 67 Serial.printf("XTask is running\r\n"); 68 delay(1000); 69 } 70 }