Arduino Forum

Using Arduino => Interfacing w/ Software on the Computer => Topic started by: powergolden on Aug 26, 2014, 04:09 am

Title: arduino and pyserial
Post by: powergolden on Aug 26, 2014, 04:09 am
I am trying to connect my arduino uno board to windows 8 through pyserial and send a series of numbers from arduino to pyserial. how would i go about doing this?
Title: Re: arduino and pyserial
Post by: AJITnayak on Aug 26, 2014, 07:07 am
If using python. Then  you need usb to TTL converted to interface with Arduino
Then only you can get data or send data over arduino.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 07:14 am

If using python. Then  you need usb to TTL converted to interface with Arduino
Then only you can get data or send data over arduino.


This is wrong.

You need to simply open the serial port in python and start sending data. Or recieving data.
Study the pose rial documentation.
The baud rate must be set the same as the arduino.
On the arduino end you use serial read and write just as you would with any serial input / output.
Title: Re: arduino and pyserial
Post by: AJITnayak on Aug 26, 2014, 07:19 am
Quote

You need to simply open the serial port in python and start sending data. Or recieving data.
Study the pose rial documentation.
The baud rate must be set the same as the arduino.
On the arduino end you use serial read and write just as you would with any serial input / output.


You can try this out. I am sure it will
not going to work unless it has USB to ttl converter in case of arduino,
Yes it is true, you followed right process but i doubt it will work.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 07:21 am

Quote

You need to simply open the serial port in python and start sending data. Or recieving data.
Study the pose rial documentation.
The baud rate must be set the same as the arduino.
On the arduino end you use serial read and write just as you would with any serial input / output.


You can try this out. I am sure it will
not going to work unless it has USB to ttl converter in case of arduino,
Yes it is true, you followed right process but i doubt it will work.


Why do you comment about things you know nothing about?
This is rubbish. I have done this many times.
Title: Re: arduino and pyserial
Post by: AJITnayak on Aug 26, 2014, 07:26 am
What you think yourself. We also not done these kind of stuff. I have also programmed. i also tried these kind of stuff in python.I have written the statement on basis of trial runs done on arduino and python communication
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 07:29 am

What you think yourself. We also not done these kind of stuff. I have also programmed. i also tried these kind of stuff in python.I have written the statement on basis of trial runs done on arduino and python communication

Then you have no idea about what you have done. And very poor language skills in trying to express what you have done.
Title: Re: arduino and pyserial
Post by: Coding Badly on Aug 26, 2014, 07:55 am
I have done this many times.


As have I.  Several times in the last few days.

The only caveat is opening the serial port resets the Arduino.  Which can be disabled with a capacitor or Exacto knife.
Title: Re: arduino and pyserial
Post by: Coding Badly on Aug 26, 2014, 07:59 am

Waits for the Arduino to send an 'M'...

Code: [Select]
import serial

port = 'COM26'
#port = 'COM6'
baud = 1000000
timeout = 3

_serial = serial.Serial( port, baud, timeout=timeout )

_serial.flushInput()

gotsomething = False

for j in range(3):
 response = _serial.readline().decode( 'ascii' ).strip()
 if response != '':
   cracked = response.rstrip().split('\t')
   if cracked[0] == 'M':
     gotsomething = True
     break

