LoginSignup
3
1

More than 3 years have passed since last update.

【pySerial】micro:bitにシリアル通信時「could not open port '/dev/cu.」エラーが出た時に考えられること

Last updated at Posted at 2020-08-05

pySerialを使ってmicro:bitにシリアル通信した際に以下のようなエラーが出た時の対処法備忘録です。

Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: '/dev/cu.usbmodem14302'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "testSerial.py", line 4, in
ser = serial.Serial(port,115200,timeout=None)
File "/usr/local/lib/python3.8/site-packages/serial/serialutil.py", line 240, in init
self.open()
File "/usr/local/lib/python3.8/site-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port /dev/cu.usbmodem14302: [Errno 2] No such file or directory: '/dev/cu.usbmodem14302'

Arduinoのシリアルポートを開いているとエラー

エラーのcould not open portという内容からUSBポートが使用中の可能性が考えられます。
僕の場合はArduinoのシリアルモニタを開いていたことが原因でした。
※デバッグのために使っていました。

閉じたら正常にシリアル通信出来ました。

最後に

今回のエラーはArduinoのシリアルモニタのように、シリアルポートを専有するような事をしていないかという視点を持つことが対処法になりそうです。

Python側

testSerial.py
import serial

mac='/dev/cu.usbmodem14302'
ser = serial.Serial(port,115200,timeout = None)
ser.write(b'1')
time.sleep(1)
ser.close()

micro:bit側(JavaScript)

receiveSerial.js
serial.setBaudRate(BaudRate.BaudRate115200)
basic.forever(function () {
    str = serial.readString()
    if (str.indexOf("1") >= 0) {
        basic.showIcon(IconNames.Heart)
    }
})
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1