Writing to a serial port using SerialPorts.jl

Hello Everyone,

I was trying to write to a device (laser) using SerialPorts.jl however there seems to be some error in my code as the device does not respond to my commands.

I was able to wrtie to this device using MATLAB. I have attached an image of both MATLAB and Julia code for your reference.

MATLAB Code:

laser = serial('COM6','BaudRate',9600,'DataBits',8,'Parity','none','FlowControl','none','StopBits',1);
fopen(laser);
fwrite(laser, [126 1 1 1 1]); 
pause(1/2) % set CW mode
fclose(laser);
pause(1/2);

Julia Code:

using SerialPorts

laser_port = "COM6"
laser_baudrate=9600
ser = SerialPort(laser_port, laser_baudrate)

print("The port is available \n")
write(ser, [126 1 1 1 1])

close(ser)

I am a complete beginner in interfacing with serial ports, any help in understanding why passing the command ( [126 1 1 1 1] ) works in MATLAB but doesn’t in Julia.

Any help would be appreciated. Thanks.

Edit: I would also like to mention I am using the RS232 communication protocol to communicate with the laser device.

1 Like

Try sending an actual byte array with write(ser, UInt8[126 1 1 1 1]) instead.

Thanks for the quick response @jebej.
Would you mind explaining, what’s the difference between sending the data as byte array using UInt8 and sending the array as it is?

The actual bytes you are sending differ. With [126 1 1 1 1], you are sending 5 64bit integers, whereas with UInt8[126 1 1 1 1] it’s 5 8bit integers. You can see the difference by “casting” the Int64 array to UInt8:

julia> reinterpret(UInt8, [126, 1, 1, 1, 1])
40-element reinterpret(UInt8, ::Vector{Int64}):
 0x7e
 0x00
    â‹®
 0x00
 0x00

The vector of 5 64bit integers is equivalent to 40 bytes of data.

In Julia, types are more strict than in MATLAB and if you tell the function to write UInt64, it will do just that. MATLAB does this implicit conversion for you which is probably not super ideal, even if it might work in most cases.

Note that I would also recommend using 1D arrays, that is with commas: UInt8[126,1,1,1,1].

3 Likes

Thanks for that comprehensive answer, I was able to understand the difference!