Go Down

Topic: Python + Arduino (Read 1 time) previous topic - next topic

JeffersonAlmeida

Hello, I'm looking to make a communication between a software on PC (Python) and Arduino but I can't. Can Anybody help me in it?  :smiley-sweat:

I do not know where to start, but I have Python installed, I'm struggling in PySerial library.

if you have an example will be of great help.

Best Regards

Jefferson

l3gendluk3

Try look at the youtuber sciguy14 and one of his most recent videos is of the competition he entered where he interfaced arduino with python to get data off Facebook. There is example code from both.
There are two videos that have the source code, both has the name Facebook hackathon.

-Luke

Suriken

In python just have to do this:
1 - Import library:
Code: [Select]
import serial

2 - Open port:
Code: [Select]
ser = serial.Serial('/dev/ttyUSB0', 38400, timeout=1)

Setting the correct port and baudrate.

3 - Read data:
Code: [Select]
read = ser.read(X)

Where X is the number of bytes you want to read together. If you just write read = ser.read(), you read 1 byte.

I recommend you to read just one byte at a time because if you read more than one, it will kept as string and you cannot modify it. For avoiding it and be able to modify you have to save it as list but I haven't the code here right now.

And, the rest is treat that data in functions or whatever you want.

robtillaart


Some serial test program I found someday on the net, I do not recall where ... Should get you started
Code: [Select]

import time
import serial, sys, os

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(4, baudrate=9600, timeout=100)

ser
#ser.open()
ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
        # Python 3 users
        # input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)

if out != '':
print ">>" + out

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Si

Also have a look at PyFirmata:

https://github.com/lupeke/python-firmata/

The basic idea is a standard sketch runs on the Arduino and you turn pins on and off, set pin modes etc with Arduino-ish Python commands.

Its pretty neat.
--
My New Arduino Book: http://www.arduinobook.com

Go Up