Tag: シリアル通信

  • I Want to Control Arduino with Python!

    I Want to Control Arduino with Python!

    Arduino is normally controlled with the Arduino language.
    Sooner or later, though, you will want to do something more complex, or control an Arduino from within 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 code for doing this.
    Just being able to use this will greatly expand what your programs can do.

    How to install

    pip install pyserial

    You can install it by opening Python in a terminal or command prompt.
    Alternatively, you can install it from a terminal inside an IDE such as PyCharm.

    Example code

    This example is a program that turns an LED on and off at one-second intervals.
    I will test it by writing output to pin 13, which drives the LED built into the Arduino.
    On the Python side:

    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()

    serial.Serial specifies 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.
    The b prefix is what marks the value as a byte sequence.

    Since this program runs in 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 code, 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.