I have an Arduino Nano Every and am using it to send a serial signal to my computer over COM5 when an external event happens that gives the Arduino's D2 pin an ON signal. The Arduino sees this signal on pin D2 and sends the serial signal to the computer. I want to be able to use this setup so that I can unplug and replug my Arduino from my computer using a USB cord, and then have the external event happen and the Arduino send the signal to my computer. I am using a PowerScript program to look on COM5 for the serial signal and close when it is seen. However, the problem is that I have to open and close the Serial monitor on the Arduino IDE before I can start the Powerscript program and have it work properly. If I don't, then the Powerscript program runs, but never sees the Arduino signal and never closes. What is the problem here? And how could I fix this so that I can simply plug in the Arduino to my computer, run the PowerScript program and get my serial signal when the Arduino external event happens.
Here is my Powerscrip program:
$portName = "COM5" # Modify to your actual port name
$baudRate = 9600
function Open-Port {
param (
[string]$portName,
[int]$baudRate
)
$port = new-Object System.IO.Ports.SerialPort $portName, $baudRate, None, 8, one
try {
$port.Open()
Write-Host "Port opened successfully."
} catch {
Write-Host "Error: $_.Exception.Message"
return $null
}
return $port
}
$port = Open-Port -portName $portName -baudRate $baudRate
if ($port -eq $null) {
Write-Host "Failed to open port. Exiting..."
exit 1
}
Write-Host "Listening on $portName. Press Ctrl+C to exit manually."
try {
while ($true) {
if ($port.BytesToRead -gt 0) {
$input = $port.ReadLine()
Write-Host "Received: $input"
if ($input -match "fire") { # Modify to the signal you expect
Write-Host "Trigger signal received. Exiting..."
break
}
}
# Start-Sleep -Milliseconds 100 # Delay to reduce CPU usage
}
}
finally {
if ($port -and $port.IsOpen) {
$port.Close()
Write-Host "Port closed."
}
}
exit 0
Here is my Arduino program that I have uploaded to the Arduino prior to everything happening:
const int ttlPin = 2; // Define the digital input pin connected to the DDG
void setup() {
// put your setup code here, to run once:
pinMode(ttlPin, INPUT); // Set as a normal input mode
Serial.begin(9600); // Initialize serial communication
// Serial.begin(115200); // Initialize serial communication
}
void loop() {
// put your main code here, to run repeatedly:
int ttlValue = digitalRead(ttlPin);
// High level detected
if (ttlValue == HIGH) {
Serial.println("fire");
delay(100); // Delay for 1000 milliseconds
}
}