1

I am working on a camera setup which could track a face when rotating camera on some servo motors. The way I want to do it (the way it's possible for me to do it) is like this: I use python openCV to get a face position and generate a vector which tells how much to turn to what direction so that the camera would look straight in a face. That vector is then sent to Arduino Uno where the input vector is decoded into a servo motor movement using Arduino IDE. The problem is sending vectors calculated in python script to Arduino. I used PowerShell commands to send said vectors to COM10 via Windows terminal:

$port= new-Object System.IO.Ports.SerialPort COM10, 9600, None, 8, one
$port.open()
$port.Writeline(vector)
$port.close()

When I use python os or subprocess commands like this:

os.system("powershell $port= new-Object System.IO.Ports.SerialPort COM10, 9600, None, 8, one")
os.system("powershell $port.open()")

Or

subprocess.run(["powershell", "-Command", "$port= new-Object System.IO.Ports.SerialPort COM10, 9600, None, 8, one"])
subprocess.run(["powershell", "-Command", "$port.open()"])

The first line works well, however the port variable I assume is not saved and I get a following error on the second line:

You cannot call a method on a null-valued expression.
At line:1 char:1
+ $port.open()
+ ~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

In the whole python script I only need one line to be executed repeatedly, because I get a live feed of a video from camera:

$port.Writeline(vector)

The other lines are used only when the script starts and stops running.

I tried many other things, like writing these 4 lines in PowerShell script and the executing it, but I can't even get that script to run on my terminal, etc. Will this kind of approach even work and I could fix it or should I just straight up give up with it an use something else? If it is possible then what could I be doing wrong?

AtticFizz
  • 51
  • 7

1 Answers1

2

It seems your issue here is that you are running the commands as subprocess. Once you run the first command os.system("powershell $port= new-Object System.IO.Ports.SerialPort COM10, 9600, None, 8, one") you have define the $port variable in a new process, and then that process exits and no longer exists.

When you run os.system("powershell $port.open()") you are creating a new process which has no knowledge that a $port variable has ever existed.

You will want to look at storing that script in its entirety in a separate file and run the whole script at once. This will also make that script easier for you to edit and debug later if you have any issues.

See this issue for help with running the script.

mklement0
  • 382,024
  • 64
  • 607
  • 775
joshmeranda
  • 3,001
  • 2
  • 10
  • 24