Title: Re: arduino and pyserial
Post by: Robin2 on Aug 26, 2014, 10:30 am
This demo illustrates Python to Arduino comms (http://forum.arduino.cc/index.php?topic=225329.msg1810764#msg1810764). It should work on any PC as long as the correct reference to the serial port is used.

The Arduino code also works just with the Arduino Serial Monitor.

...R
Title: Re: arduino and pyserial
Post by: powergolden on Aug 26, 2014, 11:20 pm
Ive gotten as far now as sending data. it doesn't seem to be reeding it right.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 11:21 pm

Ive gotten as far now as sending data. it doesn't seem to be reeding it right.

You are going to have to do better in your explanation.
What side is sending and what is receiving on the system you have got working?

Plus post the code you have now.
Title: Re: arduino and pyserial
Post by: powergolden on Aug 26, 2014, 11:30 pm
on the arduino side
Code: [Select]
/*
* ArduinoNunchukDemo.ino
*
* Copyright 2011-2013 Gabriel Bianconi, http://www.gabrielbianconi.com/
*
* Project URL: http://www.gabrielbianconi.com/projects/arduinonunchuk/
*plastic down
*top left A5 top right ground bottom left 3.3v bottom right A4
*/

#include <Wire.h>
#include <ArduinoNunchuk.h>

#define BAUDRATE 19200
const int led = 13;
const int left = 12;
const int right = 7;
const int up = 4;
const int down = 8;
const int ledz = 2;
int c = 1;
int cbutton = 0;
ArduinoNunchuk nunchuk = ArduinoNunchuk();

void setup()
{
 Serial.begin(9600);
 nunchuk.init();
 pinMode(led,OUTPUT);  
 pinMode(up,OUTPUT);  
 pinMode(down,OUTPUT); // this is your basic code that says what pins do.
 pinMode(left,OUTPUT);
 pinMode(right,OUTPUT);
 pinMode(ledz,OUTPUT);
}

void loop()
{
 nunchuk.update();

 Serial.write(nunchuk.analogX); //first number to send
 Serial.print(',');
 Serial.write(nunchuk.analogY);
 Serial.print(',');
 Serial.write(nunchuk.accelX);
 Serial.print(',');
 Serial.write(nunchuk.accelY);
 Serial.print(',');
 Serial.write(nunchuk.accelZ);
 Serial.print(',');
 Serial.write(nunchuk.zButton);
 Serial.print(',');
 Serial.write(nunchuk.cButton); //last number to send


                                                          // EVERYTHING PAST THIS POINT IS IRRELAVENT



if (nunchuk.cButton == 1) {
   if (cbutton == 0) {
      if (c == 1) {
       digitalWrite(led,LOW);
     cbutton = 1;
     c = 0;
     }
     else
     {
     digitalWrite(led,HIGH);
   cbutton = 1;
   c = 1;
   }
 }
 }
 else
 {
   cbutton = 0;
 }
 if (nunchuk.zButton == 1) {
   digitalWrite(ledz,HIGH);
 }
 if (nunchuk.zButton == 0) {
   digitalWrite(ledz,LOW);
 }
 if (nunchuk.analogY > 150) {
   digitalWrite(up,HIGH);
 }
 else
 {
   digitalWrite(up,LOW);
 }
 if (nunchuk.analogY < 110) {
   digitalWrite(down,HIGH);
 }
 else
 {
   digitalWrite(down,LOW);
 }
 if (nunchuk.analogX > 150) {
   digitalWrite(right,HIGH);
 }
 else
 {
   digitalWrite(right,LOW);
 }
 if (nunchuk.analogX < 110) {
   digitalWrite(left,HIGH);
 }
 else
 {
   digitalWrite(left,LOW);
 }
}



basicly what im trying to do is send these numbers over serial and recieve them in python to set each one as a variable.
all

on python
Code: [Select]
import serial
arduino= serial.Serial('COM3', 9600)
data = arduino.read(20)
hi = data[0] //Set hi to the first number.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 11:35 pm
OK I am not going to even read that until you put code tags round it.
If you don't know what that means read the how to use the forum sticky post.

Plus you need to say what it does, that is what you are seeing, and you need to post all the python code.
Title: Re: arduino and pyserial
Post by: powergolden on Aug 26, 2014, 11:43 pm
that is all the code.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 26, 2014, 11:47 pm
Thanks for amending the post.


that is all the code.

If it is then how do you know it is not working? Is ther some error message that you have not been telling us about?

I would have expected to see a print statement somewhere to display what you got.

Go for just receiving one byte and printing it out.
When you open the buffer flush it to clear any stuff that the arduino has been spitting out.

Remember what python is receiving are characters they are not numbers yet until you convert them.
Title: Re: arduino and pyserial
Post by: powergolden on Aug 26, 2014, 11:59 pm
I dont know if you know python or not, but when i do
Code: [Select]
data = arduino.read(20)
hi = data[0]

it tells me the output. Heres what i did to test it.

On The arduino:
Code: [Select]
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.print(300);
  Serial.print(',');
}


on python:
Code: [Select]
import serial
arduino= serial.Serial('COM3', 9600)
data = arduino.read(20)
hi = int(data[0])

depending on what i set "hi" to it gives me a different number. It will change even though all numbers printed on serial should be alike.  If you need a example ask But while you respond i will be working on getting them.
Title: Re: arduino and pyserial
Post by: powergolden on Aug 27, 2014, 12:05 am
Heres those examples

input >>> data = arduino.read(21)
input>>> data
b'00,300,300,300,300,30'

