Seperate files into header and c++ files

Updated on 3 September 2021
dev board Arduino Nano 33 BLE Sense
firmware Arduino
features imu header cpp files folders
This tutorial is more than 1 year old. If the steps below do not work, then please check the latest versions and the documentations of the individual tools used.

Before starting

Dependancies

Ensure the following dependancies are downloaded and available:

Buy the components

Code

Download code nano33-ble-sense-imu-sensors.ino
#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

Description

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

References