Arduino serial communication with Raspi or computer with python Please read python format characters and Arduino data types
Last active
October 6, 2021 12:43
-
-
Save ahmaddidiks/d0371ccd6382732774a169b92f4489fb to your computer and use it in GitHub Desktop.
Serial Comunication raspberry pi and arduino
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| union { | |
| struct { | |
| int data1; | |
| int data2; | |
| int data3; | |
| } param; | |
| byte packet[6]; | |
| } data; | |
| union { | |
| struct { | |
| int data1; | |
| int data2; | |
| int data3; | |
| } param; | |
| byte packet[6]; | |
| } dataRecv; | |
| void setup() { | |
| // put your setup code here, to run once: | |
| Serial.begin(57600); | |
| pinMode(2, OUTPUT); | |
| } | |
| void loop() { | |
| // put your main code here, to run repeatedly: | |
| data.param.data1 = 1; | |
| data.param.data2 = 2; | |
| data.param.data3 = 3; | |
| Serial.write(data.packet, sizeof(data.packet)); | |
| if (Serial.available()) { | |
| Serial.readBytes(dataRecv.packet, sizeof(dataRecv.packet)); | |
| } | |
| delay(100); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import serial | |
| from time import sleep | |
| from struct import unpack, pack | |
| ser = serial.Serial('/dev/ttyACM0', 57600) # open serial port | |
| def sendData(data1, data2, data3): | |
| dataPacket = pack("hhh", data1, data2, data3) | |
| ser.write(dataPacket) | |
| while True: | |
| dataRaw = ser.read(6) #6 ===> 2 x 3 of short data types (2 Bytes) | |
| print(dataRaw) | |
| data1, data2, data3 = unpack("hhh", dataRaw) #hhh for short ===> int (in arduino [atmel microprocessors]) = short in python, they have same size, 2 Bytes | |
| print(f"data1: {data1}") | |
| print(f"data2: {data2}") | |
| print(f"data3: {data3}") | |
| sendData(3, 5, 7) | |
| sleep(0.1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment