Go Down

Topic: Sending bytes (or numbers) from python to arduino over serial (Read 3133 times) previous topic - next topic

mahela007

Hi.. I'm new to arduino and I just got through the getting started and foundations sections. I also have some basic experience with programming python.
Untill I manage to get some interesting components to toy with, I decided to write a sketch that will make the arduino receive a value (say between 0 and 100) over the serial port and use that to set the brightness level of the onboard LED. (the one on pin 13).
However, I'm having trouble sending any numbers from the PC to the arduino..
Using the standard "write" function in pyserial sends ASCII code to the arduino.. I want to send a numerical value which can be used in a calculation.

PaulS

Quote
Using the standard "write" function in pyserial sends ASCII code to the arduino...

So, read them all (using some kind of end-of-packet marker helps you know when you got them all), then convert the string back to an int (atoi() is your friend).

mahela007

Thanks PaulS..
If anyone else has any more suggestions on how this can be achieved, please post them as well..

mahela007

Actually, I think I'd find an explanation of serial communications with the arduino very useful. Is it correct to say that all information (i.e what we call letters and numbers) are sent to the arduino as ASCII characters? Is there any way to send a piece of data so that it is considered to be an int (and not an ASCII character) by the Arduino processor?

PaulS

Quote
Actually, I think I'd find an explanation of serial communications with the arduino very useful.

http://jhaskellsblog.blogspot.com/2011/05/serial-comm-fundamentals-on-arduino.html

Quote
Is there any way to send a piece of data so that it is considered to be an int (and not an ASCII character) by the Arduino processor?

Yes, if the sending program is capable of sending binary data. The Arduino can send data using Serial.print() or Serial.write(). The print() method sends string data. The write() method sends binary data.

Whether python has that option, or not, I don't know.

mahela007

Just to clarify: I'd have to send a single byte binary representation of a decimal value to arduino right?

PaulS

Quote
Just to clarify: I'd have to send a single byte binary representation of a decimal value to arduino right?

You have to make the Arduino do something useful with the byte(s) you send. That can include reconstructing an int from 2 bytes, or a float from 4 bytes, or a struct from n bytes. Not a trivial task, but not all that difficult.

If the binary value you want to send fits in a byte, then it is easy to reconstruct that byte on the Arduino.

Go Up