This article was automatically translated from Japanese using AI. The Japanese version is the authoritative version.
Arduino is controlled using the Arduino language.
Sooner or later, however, you will want to do something more complex, or to control an Arduino together with another program.
The module introduced here, pySerial, lets you carry out serial communication with a Raspberry Pi or an Arduino.
Through serial communication, you can send commands from a Python program to an Arduino or Raspberry Pi and control them from Python.
Here I introduce the basic program for doing this.
Just being able to use it will greatly expand what you can do with your programs.
Installation
pip install pyserial
You can install it by opening Python in a terminal or command prompt.
Alternatively, you can install it from a terminal in an IDE such as PyCharm.
Example program
This example turns an LED on and off at one-second intervals.
I will test it by driving pin 13, which is connected to the LED built into the Arduino.
The Python program looks like this:
import serial, time
def main():
# COMポートを開く
print("Open Port")
ser = serial.Serial("COM3", 9600)
while True:
# LED点灯
ser.write(b"1")
time.sleep(1)
# LED消灯
ser.write(b"0")
time.sleep(1)
print("Close Port")
ser.close()
if __name__ == '__main__':
main()
Use serial.Serial to specify the port and the serial communication settings.
For the Arduino UNO, specify 9600.
This differs from board to board, so check it in the Arduino IDE.
The b in b”1″ plays a crucial role.
With the serial.write() function, numbers and strings must be converted to byte sequences before they can be sent over serial communication.
The b prefix is needed to indicate that the value is a byte sequence.
Since this program is an infinite loop, the LED keeps switching on and off every second until you stop the program.
Next is the program on the Arduino side.
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
digitalWrite(13, LOW); // 初期化
}
void loop() {
byte var;
var = Serial.read();
switch(var){
case '0':
digitalWrite(13, LOW);
break;
case '1':
digitalWrite(13, HIGH);
break;
default:
break;
}
}
Here I use a switch-case statement.
It makes the program easier to follow.
For details, take a look at my previous blog post.
In this program, sending 0 sets the pin LOW and sending 1 sets it HIGH.
Using this program as a base, you can control an Arduino from a Python program in all sorts of ways.
