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.

RocketTwitch
  • 101
  • 2

1 Answers1

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');
  }
}
Martynas
  • 538
  • 3
  • 10