#!/usr/bin/python3 import serial import json from sys import stdout baud_rate = 115200 port = "/dev/ttyACM0" def recv(link): while True: line = link.readline().rstrip() try: line = line.decode("utf-8") except UnicodeDecodeError: continue try: data = json.loads(line) except ValueError: continue try: spectrum = data["spectrum"] fundamental_bin = data["fundamental_bin"] fundamental_freq = data["fundamental_freq"] midi_note = data["midi_note"] except ValueError: continue return spectrum, fundamental_bin, fundamental_freq, midi_note def show_spectrum(data): for line in range(50, 0, -1): for ampl in data: if ampl >= line: stdout.write('█') else: stdout.write(' ') stdout.write("\n") stdout.write("\n") stdout.flush() if __name__ == '__main__': link = serial.Serial(port, baud_rate) while True: spectrum, fundamental_bin, fundamental_freq, midi_note = recv(link) show_spectrum(spectrum) print("fundamental: bin %d -> %f Hz -> note %d" % (fundamental_bin, fundamental_freq, midi_note))