% ======================================================================= % Matlab Data Import and Real Time Plotting % % By Patrick Yukman % Dartmouth College % ======================================================================= %% % The port name will be system dependent. On different systems it might % look like: % % Linux: port = '/dev/ttyS0'; % MacOS: port = '/dev/tty.usbmodemfa141'; % Windows: port = 'COM1'; % % But it will need to be correctly configured before you can receive any % data! clear all; port = 'COM3'; %% % Variables X_SIZE = 5000; %% % This code serves to open the serial port for communication between the % Arduino and the computer. in = serial(port); set(in, 'BaudRate', 115200); set(in, 'Parity', 'none'); set(in, 'DataBits', 8); set(in, 'StopBits', 1); set(in, 'InputBufferSize', 1000); fopen(in); %% % This code will open and set up an external file to which the data will % be separately written. date = datestr(now); dateString = strrep(date, ' ', '_'); dateString = strrep(dateString, ':', ''); dataTitle = ['DataInput_' dateString '.txt']; dataFile = fopen(dataTitle,'w'); disp(['Data being written to ' dataTitle]); %% % Now we will set up the figure window. voltages = zeros(1,X_SIZE); xSpacing = linspace(1,X_SIZE,X_SIZE); dataLine = plot(xSpacing,voltages); ylim([0 1023]); %% % Now we read data in through the serial port. tline = 1; count = 1; while (tline ~= -1) % Read a line from the serial port, write it to a file, and plug it % into the voltages vector. tline = fgets(in); fprintf(dataFile,tline); num = str2num(tline); voltages(count) = num; % Increment count all the way to X_SIZE, then start at the beginning % again. This lets us keep writing over the elements of voltages, so % the script doesn't get bogged down with memory allocation and % massive vector structures. if count <= (X_SIZE - 1) count = count + 1; else count = 1; end % Only redraw once every 25 data points. This allows the plotting to % happen relatively fast. Plotting each data point from the Arduino, % which is running at ~1000 Hz, would slow the script down so much % that the Arduino's data buffer would fill up. if mod(count,25) == 0 set(dataLine,'YData',voltages); drawnow; end end