Pages: [1]   Go Down
Author Topic: Powershell serial communication with Arduino  (Read 2722 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 35
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
$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.
Logged

0
Offline Offline
Tesla Member
***
Karma: 147
Posts: 9741
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

0
Offline Offline
Newbie
*
Karma: 0
Posts: 35
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.  
Logged

Pages: [1]   Go Up
Jump to: