最近我编写了一个项目,目的是为了控制使用Arduino的红外遥控器和IR遥控器以及PC上运行的PowerScript来通过串口接收来自Arduino的信息。Arduino通过PowerShell脚本与PC进行通信
问题是,我如何编写PowerShell脚本才能在从Arduino获得一些输入时执行某些操作。因为现在我在PowerShell脚本中有一个延迟循环,每次执行代码时,它都会读取并检查它是否从Arduino获得了一些输入。但是我怎么能不等待,但只有当Arduino发送了一些东西时才触发PowerShell脚本?
这里是我的PowerShell脚本:
$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
}
您可以subscripe PowerShell来这是由次曝光的DataReceived事件检索处理e SerialPort类。 (这就是我用Arduinos来做的) – bluuf
@bluuf你能详细介绍一下吗?我是PowerShell的绝对初学者。谢谢! – raulx222