MicroPython Driver for OpenLog

OpenLog Driver Code for micro:bit

Download as zip file

'''
OpenLog
Serial (UART) data logger
MicroPython driver for micro:bit

AUTHOR: fredscave.com
DATE  : 2024/12
VERSION : 1.00

micro:bit pin8 (tx) - OpenLog RX pin
micro:bit pin9 (rx) - OpenLog TX pin
micro:bit pin16     - OpenLog GRN pin
'''

from microbit import *
from utime import ticks_ms, ticks_diff

BAUD = 9600
NEWLINE = chr(10)

class OPENLOG():
    def __init__(self, Tx=pin8, Rx=pin9, Reset=pin16):
        uart.init(baudrate=BAUD, tx=Tx, rx=Rx)
        self.ResetPin = Reset
        Reset.write_digital(0)
        sleep(200)
        Reset.write_digital(1)
        self.OK = False
        start = ticks_ms()
        while ticks_diff(ticks_ms(), start) < 5000:
            if uart.any():
                if chr(uart.read(1)[0]) == '<':
                    self.OK = True
                    break

    def Close(self):
        sleep(2500)
        uart.init(115200)

    def Write(self, Buffer):
        if isinstance(Buffer, (bytes, bytearray, str)):
            uart.write(Buffer)
        elif isinstance(Buffer, (int, float)):
            uart.write(str(Buffer))
        sleep(10)

    def Writeln(self, Buffer=None):
        if isinstance(Buffer, (bytes, bytearray, str,
                               int, float)):
            if Buffer != None:
                self.Write(Buffer)
        uart.write(NEWLINE)
        sleep(10)

    def WriteCSV(self, Buffer):
        if isinstance(Buffer, (list, tuple)):
            total = len(Buffer)
            BufStr = ''
            count = 1
            for e in Buffer:
                if isinstance(e, (str)):
                    BufStr += e
                elif isinstance(e, (int, float)):
                    BufStr += str(e)
                if count != total:
                    BufStr += ','
                    count += 1
            BufStr += NEWLINE
            self.Write(BufStr)

    def Status(self):
        return self.OK