
Send data to Serial Port in MATLAB

Hello friends! Today we will send data from MATLAB to a serial port. We will begin with one character, then send a line of text entered by the user, and finally look at binary bytes, replies and connection cleanup. These are useful building blocks when a MATLAB calculation needs to communicate with an external instrument or microcontroller.
The original tutorial used MATLAB's older serial object. That code remains useful for understanding historical projects, but modern MATLAB code normally uses serialport. We will explain both interfaces clearly so that you do not mix their connection and writing functions in one program.
Before connecting any actuator, start with a receiving terminal, a suitable loopback arrangement or a device command whose effect you understand. Seeing a message in MATLAB's Command Window confirms what your program attempted; receiving and checking the bytes at the other end establishes what the communication actually delivered.
What We Mean by a Serial Port
On Windows, a serial connection commonly appears as a COM port. It may represent a physical UART through an adapter, a USB device exposing a serial interface, or a virtual connection. The COM number identifies the operating system endpoint, not a particular Arduino pin or electrical voltage.
MATLAB writes bytes to that endpoint. The connected device must use compatible communication settings and a protocol that gives those bytes meaning. Sending the letter a does nothing useful unless the receiver is programmed to recognize it.
Electrical compatibility is a separate requirement. A USB-to-TTL adapter, an RS-232 interface and an RS-485 interface are not interchangeable merely because software calls them serial ports. Match the adapter, signal levels and wiring to the device documentation before troubleshooting MATLAB syntax.
Choose the MATLAB Interface
| Task | serialport workflow | Legacy serial workflow |
|---|---|---|
| Create connection | serialport(port, baudRate) | serial followed by fopen |
| Write bytes | write | fwrite |
| Write terminated text | writeline with configured terminator | fprintf with appropriate formatting and terminator |
| Release connection | Delete or release the connection object | fclose followed by delete |
Use the documentation installed with your MATLAB release to confirm availability and syntax. The MathWorks serialport reference is the starting point for the modern interface. Do not add fopen to a serialport example simply because an older screenshot contains it.
If you maintain an old installation with the legacy serial interface, check its toolbox requirements for that release. A copied command does not establish that a particular API is installed or licensed on your computer.
Identify the Correct Port and Settings
Connect the device, check its port in the operating system, and close any other program using that connection. Arduino Serial Monitor, a terminal application and another MATLAB session can compete for the same port. A port that exists is not necessarily available to your process.
ports = serialportlist("available");
disp(ports);
Choose the intended endpoint explicitly. Do not automatically use the first listed port: ordering can change, and the first device may have an unrelated purpose. In the examples below, replace COM3 with the actual port you identified.
| Property | Example value | What must agree |
|---|---|---|
| BaudRate | 9600 | Transmitter and receiver data rate |
| DataBits | 8 | Number of data bits in each character |
| Parity | none | Parity convention |
| StopBits | 1 | Frame ending |
| FlowControl | none | Whether additional handshake behavior is required |
| Timeout | 2 seconds | How long an operation may wait |
The shorthand 8-N-1 means eight data bits, no parity and one stop bit. The receiver's documentation takes priority over these demonstration values. Changing MATLAB to 115200 while leaving the device at 9600 does not increase the connection's useful speed.
Send One Character with serialport
Save the following function as sendOneCharacter.m. It sends the ASCII byte for lowercase a without a line ending. The cleanup object releases the serial connection when the function ends, including when a later statement raises an error.
function sendOneCharacter(portName)
s = serialport(portName, 9600);
connectionCleanup = onCleanup(@() delete(s));
s.DataBits = 8;
s.Parity = "none";
s.StopBits = 1;
s.FlowControl = "none";
s.Timeout = 2;
write(s, uint8(97), "uint8");
disp("Wrote one byte: ASCII a (97).");
end
sendOneCharacter("COM3");
The variable connectionCleanup is deliberately kept alive until the function returns. Do not clear it immediately after creating it, because that would close the connection before the write. This example gives one function ownership of the port and one clear end to its lifetime.
The message says that a byte was written. It does not claim that a remote mechanism moved, an instrument accepted a command, or a measurement completed. Those conclusions require a defined response from the device.
The preserved screenshot shows the historical version of the project. The modern function above uses a different API, so the screenshot should help you recognize the learning sequence rather than serve as an exact transcription of the revised code.
Understand Text, Numbers and Raw Bytes
Serial links carry bytes. Software decides whether those bytes represent text, integers, floating-point values or a custom packet. A receiver expecting one format cannot generally interpret another without an explicit conversion rule.
| Intended representation | Bytes or value | Typical use |
|---|---|---|
| ASCII text 123 | 49, 50, 51 | Human-readable commands and logs |
| One unsigned byte | 123 | Compact values from 0 to 255 |
| Line of text 123 with LF | 49, 50, 51, 10 | A line-oriented command parser |
For example, write(s, uint8([49 50 51]), "uint8") sends three bytes. By comparison, write(s, uint8(123), "uint8") sends one byte. Printing 123 in the Command Window hides this distinction, so inspect actual byte values when debugging a protocol.
For multi-byte numerical types, specify width, signedness and byte order at both ends. A 16-bit integer is not automatically compatible with two decimal digits, and little-endian and big-endian receivers interpret byte pairs differently.
Send a Complete Line of Text
Many instruments accept commands terminated by LF, CR or CR/LF. The terminator tells the receiver where one command ends. It is part of the protocol, not a formatting preference chosen only for a nicer display.
The writeline reference describes writing text with the configured terminator. In this example we select LF and send a harmless demonstration line; replace it with a documented command only when working with a real device.
function sendTextLine(portName, textToSend)
s = serialport(portName, 9600);
connectionCleanup = onCleanup(@() delete(s));
s.DataBits = 8;
s.Parity = "none";
s.StopBits = 1;
s.FlowControl = "none";
s.Timeout = 2;
configureTerminator(s, "LF");
writeline(s, textToSend);
fprintf('Sent text: %s\n', textToSend);
end
sendTextLine("COM3", "TEP serial test");
Do not append another LF to the string when writeline already appends the terminator you selected. Two endings may create an empty command at the receiver. Conversely, write sends the bytes you specify without automatically turning them into a terminated command line.
Send Text Entered by the User
The original tutorial progressed from a fixed character to user-entered data. We can preserve that useful step while keeping input interpretation straightforward. The s option in input returns text instead of evaluating what the user types as a MATLAB expression.
portName = "COM3"; % Replace with the intended port.
data = input('Enter a line to send: ', 's');
if isempty(data)
disp('No text entered; nothing sent.');
else
sendTextLine(portName, data);
end
Keep the device's command grammar in mind. If it accepts SET,25, arbitrary prose is not a substitute. Validate any permitted value range before writing the command, and make the confirmation describe the command actually sent.
In the original example, the blog address was sent as demonstration text. That does not cause the serial device to open a website. It simply supplies a recognizable sequence of characters that another terminal or programmed receiver can display.
Check Delivery with a Defined Reply
A useful next exercise is a receiver that returns ACK when it accepts a line. After writing, read the reply using the terminator expected by that protocol. Use a bounded timeout so that a disconnected device does not leave your application waiting indefinitely.
% Use within a function that already owns and cleans up s.
configureTerminator(s, "LF");
writeline(s, "PING");
reply = strtrim(readline(s));
if reply == "ACK"
disp("Receiver acknowledged the request.");
else
error("Unexpected reply: %s", reply);
end
This is a protocol example, not a universal instrument command. It works only when the receiver implements PING and ACK. A device that streams sensor data continuously needs a different method for associating an incoming line with a particular request.
For repeated commands, include sequence numbers if the protocol supports them. Otherwise a delayed reply to the previous command can be mistaken for success of the current command. Clearing buffers blindly is also risky because it can discard an important device message.
How Fast Can We Send Data?
For ordinary 8-N-1 UART framing, each byte takes one start bit, eight data bits and one stop bit, or ten bits on the wire. At 9600 baud, the ideal payload ceiling is 9600 / 10 = 960 bytes per second before considering pauses or application overhead.
A 25-byte command therefore needs at least 25 × 10 / 9600 = 0.0260 seconds, approximately 26 ms, for UART transmission. Add any line-ending bytes to the count. USB buffering, receiver processing and replies introduce additional delays.
An unbounded MATLAB loop can generate commands faster than the receiver consumes them. Queued data can make a control interface appear responsive while the physical device is still executing old instructions. Define a command rate, wait for suitable acknowledgments, and limit queued work.
Opening some development boards' serial ports can reset their microcontroller. If the intended device behaves this way, account for its startup procedure before sending the first command. A documented ready message is preferable to assuming one fixed delay works for every board and sketch.
Maintain an Older serial-Based Project
The historical interface creates an object and opens it separately. The following function illustrates that workflow for a MATLAB installation that supports it. Notice the correct property name StopBits and the explicit binary write for one byte.
function sendLegacyCharacter(portName)
tep = serial(portName, 'BaudRate', 9600);
connectionCleanup = onCleanup(@() delete(tep));
set(tep, 'Parity', 'none', 'DataBits', 8, ...
'StopBits', 1, 'FlowControl', 'none', 'Timeout', 2);
fopen(tep);
fwrite(tep, uint8(97), 'uint8');
fclose(tep);
end
For legacy formatted text, use an explicit format such as fprintf(tep, '%s', data), together with the terminator behavior your device requires. Passing arbitrary user text as the format string can give percent characters special meaning.
Do not assume that fprintf sends exactly the same byte sequence as fwrite. Formatting, number conversion and terminators can change the output. Choose the function from the desired protocol representation, then inspect what the receiver sees.
Release the Connection Without Restarting the Computer
The original post suggested that leaving a port open could require restarting the computer. Usually the appropriate fix is to release the connection in the application that owns it. Closing a relevant terminal, deleting the intended MATLAB object or stopping its callback can be sufficient.
Avoid broad cleanup commands that delete unrelated instrument objects or clear an entire analysis workspace. The function examples keep ownership local, so cleanup affects the connection created for that operation. In a GUI or continuous acquisition program, keep the connection alive for the required session and release it when that session closes.
If the endpoint disappears because a USB device is unplugged, handle that as a connection failure. A previously selected COM name may later refer to a different device. Re-identify the intended target before retrying an action with external effects.
Design a Small Protocol Before Sending Larger Messages
Once one-character transmission works, decide how the receiver will find the beginning and end of each message. A stream of bytes does not preserve the boundaries of individual MATLAB write calls. One call may be delivered in several pieces, and several calls may be available together when the receiver next reads.
For a text example, define a line such as SET,42,125 followed by LF. SET is the operation, 42 is a sequence number and 125 is a proposed value. The receiver should collect a complete line, check the field count, parse numbers strictly, validate the permitted range and then decide whether to accept the command.
A matching response might be ACK,42 or ERR,42,RANGE. Including the sequence number lets MATLAB associate the response with the request. These strings are a proposed teaching protocol; they are not built-in commands supported by arbitrary instruments.
Keep reception bounded
Set a maximum accepted line length at the receiving end. If the terminator never arrives, an unlimited string buffer can keep growing. A practical parser discards or reports an overlong frame and then searches for a clean boundary before accepting another command.
Also define what happens when only part of a command arrives. A timeout should abandon the incomplete frame or mark the connection unhealthy according to the application. It should not execute a partially parsed number just because some digits were received.
Be careful when retrying commands
A timeout does not prove that the receiver did nothing. It may have completed the operation while the acknowledgment was lost. Retrying a command such as increment counter could perform the action twice.
A command that sets an explicit target, such as set value to 125, is easier to retry safely than a command that adds 125. For operations that must occur once, use sequence tracking and a receiver response that identifies an already processed request. The communication design must match the effect of the command.
Choose text or binary deliberately
Text is convenient during development because a terminal can display it directly. Binary encoding reduces the number of transmitted bytes, but requires precise agreement about field widths, byte order and packet boundaries.
For example, a positive value written as five ASCII digits occupies five bytes. A 16-bit unsigned representation occupies two bytes, provided the value is within its range. However, a usable binary packet also needs framing and usually identification or integrity fields, so the payload saving is not the complete bandwidth calculation.
For either format, retain a small diagnostic record containing timestamps, request identifiers and results. Logging every raw byte indefinitely can itself become a performance problem, so choose a useful retention policy. A short record of the last failed exchange is often more informative than thousands of repeated success messages.
Troubleshooting and Final Review
| Symptom | Likely area to investigate |
|---|---|
| Cannot open the port | Incorrect endpoint, another program, driver or disconnected hardware |
| Garbled text | Baud rate, framing, signal levels or wiring |
| Receiver waits forever | Missing or incorrect command terminator |
| First command is ignored | Device reset or startup delay after opening |
| Text arrives but command fails | Command grammar, expected case, range or device state |
| Old commands continue executing | Producer faster than receiver and accumulated buffering |
Start with one identifiable byte, then one complete line, then a request and reply. Record the actual port, settings, sent bytes and received bytes. This makes a failure reproducible instead of relying on the appearance of a Command Window message.
The revised examples have not been executed against your instrument. Treat device-specific delays, supported commands and acknowledgments as configuration work for that instrument, while retaining the clear ownership and cleanup structure shown here.
Frequently Asked Questions
Should I use COM1 because the original code does?
No. Select the endpoint assigned to your actual device. COM1 is only the historical example name.
Why does a receiver show 97 instead of a?
It may be displaying the byte as a decimal number. ASCII lowercase a has the numeric value 97; representation and received byte value are separate questions.
Can I send a MATLAB array?
Yes, but define its element type, order, length and framing. The receiver must know where the array ends and how to decode each element.
Does writing successfully prove the device acted?
No. Use a documented acknowledgment or status response to establish that the remote application accepted or completed the requested action.
Should I reopen the port for every command?
Usually a continuing session should reuse its connection. Repeated opening adds overhead and can reset some devices. The short functions here demonstrate complete ownership for isolated exercises.
how to receive data via serial port using matlab thnx,
1 reply
That's gonna be the title of my next tutorial. :) I will post about it soon.
2 replies
hi
i tried to search for your next tutorial as you said about reading from serial port
but i did not find anything
could you pleas provide me the link
big thanks
Hi, I tried to find your tutorial about how to receive data via serial port using matlab, and i can't find.
I'm doing a project where i'm sending over bluetooth continious data and i want recieve in matlab. My module bluetooth have a baudrate 115200, but in matlab the data rate is too slow.
This is a great tutorial.
You have send the characters in this program but, if we need to send image file then ?
can you please give me the code for that.....Please.
1 reply
I have designed such project as well, in which I have sent image file over Serial port. Add me on Skype and we will discuss it in detail.
Thanks.
can you give me your skype id
mine email id is mahantesh.kamat@gmail.com
hello there, can i ask some tutorial for serial communication in matlab, with simulink box, thank you
Hello there, do I need to connect with any device to run this project

























Comments
11