Example usage

Example code for reading sensor data and printing the values. The raw values get translated to calibrated values using the Touchlab library. You have to provide a calibration file for this to work. If you omit the calibration file only raw values will be printed.

#!/usr/bin/env python3

# Copyright (c) 2025 Touchlab Limited. All Rights Reserved
# Unauthorized copying or modifications of this file, via any medium is strictly prohibited.

import touchlab_comm_py as tl
import time
import argparse

def main():
    try:
        # Set up argument parser
        parser = argparse.ArgumentParser(description="Touchlab Sensor Example")
        parser.add_argument("port", type=str, help="Serial port to connect to")
        parser.add_argument("-p", "--parameter_file", type=str, help="Parameter file to load")
        args = parser.parse_args()
        if args.parameter_file is None:
            args.parameter_file = ""

        # Connect to the sensor
        com=tl.TouchlabComms()
        com.init(args.parameter_file)
        com.connect(args.port)

        time.sleep(1.0)  # Wait for connection to stabilize
        com.zero([])

        # Set up frequency counting
        start = time.time()
        hz = 0.0
        count = 0
        while True:
            # Read data and print
            data = com.read(1000)
            print(f"Rate: {hz:.1f}Hz, Calibrated Data: {data}")

            # Read raw data and print
            data_raw = com.read_raw(0)
            print(f"Rate: {hz:.1f}Hz, Raw Data: {data_raw}")

            # Calculate sensor update rate
            diff = float(time.time() - start)
            if diff > 0.5:
                hz = float(count) / diff
                count = 0
                start = time.time()
            count += 1
    except KeyboardInterrupt:
        pass

if __name__ == "__main__":
    main()

The following code will not connect to the Touchlab device, but it will translate raw data provided by user into calibrated values using the Touchlab library. You have to provide a calibration file for this to work. The calibration requires the model to be biased. We do this by calling the zeroing function before translating the data. You have to choose one or more samples that represent sensor values without any load.

#!/usr/bin/env python3

# Copyright (c) 2025 Touchlab Limited. All Rights Reserved
# Unauthorized copying or modifications of this file, via any medium is strictly prohibited.

import touchlab_comm_py as tl
import time
import argparse
import numpy as np

def plot(raw, translated):
    import matplotlib.pyplot as plt
    plt.figure(figsize=(12, 6))

    x = np.arange(raw.shape[0])

    plt.subplot(2, 1, 1)
    plt.title("Raw Data")
    plt.plot(x, raw)
    plt.ylabel('Channels')
    plt.xlabel('Samples')

    plt.subplot(2, 1, 2)
    plt.title("Translated Data")
    plt.plot(x, translated)
    plt.ylabel('Channels')
    plt.xlabel('Samples')

    plt.tight_layout()
    plt.show()

def main():
      # Set up argument parser
      parser = argparse.ArgumentParser(description="Touchlab Sensor Example")
      parser.add_argument("parameter_file", type=str, help="Parameter file to load")
      args = parser.parse_args()

      # Load parameters from a file
      com=tl.TouchlabComms()
      com.init(args.parameter_file)

      # Create sample data for translation
      sample_data = np.tile(np.sin(np.linspace(0, np.pi, 100)) *  3000 + 3000, (18, 1)).transpose()
      sample_data += np.round(np.random.normal(0, 20.0, sample_data.shape))

      # Pick a bias from the sample data
      bias = sample_data[0:1, :].tolist()

      # Zero the translator and translate the sample data
      com.zero(bias, [])
      translated = np.zeros((sample_data.shape[0], len(com.translate(sample_data[0]))))
      for i, row in enumerate(sample_data):
          translated[i, :] = com.translate(row)

      plot(sample_data, translated)

if __name__ == "__main__":
    main()