i>>> data = arduino.read(20)
>>> data
b'0,300,300,300,300,30'

>>> hi = int(data[1])
>>> hi
44

>>> hi = int(data[2])
>>> hi
51

>>>
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 27, 2014, 12:07 am
Quote
I dont know if you know python or not, but when i do it tells me the output. Heres what i did to test it.

So this is in the direct mode from the console?

When you send
Code: [Select]
Serial.print(300);
You will send the ASCII codes 0x33, 0x30, 0x30. In decimal these will be 51, 48, 48
You are sending them very fast so you are filling up the buffer.

Quote
depending on what i set "hi" to it gives me a different number.

You need to say what the numbers are to make any sense of this.

Edit. Just seen your results, does this make sense to you now?
Comma is 44 in decimal as well. so it is working you are just not converting them correctly.
Title: Re: arduino and pyserial
Post by: powergolden on Aug 27, 2014, 12:13 am
So. not to rush it or anything, but how would i fix it and send numbers like this across? Would you recommend breaking the numbers down before sending them? But after I break them down then what? Sorry BTW for being a total Noob at this.
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 27, 2014, 12:26 am
At the moment the only thing that separates your numbers is comma, yuo extract a number like this you read the serial port one bit at a time until you find a comma, that marks the end of your last number. Then you gather bytes into a list until you get another comma, don't add that to the list. Then you convert each byte from the character into a number with an (ord(data[0]).
For each successive number you then multiply the previous number by ten and add the next byte to it.

Bottom line is you have to think about what data format you are sending and how you communicate with the arduino.

This bit of code I used to get two 16 bit ints from the arduino. Each byte was tagged with a unique top two bits so I could identify them.
Code: [Select]

def openPort():
      global running
      ser.flushInput()
      # tell the arduino to start sending
      running = True
      ser.write('3')
      ser.write('G')
     
def checkInput(b): # see if the bytes have been received in the correct order
      correct = True
      for i in range(0,4):
           #print i," - " # ,hex(ord(b[i]))
           if (ord(b[i]) >> 6) != i :
              correct = False
      return correct
           
def getData():
  global reading, running
  if running :    
       a = ser.read(4)        
       if checkInput(a) :
           reading[0] = ((ord(a[0]) & 0x1f)<< 5) | (ord(a[1]) &0x1f)
           reading[1] = ((ord(a[2]) & 0x1f)<<5) | (ord(a[3]) &0x1f)
           #print reading[0]," - ",reading[1]
       else:
           correct = False
           while correct == False : # resyncronise
               print "lost sync ",ser.inWaiting()
               b = ser.read(1)
               t = a[1] + a[2] + a[3] + b[0]
               a = t
               correct = checkInput(a)



The code is from my book:-
http://www.thebox.myzen.co.uk/Raspberry/Pi_Projects.html (http://www.thebox.myzen.co.uk/Raspberry/Pi_Projects.html)
Which describes both the arduino code and the python code. You should be able to down load both from the book's web site.
It is chapter 16.

Quote
Would you recommend breaking the numbers down before sending them?

You have no choice the numbers are sent only one byte at a time by the hardware so they are broken down.
Title: Re: arduino and pyserial
Post by: Robin2 on Aug 27, 2014, 10:26 am
The demo (http://forum.arduino.cc/index.php?topic=225329.msg1810764#msg1810764) I linked to in Reply #9 works in both directions. Have you got that to work?

This newer demo shows how you can send binary data from Python to the Arduino (http://forum.arduino.cc/index.php?topic=263107.0). The same concept could also be used in reverse.

...R
Title: Re: arduino and pyserial
Post by: powergolden on Aug 28, 2014, 11:28 pm
I would be testing out my code but i keep getting this error when attempting to import pyserial:


Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
  File "C:\Python33\serial\__init__.py", line 19, in <module>
    from serial.serialwin32 import *
  File "C:\Python33\serial\serialwin32.py", line 12, in <module>
    from serial import win32
  File "C:\Python33\serial\win32.py", line 196
    MAXDWORD = 4294967295L # Variable c_uint
                         ^
SyntaxError: invalid syntax
Title: Re: arduino and pyserial
Post by: Robin2 on Aug 29, 2014, 11:02 am
I give up.

...R
Title: Re: arduino and pyserial
Post by: Grumpy_Mike on Aug 29, 2014, 11:27 am
That looks like a windows problem. Unfortunately for you I have only used Python under Linux.