0

How would I establish a serial connection with python without using the serial monitor?

What I want to do is give my python script some input and have the arduino do something (blink for example)

I also want to be able to read in data with the arduino to give it to my python script.

What modules for python would be useful? I'm just starting out and don't have much of an idea for this one.

I am using a windows7 machine with python 2.7.6 and have an UNO board and a Leonardo board that I want to be able to use.

3
  • 1
    This question is about python not arduino
    – Martynas
    Nov 6, 2014 at 8:19
  • @Martynas - Technically you're right, and thanks for your vigilance here. However, we'll often allow questions like this which involve an Arduino even if the main issue is about something else. That policy is mainly for the sake of newcomers to the platform who perhaps don't know exactly where/what to ask. Nov 6, 2014 at 9:05
  • @PeterR.Bloomfield yes i read about something like this in meta and i said my opinion to Twitchykid. There are better places with more experienced ppl to ask.
    – Martynas
    Nov 6, 2014 at 9:07

1 Answer 1

1

This question is about Python not Arduino... Before asking here please ask GOOGLE

Anyway...

This is the answer Arduino and Python

Python code:

## import the serial library
import serial

## Boolean variable that will represent 
## whether or not the arduino is connected
connected = False

## open the serial port that your ardiono 
## is connected to.
ser = serial.Serial("COM11", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## Tell the arduino to blink!
ser.write("1")

## Wait until the arduino tells us it 
## is finished blinking
while ser.read() == '1':
    ser.read()

## close the port and end the program
ser.close()

Arduino code:

// Open a serial connection and flash LED when input is received

void setup(){
  // Open serial connection.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.write('1'); 
}

void loop(){ 
  if(Serial.available() > 0){      // if data present, blink
    digitalWrite(13, HIGH);
    delay(500);            
    digitalWrite(13, LOW);
    delay(500); 
    digitalWrite(13, HIGH);
    delay(500);            
    digitalWrite(13, LOW);
    Serial.write('0');
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.