Código más simple para conectar:
import serial
arduino = serial.Serial('com3', baudrate=57600, timeout=1.0)
while True:
line = arduino.readline()
print(line)
Código para enviar y recibir datos desde Arduino a Python por el serial:
import serial
import msvcrt # to detect keys pressed
import time # to execute time functions ( gives the ability to use delay-like commands )
print("Connecting to Arduino....") # print(something
arduino = serial.Serial('com3', baudrate=57600, timeout=1.0)
time.sleep(2)# wait for 2 seconds
print("Connected Successfully!")
while True:
line = arduino.readline()
print(line)
if msvcrt.kbhit(): # if a key is pressed
keypress = ord(msvcrt.getch()) # store the ASCII value of the character into our variable keypress
if keypress == 119: #if 'w' is pressed (ASCII value of 'w' is 119)
print('up') #simply print('up' in command prompt
arduino.write('w'.encode('ascii')) #send 'w' to Arduino
if keypress == 115: #if 's' is pressed (ASCII value of 's' is 115)
print('down') #simply print('down' in command prompt
arduino.write('s'.encode('ascii')) #send 's' to Arduino
if keypress == 97: #if 'a' is pressed (ASCII value of 'a' is 97)
print('left') #simply print('left' in command prompt
arduino.write('a'.encode('ascii')) #send 'a' to Arduino
if keypress == 100: #if 'd' is pressed (ASCII value of 'd' is 100)
print('right') #simply print('right' in command prompt
arduino.write('d'.encode('ascii')) #send 'd' to Arduino
if keypress == 101: #if 'e' is pressed (ASCII value of 'e' is 101)
print('stop') #simply print('stop' in command prompt
arduino.write('e'.encode('ascii')) #send 'e' to Arduino
Ojo con la decodificación a ascii con bytes para enviar al Arduino:
date_string = str(datetime.datetime.now())
dates_bytes = date_string.encode('ascii')
ser.write(date_bytes)
http://stackoverflow.com/questions/34653568/error-writing-to-serial-device-in-python
Captura de Teclas Teclado desde python:
http://www.robotshop.com/letsmakerobots/a-guide-to-building-python-apps-for-controlling-your-robot
Referencia que puede servir:
http://pybonacci.org/2014/01/19/leer-datos-de-arduino-desde-python/
No hay comentarios:
Publicar un comentario