# Open a serial port

In order to send commands to the device, you first need to open a **serial port**.

Which port to open depends on the computer, operating system, and how the device is connected.

> **Windows:**
>
> In the following examples, replace the placeholder port name, `COM3`, with name of your connection.
> If you are uncertain about the name of your connection, see [our guide to finding the right port](https://software.zaber.com/motion-library/docs/guides/communication/find_right_port.md).

> **Linux:**
>
> In the following examples, replace the placeholder port name, `/dev/ttyUSB0`, with name of your connection.
> If you are uncertain about the name of your connection, see [our guide to finding the right port](https://software.zaber.com/motion-library/docs/guides/communication/find_right_port.md).

> **Mac OS:**
>
> In the following examples, replace the placeholder port name, `/dev/tty.usbserial-A4017DXH`, with name of your connection.
> If you are uncertain about the name of your connection, see [our guide to finding the right port](https://software.zaber.com/motion-library/docs/guides/communication/find_right_port.md).

> **Windows:**
>
> **Python:**
>
> ```py
> with Connection.open_serial_port("COM3") as connection:
>     device_list = connection.detect_devices()
>     print("Found {} devices".format(len(device_list)))
>
>     # The rest of your program goes here (indented)
> ```
>
> **C#:**
>
> ```cs
> using (var connection = Connection.OpenSerialPort("COM3")) {
>     var deviceList = connection.DetectDevices();
>     Console.WriteLine($"Found {deviceList.Length} devices.");
>
>     // The rest of your program goes here
> }
> ```
>
> **JavaScript:**
>
> ```js
> const connection = await Connection.openSerialPort('COM3');
> try {
>     const deviceList = await connection.detectDevices();
>     console.log(`Found ${deviceList.length} devices.`);
>
>     // The rest of your program goes here
> } finally {
>     // Close the port to allow Node.js to exit
>     await connection.close();
> }
> ```
>
> **Java:**
>
> ```java
> try (Connection connection = Connection.openSerialPort("COM3")) {
>     Device[] deviceList = connection.detectDevices();
>     System.out.println(String.format("Found %d devices.", deviceList.length));
>
>     // The rest of your program goes here
> }
> ```
>
> **MATLAB (legacy):**
>
> ```matlabjava
> connection = Connection.openSerialPort('COM3');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', deviceList.length);
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **MATLAB:**
>
> ```matlab
> connection = Connection.openSerialPort('COM3');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **Octave:**
>
> ```octave
> connection = javaMethod("openSerialPort", CONNECTION_CLASS, "COM3");
> try
>     deviceList = connection.detectDevices();
>     fprintf("Found %d devices.\n", length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **C++:**
>
> ```cpp
> Connection connection = Connection::openSerialPort("COM3");
>
> std::vector<Device> deviceList = connection.detectDevices();
> std::cout << "Found " << deviceList.size() << " devices." << std::endl;
>
> // The rest of your program goes here
> ```

> **Linux:**
>
> **Python:**
>
> ```py
> with Connection.open_serial_port("/dev/ttyUSB0") as connection:
>     device_list = connection.detect_devices()
>     print("Found {} devices".format(len(device_list)))
>
>     # The rest of your program goes here (indented)
> ```
>
> **C#:**
>
> ```cs
> using (var connection = Connection.OpenSerialPort("/dev/ttyUSB0")) {
>     var deviceList = connection.DetectDevices();
>     Console.WriteLine($"Found {deviceList.Length} devices.");
>
>     // The rest of your program goes here
> }
> ```
>
> **JavaScript:**
>
> ```js
> const connection = await Connection.openSerialPort('/dev/ttyUSB0');
> try {
>     const deviceList = await connection.detectDevices();
>     console.log(`Found ${deviceList.length} devices.`);
>
>     // The rest of your program goes here
> } finally {
>     // Close the port to allow Node.js to exit
>     await connection.close();
> }
> ```
>
> **Java:**
>
> ```java
> try (Connection connection = Connection.openSerialPort("/dev/ttyUSB0")) {
>     Device[] deviceList = connection.detectDevices();
>     System.out.println(String.format("Found %d devices.", deviceList.length));
>
>     // The rest of your program goes here
> }
> ```
>
> **MATLAB (legacy):**
>
> ```matlabjava
> connection = Connection.openSerialPort('/dev/ttyUSB0');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', deviceList.length);
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **MATLAB:**
>
> ```matlab
> connection = Connection.openSerialPort('/dev/ttyUSB0');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **Octave:**
>
> ```octave
> connection = javaMethod("openSerialPort", CONNECTION_CLASS, "/dev/ttyUSB0");
> try
>     deviceList = connection.detectDevices();
>     fprintf("Found %d devices.\n", length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **C++:**
>
> ```cpp
> Connection connection = Connection::openSerialPort("/dev/ttyUSB0");
>
> std::vector<Device> deviceList = connection.detectDevices();
> std::cout << "Found " << deviceList.size() << " devices." << std::endl;
>
> // The rest of your program goes here
> ```

> **Mac OS:**
>
> **Python:**
>
> ```py
> with Connection.open_serial_port("/dev/tty.usbserial-A4017DXH") as connection:
>     device_list = connection.detect_devices()
>     print("Found {} devices".format(len(device_list)))
>
>     # The rest of your program goes here (indented)
> ```
>
> **C#:**
>
> ```cs
> using (var connection = Connection.OpenSerialPort("/dev/tty.usbserial-A4017DXH")) {
>     var deviceList = connection.DetectDevices();
>     Console.WriteLine($"Found {deviceList.Length} devices.");
>
>     // The rest of your program goes here
> }
> ```
>
> **JavaScript:**
>
> ```js
> const connection = await Connection.openSerialPort('/dev/tty.usbserial-A4017DXH');
> try {
>     const deviceList = await connection.detectDevices();
>     console.log(`Found ${deviceList.length} devices.`);
>
>     // The rest of your program goes here
> } finally {
>     // Close the port to allow Node.js to exit
>     await connection.close();
> }
> ```
>
> **Java:**
>
> ```java
> try (Connection connection = Connection.openSerialPort("/dev/tty.usbserial-A4017DXH")) {
>     Device[] deviceList = connection.detectDevices();
>     System.out.println(String.format("Found %d devices.", deviceList.length));
>
>     // The rest of your program goes here
> }
> ```
>
> **MATLAB (legacy):**
>
> ```matlabjava
> connection = Connection.openSerialPort('/dev/tty.usbserial-A4017DXH');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', deviceList.length);
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **MATLAB:**
>
> ```matlab
> connection = Connection.openSerialPort('/dev/tty.usbserial-A4017DXH');
> try
>     deviceList = connection.detectDevices();
>     fprintf('Found %d devices.\n', length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **Octave:**
>
> ```octave
> connection = javaMethod("openSerialPort", CONNECTION_CLASS, "/dev/tty.usbserial-A4017DXH");
> try
>     deviceList = connection.detectDevices();
>     fprintf("Found %d devices.\n", length(deviceList));
>
>     % The rest of your program goes here
>
>     connection.close();
> catch exception
>     connection.close();
>     rethrow(exception);
> end
> ```
>
> **C++:**
>
> ```cpp
> Connection connection = Connection::openSerialPort("/dev/tty.usbserial-A4017DXH");
>
> std::vector<Device> deviceList = connection.detectDevices();
> std::cout << "Found " << deviceList.size() << " devices." << std::endl;
>
> // The rest of your program goes here
> ```

Run the code and you should see the number of detected devices in the output of the application.

If you encounter a problem during this step, check that the device is connected correctly and powered on.
Also ensure that other applications, such as Zaber Console, do not have the port open by either selecting *Close* or exiting the application.
If you encounter `DeviceAddressConflictException`, use the Zaber Launcher application to assign distinct addresses to your devices.

During the device identification, the library connects to the internet to retrieve information about Zaber devices.
No personal or identifying information is exchanged with Zaber servers.
The library stores all the information in the operating system cache folder to later allow for offline use.
For more information about the behaviour see [Device Database](https://software.zaber.com/motion-library/docs/guides/advanced/device_db.md).

> **Python:**
>
> The example code demonstrates use of a [`with`](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement) statement to ensure that the serial port closes after the program runs.

> **C#:**
>
> The example code demonstrates use of a [`using`](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using) statement to ensure that the serial port closes after the program runs.

> **JavaScript:**
>
> The example code demonstrates use of a [`try, finally`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement to ensure that the serial port closes after the program runs.
> Closing the port is crucial because an open port prevents Node.js from exiting.

> **Java:**
>
> The example code demonstrates use of a [`try-with-resources`](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) statement to ensure that the serial port closes after the program runs.

> **MATLAB (legacy):**
>
> The example code demonstrates use of a [`try-catch`](https://la.mathworks.com/help/matlab/ref/try.html) statement to ensure that the serial port closes in case of an exception.

> **C++:**
>
> The serial port is closed on object deconstruction.
> No additional `try-catch` or explicit `close()` call is needed.

Continue the Getting Started guide by [homing your device](https://software.zaber.com/motion-library/docs/binary/tutorials/home_device_binary.md).

> **Linux:**
>
> ### Troubleshooting: Permission denied
>
> In some cases you may encounter:
>
> ```text
> Cannot open serial port: open /dev/ttyUSB0: permission denied
> ```
>
> This problem occurs when the current user is not allowed to use serial ports on the computer.
> To resolve this issue open a console and enter the following:
>
> ```bash
> sudo adduser $USER dialout
> ```
>
> Logout and login again and you should have access to the serial ports. If that doesn't work, try rebooting your computer.

> **Linux and Mac OS:**
>
> ### Port Locking
>
> To avoid conflict with other software accessing the serial port, the library locks the port using the `flock` system call.
> If the lock cannot be acquired without blocking, the `open_serial_port` method throws a `ConnectionFailedException` exception.
> The library also puts the port into exclusive mode using the `TIOCEXCL` command of the `ioctl` system call to prevent further attempts to open the port.
> The lock is released and exclusive mode is disabled when the connection is closed.

## API Reference

- [`Connection`](https://software.zaber.com/motion-library/api/py/binary/connection.md)
