Browse Source

arduino: report analog reading of pin A0 once per second as unsigned 16bit int via serial port

Fabian Peter Hammerle 3 years ago
commit
1fdd81f5b4
5 changed files with 65 additions and 0 deletions
  1. 2 0
      .gitignore
  2. 2 0
      Makefile
  3. 27 0
      arduino-sketch.ino
  4. 31 0
      display.py
  5. 3 0
      pre-build-hook.sh

+ 2 - 0
.gitignore

@@ -0,0 +1,2 @@
+/build-*/
+/version.h

+ 2 - 0
Makefile

@@ -0,0 +1,2 @@
+BOARD_TAG = uno
+include /usr/share/arduino/Arduino.mk

+ 27 - 0
arduino-sketch.ino

@@ -0,0 +1,27 @@
+#include "version.h"
+
+// https://www.arduino.cc/reference/en/language/functions/time/micros/
+const unsigned long SAMPLE_INTERVAL_MICROSECONDS = 1000000L;
+
+void setup() {
+    // $ stty -F /dev/ttyUSB0 | grep speed
+    Serial.begin(115200);
+    // Serial.println("https://git.hammerle.me/fphammerle/TODO");
+    // Serial.println(PROJECT_VERSION);
+}
+
+unsigned long last_sample_micros = 0;
+
+void loop() {
+    while (micros() - last_sample_micros < SAMPLE_INTERVAL_MICROSECONDS) {
+        delay(1);
+    }
+    // > On ATmega based boards [...], it takes about 100 microseconds (0.0001
+    // s) to read an analog input, [...]
+    // https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
+    unsigned short reading = analogRead(A0);
+    // $ tail --follow /dev/ttyUSB0 | od --format=u2 --endian=big --width=2
+    Serial.write(reading >> 8);
+    Serial.write(reading & 0xff);
+    last_sample_micros = micros();
+}

+ 31 - 0
display.py

@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+
+import argparse
+import logging
+import struct
+
+import serial
+
+_LOGGER = logging.getLogger(__name__)
+
+
+def _main():
+    logging.basicConfig(
+        level=logging.DEBUG,
+        format="%(asctime)s:%(levelname)s:%(name)s:%(funcName)s:%(message)s",
+        datefmt="%Y-%m-%dT%H:%M:%S%z",
+    )
+    argparser = argparse.ArgumentParser()
+    argparser.add_argument("--serial-port", type=str, nargs="?", default="/dev/ttyUSB0")
+    args = argparser.parse_args()
+    _LOGGER.debug("args=%r", args)
+    with serial.Serial(args.serial_port, 115200, timeout=2) as serial_port:
+        _LOGGER.debug("serial_port.name=%s", serial_port.name)
+        while True:
+            reading, = struct.unpack(">H", serial_port.read(2))
+            voltage = reading * 5 / 1024
+            print(f"{voltage:.02f}V")
+
+
+if __name__ == "__main__":
+    _main()

+ 3 - 0
pre-build-hook.sh

@@ -0,0 +1,3 @@
+#!/bin/sh
+set -ex
+echo "#define PROJECT_VERSION \"$(shell git describe --dirty --long --always)\"" > version.h