Arduino struct with functions in seperate folder

Updated on 3 September 2021
dev board LilyGO T-Beam
firmware Arduino
features struct function files header cpp pointer
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

Pre-requisites

Try these simpler or similar examples:

Buy the components

Code

Download code struct-functions.ino
#include "src/latlong/latlong.h"

LatLong latlong = {1.2480631, 103.8285657};

void setup() {
  Serial.begin(9600);
  while (!Serial) { }
  Serial.println("Locations of places around the world!");
}

void loop() {
  goToSentosa(&latlong);
  Serial.print("Sentosa: (");
  Serial.print(latlong.latitude, 6);
  Serial.print(", ");
  Serial.print(latlong.longitude, 6);
  Serial.println(")");

  goToEiffelTower(&latlong);
  Serial.print("Eiffel Tower: (");
  Serial.print(latlong.latitude, 6);
  Serial.print(", ");
  Serial.print(latlong.longitude, 6);
  Serial.println(")");

  delay(2000);
}

Makefile

BOARD?=esp32:esp32:t-beam
PORT?=/dev/cu.SLAB_USBtoUART

.PHONY: default lint all flash clean

default: all flash clean

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

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

flash:
	arduino-cli upload -p $(PORT) --fqbn $(BOARD)

clean:
	rm -r build

Serial console

Serial output from the firmware.

Arduino struct with functions in seperate folder serial console

Description

Use struct data type to declare, create and use it in a function. The struct functions are abstracted in a seperate folder to show how it can be used and referred in the main.ino.

The struct LatLong can be declared:

struct LatLong {
  double latitude;
  double longitude;
};

The struct can be defined:

LatLong latlong = {1.2480631, 103.8285657};

The struct can be used in a function declaration:

void goToSentosa(struct LatLong *);

The struct can be used in a function definition:

void goToSentosa(struct LatLong *ll) {
  ...
}