Recently I've written a project in order to control media players using Arduino and an IR remote and a PowerScript running on PC to recevie the information from Arduino via serial port.
The problem is that how can I script the PowerShell in order to do something only when it get some input from Arduino. Because right now I have a loop with delay in powershell script and every time when the code is executed, it reads and check if it got some input from Arduino. But how can I do to not wait but to trigger the PowerShell script only when Arduino sends something?
Here's my PowerShell script:
$console = $host.UI.RawUI
$console.BackgroundColor = "darkgreen"
$console.ForegroundColor = "black"
$size = $console.WindowSize
$size.Width = 15
$size.Height = 2
$console.WindowSize = $size
$buffer = $console.BufferSize
$buffer.Width = 15
$buffer.Height = 2
$console.BufferSize = $buffer
Write-Host "PC Media Remote"
function IRinputText {
Param([string]$serialread,[string]$combo,[string]$key)
Process{If ($IRbuffer -like ("*"+$serialread)) {IRbufferReset;$wshell.SendKeys($combo+"{"+$key+"}")}}
}
function IRinputHEX {
Param([string]$serialread,[string]$key)
Process{If ($IRbuffer -like ("*"+$serialread)) {IRbufferReset;$wshell.SendKeys([char]+$key)}}
}
function IRbufferReset {
$Script:IRbuffer=""
$Script:IRbuffer= $Script:IRbuffer.PadLeft(15,'0')
}
IRbufferReset
$port= new-Object System.IO.Ports.SerialPort COM4,9600,None,8,one
$wshell = New-Object -ComObject wscript.shell;
$port.open()
while($true)
{
$inputvar= $port.ReadExisting() -replace "`n","" -replace "`r",""
If(($inputvar -ne "")){
$IRbuffer= If($IRbuffer.Length -ge $inputvar.Length){$IRbuffer.Substring($inputvar.Length) }
$IRbuffer= $IRbuffer + $inputvar
}
If($IRbuffer.Length -gt 15){$IRbuffer= $IRbuffer.Substring($IRbuffer.Length - 15);}
IRinputText -serialread "CH+" -combo "^" -key "UP"
IRinputText -serialread "CH-" -combo "^" -key "DOWN"
IRinputText -serialread "100+" -combo "^" -key "LEFT"
IRinputText -serialread "200+" -combo "^" -key "RIGHT"
IRinputText -serialread "CH" -key "f"
IRinputHEX -serialread "VOL+" -key "0xAF"
IRinputHEX -serialread "VOL-" -key "0xAE"
IRinputHEX -serialread "PLAY/PAUSE" -key "0xB3"
IRinputHEX -serialread "PREV" -key "0xB1"
IRinputHEX -serialread "NEXT" -key "0xB0"
IRinputHEX -serialread "EQ" -key "0xAD"
If ($IRbuffer -like ("*1532")) {IRbufferReset;Stop-Computer}
Start-Sleep -m 20
}