Lab 3
Lab 3
ENGINEERING
MECH 3905 – INTRODUCTION TO MECHATRONICS
LAB #3: SERIAL I/O
/*
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.
*/
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
% Initialize serial port communication with Arduino UNO. Replace "COM7" with your
Arduino's COM port.
arduinoObj = serialport("COM7", 115200); % Resets Arduino and counter
i = 1; % Initialize counter