Saturday 21 February 2015

Arduino - Sending key presses from attached PC


I wanted to be able to send real time key presses to the Arduino from the PC so could not use the Arduino application as it requires the return key after every send. I initially tried a simple bat file with echos to the COM ports but could not get it to work. In the end I wrote a powershell script:

$port = new-Object System.IO.Ports.SerialPort COM9,9600,None,8,one
$port.open()
do
{
  $key = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
  Write-Host $key.Character
  $port.WriteLine($key.Character) 
}
while(($key.Character -ne 'q'))
$port.Close()

Put the above into a script (scr.ps1) and invoke it as follows:

c:\> powershell -ExecutionPolicy ByPass -File scr.ps1

Ensure you have closed the Arduino app or you will get a permission error talking to the COM port. Also ensure you amend the COM9 (first line of script) to be the appropriate COM port. The script will run until the q key is pressed. I have only tested it on Windows 7 so I don't know whether it will work with powershell 1 (XP / Vista version). The corresponding Arduino code is simply:

void setup() { serial.begin(9600); }

void loop() {
  char inChar = serial.read();
  if (inChar == 'a') {
    // 'a' key was pressed
  }
}

No comments:

Post a Comment