Go Down

Topic: Powershell serial communication with Arduino (Read 2953 times) previous topic - next topic

maxr

I was just pulling my hair out trying to figure out why I can't communicate with the Arduino through Windows Powershell (which relies on .NET components).  Hopefully this will help others.  The final code is:

Code: [Select]

$port = New-Object System.IO.Ports.SerialPort
$port.PortName = "COM6"
$port.BaudRate = "9600"
$port.Parity = "None"
$port.DataBits = 8
$port.StopBits = 1
$port.ReadTimeout = 9000 # 9 seconds
$port.DtrEnable = "true"

$port.open() #opens serial connection

Start-Sleep 2 # wait 2 seconds until Arduino is ready

$port.Write("93c") #writes your content to the serial connection

try
{
  while($myinput = $port.ReadLine())
  {
  $myinput
  }
}

catch [TimeoutException]
{
# Error handling code here
}

finally
{
# Any cleanup code goes here
}

$port.Close() #closes serial connection



The line that made all the difference was this:

$port.DtrEnable = "true"

Also, I have my Arduino write back a response after it executes every command, hence the read afterwards.

Hope this helps someone.

zoomkat

Most interesting. How is the input to the pc serial port from the arduino displayed by powershell? I use batch files to send strings to the com port, but cmd.exe doesn't have the capability to read he serial port input buffer.
Google forum search: Use Google Advanced Search and use Http://forum.arduino.cc/index in the "site or domain:" box.

maxr

Thanks Zoomkat.  I would have used my usual way of doing things through cmd, vbscript in windows scripting host, but there are issues with calling the comm ocx.  Powershell uses the latest .NET objects so is very powerful once you get the hang of it.  I also recommend making sure you have version 2.0 of Powershell.  Anyway, because Powershell (which is now Microsoft's official scripting platform) uses .NET objects you have as much power as you would programming a C# application.  That's what got me through the hours of pulling my hair out with Powershell.  It is not like DOS or VBSCRIPT commands at all.  More like Ruby.  It did hurt my head.  

Go Up