0% found this document useful (0 votes)
16 views

Lab 3

The document describes an experiment using an Arduino and MATLAB for serial communication. The Arduino reads a PWM value from MATLAB to control an LED brightness and a photoresistor value, then sends the data back to MATLAB. The code snippets show how the Arduino and MATLAB are configured for this synchronized serial communication experiment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Lab 3

The document describes an experiment using an Arduino and MATLAB for serial communication. The Arduino reads a PWM value from MATLAB to control an LED brightness and a photoresistor value, then sends the data back to MATLAB. The code snippets show how the Arduino and MATLAB are configured for this synchronized serial communication experiment.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

DALHOUSIE UNIVERSITY - DEPARTMENT OF MECHANICAL

ENGINEERING
MECH 3905 – INTRODUCTION TO MECHATRONICS
LAB #3: SERIAL I/O

Date: 8th February 2024

Debaprashad Bhowmik (B00907766)

Ahmad Usman (B00963449)


ARDUINO CODE

/*
Project Title: Arduino-MATLAB Serial Communication
Author: Debaprashad Bhowmik (B00907766)
Date: February 08, 2024

Description:
This sketch is designed for an Arduino to communicate with MATLAB via
serial communication. It reads a PWM value sent from MATLAB, applies this
value to control the brightness of an LED connected to pin D6, and reads the
intensity of light using a photoresistor connected to analog pin A0. The
Arduino then sends the photoresistor's reading back to MATLAB along with a
counter value to ensure synchronized communication. This setup can be used
for experiments requiring real-time data exchange between MATLAB and Arduino,
such as closed-loop control systems or data logging applications.

Components:
- Arduino board
- LED connected to digital pin D6
- Photoresistor connected to analog pin A0
- Resistor for the LED (if necessary, depending on LED specifications)
- Serial connection between Arduino and MATLAB

Features:
- High-speed serial communication at 115200 bits per second.
- Reading of PWM values sent by MATLAB to control an LED.
- Reading of light intensity using a photoresistor.
- Synchronization mechanism using a counter variable.

Setup:
- Ensure the LED is correctly connected to pin D6 with appropriate current-
limiting resistance.
- Connect the photoresistor to analog pin A0 in a voltage divider
configuration.
- Set the same baud rate in MATLAB's serial communication setup to match
the Arduino sketch.
*/

// Variable to store data received from MATLAB


int data_from_MATLAB;
// Counter variable for synchronized communication
int i = 1;
// Pin assignment for LED control
const byte LED = 6;
// Pin assignment for reading from photoresistor
const byte photoresistor = A0;

void setup() {
// Initialize serial communication with MATLAB
Serial.begin(115200);
delay(500); // Short delay to ensure serial communication stability

// Configure pins
pinMode(photoresistor, INPUT); // Set photoresistor pin as input
pinMode(LED, OUTPUT); // Set LED pin as output
}

void loop() {
int photoresistor_value; // Variable to store photoresistor reading
int pwm_value; // Variable to store PWM value received from MATLAB

// Check if there's data available to read from MATLAB


if (Serial.available() > 2) {
// Read the first valid integer (PWM value) from the incoming serial
stream
pwm_value = Serial.parseInt();

// Read the current value from the photoresistor


photoresistor_value = analogRead(photoresistor);
// Apply the received PWM value to the LED
analogWrite(LED, pwm_value);

// Send counter and photoresistor reading back to MATLAB


Serial.print(String(i) + "," + String(photoresistor_value));
Serial.write(13); // Carriage Return (CR)
Serial.write(10); // Linefeed (LF)
Serial.flush(); // Ensure data is sent before proceeding

i++; // Increment counter to track communication synchronization


}
}
MATLAB CODE

% MATLAB Code for Arduino Communication via USB


% Author: Debaprashad Bhowmik (B00907766)
% Date: February 08, 2024
%
% Description:
% This MATLAB script establishes serial communication with an Arduino UNO to perform
synchronized
% input/output operations. It sends PWM values to the Arduino, which controls the
brightness of an LED.
% The Arduino reads a photoresistor's value and sends it back to MATLAB, along with a
counter value to
% ensure synchronized communication. This script is useful for experiments involving
real-time data
% exchange between MATLAB and an Arduino, such as sensor data collection or control
systems.
%
% Usage:
% Before running this script, upload the "Arduino_basic_communication.ino" sketch to
the Arduino UNO.
% Ensure the Arduino serial port (COM port) and baud rate match those specified in
this script.
% Adjust 'COM7' and '115200' below to match your Arduino configuration.
%
% Components Required:
% - Arduino UNO
% - LED connected to a specified pin on the Arduino
% - Photoresistor connected to the Arduino
% - Proper circuit setup for LED and photoresistor on the Arduino

clear all; close all;

% Initialize serial port communication with Arduino UNO. Replace "COM7" with your
Arduino's COM port.
arduinoObj = serialport("COM7", 115200); % Resets Arduino and counter

pause(2); % Critical pause for MATLAB to establish serial port communication

% Configure terminator for serial communication to recognize end of line


configureTerminator(arduinoObj, "CR/LF");

% Flush any existing data from the serial buffer


flush(arduinoObj);

% Define the number of iterations for communication events


num_iter = 1500;

% Pre-allocate arrays for storing data to enhance performance


Matlab_pwm_value = zeros(num_iter, 1); % Array to store PWM values sent from MATLAB
Arduino_Counter = zeros(num_iter, 1); % Array to store counter values received from
Arduino
Arduino_Data = zeros(num_iter, 1); % Array to store data received from Arduino
Ts = zeros(num_iter, 1); % Array to store sample times
Time = zeros(num_iter, 1); % Array to store timestamps

start_time = tic; % Start timing for the entire communication session

i = 1; % Initialize counter

% Loop for a fixed duration or until a set number of iterations


while (toc(start_time) <= 16) % 16-second duration for this example
start_iteration = tic; % Time each iteration for sample time estimation

Time(i) = toc(start_time); % Timestamp for current data point

% Generate PWM value using a sinusoidal function to simulate varying brightness


Matlab_pwm_value(i) = 128 + 127 * sin(Time(i));

% Send the PWM value to Arduino


writeline(arduinoObj, int2str(Matlab_pwm_value(i)));

% Wait for Arduino to send data back


while true
if arduinoObj.NumBytesAvailable > 0
break; % Exit loop when data is ready
end
end

% Read and process data received from Arduino


data = readline(arduinoObj);
tmp = split(data, ',');
num = str2double(tmp);
Arduino_Counter(i) = num(1); % First element is the counter
Arduino_Data(i) = num(2); % Second element is the photoresistor data

% Display counters to ensure synchronization


fprintf("%d, %d\n", i, Arduino_Counter(i));

Ts(i) = toc(start_iteration); % Calculate sample time for this iteration


i = i + 1; % Increment counter for next iteration
end

% Cleanup by closing the serial port


clear arduinoObj;

% Display average sample time


fprintf('Mean sample time: %2.1f Hz\n', 1/mean(Ts));
RESULTS

Figure 1: Photoresistor Readings vs Time.

Figure 2: Sample Time vs Time.


Figure 3: LED VOLTAGE reading / Volts vs Time

You might also like