How to get Arduino received value using Matlab?
5 views (last 30 days)
Show older comments
How to get Arduino received value using Matlab?
I tried to transmit string using Arduino. Now i need to connect to matlab and show the received data using mathlab. How can i do it?
This is my arduino code
#define LED_PIN 3
#define LDR_PIN A2
#define THRESHOLD 100
#define PERIOD 15
bool previous_state;
bool current_state;
void setup()
{
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
current_state = get_ldr();
if(!current_state && previous_state)
{
print_byte(get_byte());
}
previous_state = current_state;
}
bool get_ldr()
{
int voltage = analogRead(LDR_PIN);
return voltage > THRESHOLD ? true : false;
}
char get_byte()
{
char ret = 0;
delay(PERIOD*1.5);
for(int i = 0; i < 8; i++)
{
ret = ret | get_ldr() << i;
delay(PERIOD);
}
return ret;
}
void print_byte(char my_byte)
{
char buff[2];
sprintf(buff, "%c", my_byte);
Serial.print(buff);
}
0 Comments
Answers (1)
Amish
on 25 Mar 2025
Hi Thakshila,
I see that your Arduino code reads an LDR (Light Dependent Resistor) sensor and sends a byte over the serial connection when a transition from high to low is detected. The code also toggles an LED based on the LDR reading.
You can set up MATLAB to read the data being sent from your Arduino. Please refer to the below code snippet:
% Define the serial port and baud rate
port = 'COM3'; % Replace this with your Arduino's COM port
baudRate = 9600;
% Create a serial port object
arduinoObj = serialport(port, baudRate);
% Configure the serial port object
configureTerminator(arduinoObj, "LF"); % Set line terminator to Line Feed
flush(arduinoObj); % Clear any old data
% Read data from Arduino
try
while true
if arduinoObj.NumBytesAvailable > 0
data = readline(arduinoObj); % Read a line of data from Arduino
disp(['Received: ', data]); % Display the received data
end
pause(0.1); % Small delay to prevent overwhelming the serial port
end
catch ME
disp('Error occurred:');
disp(ME.message);
end
% Clean up
clear arduinoObj;
The serialport function is used to create a connection to the Arduino and the readline function reads a line of data from the serial buffer. The received data is then displayed in the MATLAB console. A try-catch block is used to handle any errors.
For more information on the functions used in the above code, refer to the documentation:
Arduino Support Package for MATLAB: https://www.mathworks.com/matlabcentral/fileexchange/47522-matlab-support-package-for-arduino-hardware
Hope this helps!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!