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