Serial Receive in ASCII

2 views (last 30 days)
Ashal Akhtar
Ashal Akhtar on 3 Jul 2023
Answered: Raj on 6 Sep 2023
I am sending and receiving data over serial port the data i am receiving is in ASCII one character after another. i conactenated the characters to get an endless string however I want the last two values from the string which in my case are 42.000 and 2.000
  2 Comments
Ashal Akhtar
Ashal Akhtar on 5 Jul 2023
ok so we can apply scan string but not on the endless string but like last 20 characters or something
Aiswarya
Aiswarya on 19 Aug 2023
Do you want to create an endless string (of 42 and 2)? Or do you simply want to obtain the result as 42 and 2?

Sign in to comment.

Answers (1)

Raj
Raj on 6 Sep 2023
Hi,
I understand you are trying to exchange data and want to fetch just the last 2 characters of it. Follow the steps stated below to resolve the issue
  1. Open the serial port connection using the `serial` function in MATLAB. Assign the specific port to the variable
  2. Use the `fread` function to read the signal from the serial port. You can store the value in the buffer as the length of the data is unknown
  3. Extract the last 2 characters using MATLAB indexing
  4. Use the `fclose` function to close the serial port connection.
As I do not have access to your code, an indicative code is here, adapt it with your code accordingly
s = serialport('COM1'); % Replace 'COM1' with the appropriate port name
fopen(s);
b_Size = 1024; % Specify the buffer size
data = [];
while s.BytesAvailable > 0
data = [data; fread(s, b_Size)];
end
lastTwoChars = char(data(end-1:end)');
fclose(s);
Additionally refer to the documentation of fread and Serial receive for better understanding
I hope this resolves your query!

Products


Release

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!