Search code examples
carduinoavrarduino-ide

How to call Serial.print() from .c file in Arduino IDE?


I have two files in Arduino IDE. One is the .ino file and one is a .c file.

main.ino:

#include "somefile.c"

void setup(){
    Serial.begin(9600);
    // Do something
}

void loop(){
    // Do something
}

And in somefile.c I want to call Serial.print(). How can I do that? Thanks!


Solution

  • create a my_logging.h file with

    void my_log(const char *msg);
    

    create a my_logging.cpp file with

    #include <Arduino.h>
    extern "C" {
      #include "my_logging.h"
    }
    
    void my_log(const char *msg) {
      Serial.println(msg);
    }
    

    then in in your c file include the my_logging.h file and you can use the my_log function