Raspberry pi --An object-oriented version of what I was able to find when I wanted to exchange data between Arduino and so on.
Serial.ino
int n = 12;
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println(n);
Serial.write("Hello World!\n");
delay(1000);
}
--For the time being, check if communication is possible with the serial monitor.
--Close the serial monitor when you can confirm the communication on the serial monitor. (If you don't close it, you will get a SerialException
error.)
--Communication speed is set to 9600
--Use the Serial.print
function to send numbers and the Serial.write
function to send strings. (Can't we make one?)
Install the library required for serial communication with Python.
pip install pyserial
Arduino_USB.py
import serial
import time
class Arduino_USB:
data = ""
#constructor
def __init__(self, dev, bps):
#Communication settings Device name Communication speed
self.ser = serial.Serial(dev, bps)
time.sleep(2)
#Start serial communication
def startUSB(self):
#Start command. Byte character"a"Send
self.ser.write(b"a")
#Serial communication disconnection
def closeUSB(self):
self.ser.close()
#Read data from Arduino
def getUSB(self):
self.data = self.ser.readline()
return str(self.data, encoding = "utf-8")
a = Arduino_USB("/dev/ttyACM0", 9600)
a.startUSB()
print(a.getUSB())
print(a.getUSB())
a.closeUSB()
--Connect Arduino to Raspberry pi via USB.
--The device name is basically recognized by / dev / ttyACM0
.
--Set the same communication speed as the Arduino side.
--Wait for lag on the Arduino side with time.sleep
.
-Maybe you are reading up to the line feed code?
12
Hello
――I'm not sure about the synchronization of data reading timing and the reading range. (It was written as 1Byte, but why can I read Japanese?)
――Isn't it possible to use the Serial.print
function to send numbers and the Serial.write
function to send strings?
――It's a mystery, but it's a personal play, so if you move, Yoshi!
Recommended Posts