Reading and writing serial port data with PowerShell

Posted on by 0 comment

List com ports

To see a list of available com ports,

PS C:\> [System.IO.Ports.SerialPort]::getportnames()
COM1
COM2
COM3

Read or write data

To read or write data with given details, such as port, Baudrate etc.

$port= new-Object System.IO.Ports.SerialPort COM3,9600,None,8,one
$port.open()
$port.WriteLine("some string data")
$port.ReadLine()
$port.Close()

Write unix time

I have a clock which accepts unix time for syncing the time, so I use script below to sync the time if the clock being off for few minutes after some time.

$time='T'+[string]([int](New-TimeSpan -Start (Get-Date "01/01/1970") -End (Get-Date)).TotalSeconds)
$port= new-Object System.IO.Ports.SerialPort COM3,9600,None,8,one
$port.open()
$port.WriteLine($time)
$port.Close()
Category: PowerShell, uart

Leave a Reply

Your email address will not be published. Required fields are marked *