Using Arduino as output for Python progam

I'm trying to control Arduino outputs via USB with python. Basically if a value x in python is 5, then digital output 5 should be high.

What I had imagined was something like this on the

Python side:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)

x=5

while True:
ser.write('x')

Arduino:

void setup(){
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(4, OUTPUT);

}

void loop()
{
int out

int out = Serial.read()

if (out == 5){
digitalWrite(5, HIGH);

}

Am I way off?

You are basically right but there are some questions you will have to ask yourself like:

  • How do i turn pins off?
  • How can i plan my program so that it is scalable? You should be able to extend the number of pins and also restrict which pins are permittable output with a minimum of code chages

Before you have answered questions like you should refrain from writing any code. Partly because it will cause unnecessary reworking but more important, once you start to write code you will tend to stick to that solution and reject other ones.

This demo of Python and Arduino comms should help. Note the need to allow for the Arduino resetting when Python opens the serial port. And keep the serial port open until Python is completely finished with the Arduino.

...R

Thanks for your responses Shannon and Nilton!

What do you think of this solution by Cvyak?:

import serial
import time

ser = serial.Serial('/dev/ttyACM0', 9600)
x='5'

while True:
ser.write(x)

Now, you get '5' in out, not 'x'.

And arduino code:

void setup() {
Serial.begin(9600);
for(char i=0;i<10;i++)
pinMode(i, OUTPUT);
}

void loop() {
;
}

void serialEvent() {
if (Serial.available()) {
char inChar = (char)Serial.read();
inChar-='0';
for(char i=0;i<10;i++)
digitalWrite(i, LOW);
digitalWrite(inChar,HIGH);
}
}

I tried it and it seems to work perfectly between linux machine and arduino uno. I might add a time delay at the end in the python code, to stop it from blasting the arduino's RX pin.

davidjberman:
Thanks for your responses Shannon and Nilton!

What do you think of this solution by Cvyak?:
...SNIP...
I tried it and it seems to work perfectly between linux machine and arduino uno. I might add a time delay at the end in the python code, to stop it from blasting the arduino's RX pin.

I think you meant Robin rather than Shannon.

If it works perfectly you hardly need my opinion.
In any case why do you expect me to work on two solutions to your problem?

...R