Pine

🌲 An indoor infrared receiver and transmitter with a temperature sensor 🎐

power AA
wireless Infrared
mcu SAMD21G18
bom items 49
bom cost USD $9.71
vendors 2
completed September 2020

Measure battery voltage

battery voltage easy

VBAT is connected to the battery or voltage source you wish to measure the voltage of.


Serial console

Serial output from the firmware.

Schematic

Wire up the hardware accordingly

 setup

Code

Download code
#define VBATPIN 6

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  SerialUSB.begin(9600);
  while (!SerialUSB) {}
  delay(1000);

  SerialUSB.println("Start battery voltage measurement!");
}

void loop() {
  // SerialUSB.println("HIGH");
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);

  // SerialUSB.println("LOW");
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);

  float measuredvbat = analogRead(VBATPIN);

  for (int i = 0; i < 10; i++) {
    measuredvbat += analogRead(VBATPIN);
    delay(10);
  }

  measuredvbat /= 10;
  measuredvbat *= 2;
  measuredvbat *= 4.5;  // Or the reference voltage E.g. 2.8V, 3.3V
  measuredvbat /= 1024;

  SerialUSB.print("VBat: ");
  SerialUSB.print(measuredvbat);
  SerialUSB.println("V");
}

Makefile

BOARD?=arduino:samd:arduino_zero_native
PORT := $(shell ls /dev/cu.usbmodem*)

.PHONY: default lint all flash clean

default: lint all flash clean

lint:
	cpplint --extensions=ino --filter=-legal/copyright,-whitespace/line_length,-readability/casting,-readability/todo *.ino

all:
	# This custom PCB does not have a crytal on pins PA00 and PA01
	# Hence, use -DCRYSTALLESS to replace the extra_flags in boards.txt
	arduino-cli compile --fqbn $(BOARD) --build-properties build.extra_flags="-DCRYSTALLESS -D__SAMD21G18A__ {build.usb_flags}" ./

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

clean:
	rm -r build

References