Skip to content

Instantly share code, notes, and snippets.

@openfirmware
Created August 23, 2016 23:52
Show Gist options
  • Save openfirmware/c0da46508b344ce00c790edea964b9d1 to your computer and use it in GitHub Desktop.
Save openfirmware/c0da46508b344ce00c790edea964b9d1 to your computer and use it in GitHub Desktop.
Read from a serial port, print to screen and file with ISO timestamp with milliseconds

Run this, changing path to serial for your setup:

$ ruby read.rb /dev/cu.usbmodem1411

Output will be appended to serial.log in the current directory. Use control-C to exit. Connection will also be terminated if Arduino resets.

#!/bin/env ruby -wKU
require 'date'
require 'serialport'
port = ARGV[0]
baud_rate = ARGV[1] || 9600
file = "serial.log"
serial = SerialPort.new(port, baud_rate, 8, 1, SerialPort::NONE)
begin
while true do
while (i = serial.gets.chomp) do
date = DateTime.now.strftime("%Y-%m-%dT%H:%M:%S.%3N%z")
$stdout.puts "[" + date + "] " + i
File.write(file, "[" + date + "] " + i + "\n", { mode: 'a' })
end
end
ensure
serial.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment