Serial Receive in ASCII

5 次查看(过去 30 天)
Ashal Akhtar
Ashal Akhtar 2023-7-3
回答: Raj 2023-9-6
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 个评论
Ashal Akhtar
Ashal Akhtar 2023-7-5
ok so we can apply scan string but not on the endless string but like last 20 characters or something
Aiswarya
Aiswarya 2023-8-19
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?

请先登录,再进行评论。

回答(1 个)

Raj
Raj 2023-9-6
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!

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by