I am trying to send x and y coordinates from my Python on my Raspberry Pi to a Arduino Nano. Currently, I am using serial communication, packing the coordinates with struct.pack(), but my Arduino is not receiving the coordinates the way I would expect.
import serial
import struct
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout = 1)
def sendpacket(x,y) # x and y are integers
packet = struct.pack('BsBs',x, ',' , y, ',')
print packet
print ord(packet)
ser.write(packet)
I have inserted commas so that the Arduino can tell the difference between x's and y's. I know that the Arduino can only read one byte at a time, which is why I was packing the data before sending it, but I don't really understand what is going on.
I know struct.pack() converts my packet to Unicode, or at least it appears to from my above print statements. Is that what is actually being send over serial? How should I read this in the Arduino code?
Alternatively, is there a better way to send/receive xy coordinates over serial?
I am a beginner, I know/understand very little of what I am trying to do.
Related
I'm using LoRa Dorji DRF1278DM as a communication module and set it central mode. From the datasheet (http://www.dorji.com/docs/data/DRF1278DM.pdf), the central module needs to send a string with a specific format.
I'm using raspberry pi for the central module and arduino for the node module (with node id=1). Trying a simple program, to send string "hello" from Raspberry to Arduino. This is the code:
import serial
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
ser.flush()
while True:
ser.write(serial.to_bytes([0x00,0x01,0x68,0x65,0x6c,0x6c,0x6f]))
time.sleep(5)
*2 first bytes for the id node and the rest is 'hello' in hex
Arduino receive data from the raspberry but have a problem to receive it in string type
void setup(){
Serial.begin(9600);
}
int=data;
void loop(){
if(Serial.available()>0){
data=Serial.read();
Serial.println(data);}
}
If I set the data type as integer, there isn't any problem in receiving it but don't know how to convert it to "hello" back. Try set data type as char but giving error "incmompatible types in assignment of 'int' to 'char'
Is there a way to receive it as string? also is there other method that allow me to send data from raspberry pi without converting each data as hex and then send it in bytes with keep including the header bytes(node id of node module)
I'm trying to read and write data from an RFID tag using python whit this module:
https://es.aliexpress.com/item/32573423210.html
I can connect successfully whit serial but I don't know how to read any tag, because the datasheet from pr9200(the reader that I am working) use this:
Image for pr9200 operation It's like a raw packet whit only hex address that I need to send to the module for it works
my code on python is this:
import serial
ser = serial.Serial(port = "COM27", baudrate=115200, bytesize=8, parity='N', stopbits=1)
while(ser.is_open == True):
rfidtag = ''
incomingByte = ser.read(21)
print(incomingByte)
for i in incomingByte:
rfidtag = rfidtag + hex(i)
Some comments to jump start your coding:
-What you need to do is send a command to your device to ask it to start sending readings in auto mode. To do that you need to use ser.write(command). You can find a good template here.
-To prepare the command you just need to take the raw bytes (those hex values you mentioned) and put them together as, for instance a bytearray.
-The only minor hurdle remaining is to calculate the CRC. There are some nice methods here at SO, just search CRC 16 CCITT.
-Be aware that after writing you can not start immediately waiting for readings, you have to wait first for the device to acknowledge the command. Hint: read 9 bytes.
-Lastly, take a new count of the bytes you will receive for each tag. I think they are 22 instead of 21.
You can use pyembedded python library for this which can give you the tag id.
from pyembedded.rfid_module.rfid import RFID
rfid = RFID(port='COM3', baud_rate=9600)
print(rfid.get_id())
https://pypi.org/project/pyembedded/
I'm trying to combine three values that I got through serial port using pyserial. These values are corresponding to 3 parts of a 24bit data transmitted from and fpga board and I want to get the 24 bit data in python script. What kind of a conversion and combination process can give me back this 24 bit data? I'm reading data using below simple while loop...
import serial
port = serial.Serial('/dev/ttyUSB0', 115200)
file = open("my_file.txt","a")
while True:
message = ord(port.read())
print(message)
file.write(str(message) + "\n")
file.close()
Thanks in advance :)
You can use the struct module (built-in Python) for pack those 3 bytes into one:
import struct
#Your code ...
while True:
message = port.read(3) #Read 3 bytes at once
combined = struct.unpack(">I", b'\x00' + message)[0]
The >I means you decoding 32-bit unsigned integer (I) saved in big-endian (>). Because struct.unpack() doesn't support 24-bit numbers I added 1 zero byte to the start of the 24-bit number which effectively creates 32-bit number.
Your help is badly needed...
I'm trying to read data and print it to the python console from a load cell. My setup is as follow:
The load cell is a MD type from Eilersen connected to a load cell signal converter of type MCE2040 Seriel Communication Module also from Eilersen. The MCE2040 is connected to my PC through a USB to seriel connector like this link_http://www.usbgear.com/USB-COM-I-SI.html (I'm only allowed two links) one.
The load cell is connected to COM 1.
I have tried to run this snippet:
import serial
ser = serial.Serial(0) # open first serial port
print ser.portstr # check which port was really used
#ser.write("hello") # write a string
ser.close()
...and that prints 'COM1' to the console so I guess my connection should be okay.
My problem is that I don't know how to proceed. In the end I'd like to plot a graph of the incoming data and output a data file with time stamps, but for starters I'd like to print some load cell data to the console.
Any help will be highly appreciated. If further information is needed, please let me know.
Thx in advance.
Edit:
I have some documentation re MCE2040:
3.1 EVC Mode (without time stamp)
Specification: RS232/RS4422
Baudrate: 115200 bps
38400 bps (select with SW1.5)
Data bits: 7
Parity: Even
Stop bits: 1
Protocol: EVC protocol described below (Transmit Only)
3.1.1 EVC Protocol Format
After each sample period a new weight telegram is transmitted. The transmitted telegram has the following format:
<LF>WWWWWWWW<CR>
Each telegram contains a line feed character, a weight result and a carriage return character. The telegram contains:
<LF> Line Feed character (ASCII 0Ah).
WWWWWWWW Weight value for the loadcell. The value is an 8 byte ASCII hex number with MSB first.
<CR> Carriage Return character (ASCII 0Dh).
I was able to get some output from the following code:
import serial
ser = serial.Serial(0, baudrate=115000 ,timeout=100)
print ser.portstr
x = ser.read(50)
print x
ser.close()
print 'close'
Output:
COM1
ÆÆÆÆA0·5
ÆÆÆÆA0·6
ÆÆÆÆA0·5
ÆÆÆÆA0·±
ÆÆÆÆA0·±
close
First of all make sure it's really your com port, since COM1 is used by a lot of computers i'm not sure it's your com port.
You can use a simple wire to loop back info by connecting TX to RX at the USB to Serial converter, it will result in an echo (you will read what you write) it's a very simple way to verify that you are talking with the right com port.
Regarding how to continue:
Useful basic commands:
ser.write("command") with this command you send to the device some command.
ser.read(n) is for read n bytes from the device
ser.readline() will read line until it reached \n (new line)
Steps:
Send a command to your device.
Read all the data by some end byte (Frame Synchronization).
Parse data to structure (list or something like that..)
Plot it to graph.
Useful Links:
pyserial docs
tips for reading serial
plotly for graphs in python
I want to send data from a Simulink model (running in real time) to a Python script (also running in real time. I am using Simulink's built-in "UDP Send" block, which works, but I don't know how to decode the data I'm getting. This is what my python script looks like:
import sys, struct
from socket import *
SIZE = 1024 # packet size
hostName = gethostbyname('0.0.0.0')
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind((hostName,5002))
repeat = True
while repeat:
(data,addr) = mySocket.recvfrom(SIZE)
data = struct.unpack('d',data)
print data
I've suspected that the data stream should be something like a double, but while it's giving me numbers they aren't meaningful:
If simulink sends a constant "1", I get an output of "3.16e-322"
If Simulink sends a constant "2", I get an output of "3.038e-319"
Any ideas?
Turns out my network was reversing the packet bits. The solution was to read it in as bit-reversed:
data = struct.unpack('!d',data)
I have no clue why this happens over some networks and not others. Can someone comment on a way to tell if I need to use bit-reversal?
The problem occurs when the sender and receiver has different byte order.
See sys.byteorder.
Best practice should be to always convert to network order when sending and convert again when receiving.