Skip to content

Instantly share code, notes, and snippets.

@hidsh
Last active July 22, 2024 03:49
Show Gist options
  • Save hidsh/edf28f6c5859755223e07f0f6715d812 to your computer and use it in GitHub Desktop.
Save hidsh/edf28f6c5859755223e07f0f6715d812 to your computer and use it in GitHub Desktop.
arduino example: calling Serial.println() from a C source file

C言語からArduinoのSerialオブジェクトを使うには

  1. C++のソースにSerialオブジェクトを使ったラッパー関数を作る (my_log() @sub.cpp)
  2. Cのソースからそのラッパー関数をコールするラッパー関数を作る (my_log_c() @sub.c)

という、二段構えのラップラップが必要になる。

C++から直接Serialオブジェクトを使うときに比べてめんどいけど、このやり方を覚えるとArduinoだけでなく他の言語でも使えるので応用が効くはず。

元ネタ:https://stackoverflow.com/questions/66632376/how-to-call-serial-print-from-c-file-in-arduino-ide

#include "sub.h"
void setup(){
Serial.begin(9600);
delay(0.5 * 1000);
my_log_c("hoge");
}
void loop(){
my_log_c("fuga");
delay(1 * 1000);
}
// sub.c
#include "sub.h"
void my_log_c(const char *msg) {
my_log(msg);
}
// sub.cpp
#include <Arduino.h>
#include "sub.h"
void my_log(const char *msg) {
Serial.println(msg);
}
// sub.h
#ifdef __cplusplus
extern "C" {
#endif
void my_log(const char *msg); // defined in sub.cpp
void my_log_c(const char *msg); // defined in sub.c
#ifdef __cplusplus
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment