Pico-Arduino
PicoThread.h
1 #pragma once
2 
3 #include "pico/stdlib.h"
4 #include "pico/multicore.h"
5 
6 
7 typedef void (*ThreadCB)(void* arg);
8 
15 class Thread {
16  public:
17  Thread(){
18  started(false);
19  }
20 
21  ~Thread(){
22  stop();
23  }
24 
26  bool start(ThreadCB callback, void* ptr=nullptr){
27  bool result = false;
28  // set arguments to callback
29  staticPtr(ptr);
30  staticCallback(callback);
31 
32  if (!started()){
33  multicore_launch_core1(callback_handler);
34  started(true);
35  result = true;
36  Logger.info("Thread started on core1");
37  } else {
38  Logger.info("Thread not started - because one is already active");
39  }
40  return result;
41  }
42 
44  void stop() {
45  multicore_reset_core1();
46  started(false);
47  }
48 
49  // // Send core 1 to sleep.
50  // void sleep() {
51  // multicore_sleep_core1();
52  // }
53 
55  bool isRunning() {
56  return started();
57  }
58 
59  static void callback_handler(){
60  ThreadCB cb = staticCallback();
61  void* ptr = staticPtr();
62  // calling callback
63  cb(ptr);
64  }
65 
66  protected:
67  // static setter / getter for ptr
68  static void *staticPtr(void* ptr = nullptr){
69  static void *stat_ptr = {ptr};
70  return stat_ptr;
71  }
72 
73  // static setter / getter for callback
74  static ThreadCB staticCallback(ThreadCB cb = nullptr) {
75  static ThreadCB stat_cb = {cb};
76  return stat_cb;
77  };
78 
79 
80  // get or update static started flag
81  bool started(int flag=-1){
82  static bool started_flag;
83  if (flag!=-1)
84  started_flag = flag;
85  return started_flag;
86  }
87 
88 };
89 
Adds support for running code on the second processor core (core1)
Definition: PicoThread.h:15
bool start(ThreadCB callback, void *ptr=nullptr)
Run code on core 1 - we can pass a reference to an object which will be given to the callback as argu...
Definition: PicoThread.h:26
bool isRunning()
check if the core1 has been started and is not stoped
Definition: PicoThread.h:55
void stop()
resets the core 1
Definition: PicoThread.h:44