Seperate files into header and c++ files

arduino nano 33 ble sense imu header cpp files folders

Pre-requisites

Learn how to split long files into several header and cpp files for better code organization. The final directory structure will look like this:

$ tree
.
├── Imu.cpp
├── Imu.h
├── Makefile
├── Sensor.cpp
├── Sensor.h
└── nano33-ble-sense-imu-sensors.ino

0 directories, 6 files

Install the dependancies:

arduino-cli lib install Arduino_LSM9DS1
arduino-cli lib install Arduino_HTS221

Code

Download code
#include "Imu.h"
#include "Sensor.h"

long lastSendTime = 0;
long period = 1000;

void setup() {
  Serial.begin(9600);
  while (!Serial) {}

  if (!initSensor()) {
    Serial.println("Failed to initialize humidity temperature sensor!");
  }

  if (!initIMU()) {
    Serial.println("Failed to initialize IMU!");
  }

  Serial.println("Let's start!");
}

void loop() {
  float x, y, z;

  if (getAcceleration(x, y, z)) {
    Serial.print("X: ");
    Serial.print(x);
    Serial.print('\t');

    Serial.print("Y: ");
    Serial.print(y);
    Serial.print('\t');

    Serial.print("Z: ");
    Serial.println(z);
  }

  if (millis() - lastSendTime >= period) {
    float temperature;
    float humidity;
    getSensorValues(temperature, humidity);

    Serial.print("Temperature = ");
    Serial.print(temperature);
    Serial.println("°C");

    Serial.print("Humidity = ");
    Serial.print(humidity);
    Serial.println("%");

    lastSendTime = millis();
  }
}

Makefile

BOARD?=arduino:mbed:nano33ble
PORT?=/dev/cu.usbmodem14*
BUILD=build

.PHONY: default lint all flash clean

default: lint all flash clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright,-runtime/int *.ino

all:
	arduino-cli compile --fqbn $(BOARD) --output-dir $(BUILD) ./

flash:
	arduino-cli upload --fqbn $(BOARD) --port $(PORT) --input-dir $(BUILD)

clean:
	rm -r build

Serial console

Serial output from the firmware.

Seperate files into header and c++ files serial console

References