Fprintf Fprintf ( PHYS352') PHYS352 Fopen Id Fopen ( Datafile - TXT','W') R' W' Fopen Id

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

PHYS 352

Measurement Instrumentation and Experiment Design


General Instrumentation Experiment No. 1

Serial Port Communication using MATLAB

Introduction:

Most modern instruments such as oscilloscopes, spectrum analyzers, function generators, and even
some power supplies support communication with a computer through a parallel port or a serial
port. This communication provides an easy and accurate way to control an experiment and collect
and process data. The objective of this experiment is to write a MATLAB m-file to collect a
digitized waveform from a digital oscilloscope. You will be using this m-file in subsequent
experiments.

Many different interface standards have been proposed to allow scientific instrument and computer
developers to design systems that can communicate with each other. One of the most common
serial port standards is the RS-232 interface standard. Personal computers usually have two 9-pin
communication ports labeled COM1 and COM2, both of which are designed based on the RS-232
standard. This standard defines the mechanical connectors and pin assignments, as well as the
electrical characteristics of the port. Connecting a computer to a scientific instrument that supports
RS-232 communication is as simple as attaching an appropriate cable to either the COM1 orCOM2
port of the computer and attaching the other end to the serial port of the instrument.

What is Serial Communication?

Serial communication is the simplest way to communicate between two devices. As the name
suggests, information is sent in a serial fashion, one bit at a time. The transmission begins with a
start bit (logic 0) and is followed by the string of data bits, starting with the least significant bit and
ending with the most significant bit. The number of bits transferred per second is given by the baud
rate. The default baud rate for the serial port on the oscilloscope we will be using is 9600 bits/sec.
This is very slow compared to hundreds of Mbytes/sec. that are possible using a parallel port and
dedicated data acquisition hardware. However, the ease of use and low cost of serial
communication makes it popular for applications where the data transfer rate is not critical.

Getting Started:

Sending a command or data through a serial port is very similar to writing data to a file. Since you
may not be familiar with file I/O using MATLAB, we will discuss this first first before tackling the
problem of serial port communication. Writing data in MATLAB is accomplished using the fprintf()
statement. Try typing fprintf(‘PHYS352’). When you press ‘Enter’, the test string PHYS352 should
appear on your screen. To direct this output to a file instead of the computer screen you need to
first open a file. This is done using the fopen() statement. For example, id=fopen(‘datafile.txt’,’w’);
will open a file called ‘datafile.txt’ that can be used for writing data (use ‘r’ in place of ‘w’ of you
want to read from the file). When the fopen() statement is executed, MATLAB returns a file
identifier. In this example, the value of the file identifier is captured by the variable id. By

PHYS352_2009, Lab #1 Pg. 1 of 5 Lab:- Prof. G. Lockwood


including the file identifier in the fprintf() statement, data is written to the file instead of the screen.
Type the statement fprintf(id,’PHYS352’); To see if the operation is successful you can examine the
contents of the file datafile.txt. However, before you can do this, you will need to close the file.
This is done by using fclose(id) statement. Close the file and check that the text string was stored in
the file successfully.
(For example, enter the command type datafile.txt )

Data can be read from the file using the fscanf() command. Reopen the file, this time using ‘r’ in
place of ‘w’ to indicate that you want to read from the file. Enter data=fscanf(id,’%s’) and press
return. The argument ‘%s’ is a conversion character that indicates that we want to read a string of
characters. (Examples of other conversion characters are %d for decimal, %f for fixed point, and
%e for exponential notation.) The variable data should now hold the character string ‘PHYS352’.

Very similar operations are performed when you want to communicate with an instrument using the
serial port.

MATLAB Code for Serial Port Communication:

Before you can send or receive information using a serial port, you must first identify what port will
be used (COM1 or COM2). This is done by using the serial command. For example,
s=serial(‘COM1’); selects COM1 and returns an identifier which is captured by the variable ‘s’. If
you enter the command without the ‘;’ and press return, the current settings of COM1 should be
displayed. The output for a particular computer is shown below:

s=serial(‘COM1’)

Serial Port Object: Serial-COM1

Communication Settings
Port: COM1
BaudRate: 1200
Terminator: ‘CR’

Communication State
Status closed
RecordStatus: off

Read/Write State
TransferStatus: idle
BytesAvailable: 0
ValuesReceived: 0
ValuesSent: 0

It is obviously important that the serial port on the computer and the oscilloscope are configured in
exactly the same manner. You can change the serial port settings using ‘s. commands’. (Note: ‘s’
is the serial port identifier assigned when the serial command was executed.) For example, on a
particular computer: s,BaudRate = 9600; changed the Baud rate from 1200 to 9600, and
s.Terminator = ‘LF’; changed the line terminator from a ‘carriage return’ to a ‘line feed’. Ensure that

PHYS352_2009, Lab #1 Pg. 2 of 5 Lab:- Prof. G. Lockwood


the Baud rate on the COM1 port of your computer is 9600, and that the terminator is a ‘LF’. To see
a complete list of the COM1 settings, type: get(s)

Although you do not need to be concerned with most of the properties (the default settings are
probably fine), there are two properties of the serial port that you may need to change. One is the
Timeout and the other is the InputBufferSize. The Timeout property tells the computer how long to
wait during the data transfer before deciding that something is wrong and terminating the transfer.
The data files that you will be collecting from the oscilloscope are large, and the default time out
setting may be too short. To fix this problem, enter s.Timeout=20; Similarly, the default input
buffer size may be too small to accept the full data file. Resize the buffer size using:
s.InputBufferSize = 50000;

The serial port on the computer side of the system should now be ready to go. You now need to set
the equivalent properties on the oscilloscope.

Turn on the oscilloscope and follow the menu from UTILITIES to OPTIONS to RS 232 SET UP.
Make sure that the Baud rate, Flow Control, EOL String, and Parity match the settings on the
COM1 port. (The default settings on the ‘scope are probably OK.)

Now that the serial port has been identified and the properties have been defined you can open the
port for communication. The serial port connection to the ‘scope is established by simply typing:
fopen(s); You can now send a simple command to the ‘scope to verify that the connection is open.
A universal serial port command that simple asks the device to identify itself is the string *IDN? To
send the *IDN? Command you simply enter: fprintf(s,’*IDN?’); You can record the reply by
entering: out = fscanf(s) . Try it! The result should be very similar to the following:

out =
TEKTRONIX, TDS 210,0,CF:91. 1CT FV:v1,16 TDS2CM:CMVv1.04

Most other commands are instrument dependent and you will usually need to consult the
programmer’s manual for the instrument to proceed. A typical entry from the TDS 210 ‘scope
manual is shown below:

DATA:STOP

Sets the last data point in the waveform that will be transferred when executing the CURVE? command. This lets you transfer partial
waveforms from the oscilloscope.

When using the CURVE command, the oscilloscope stops reading data when there is no more data to read or when the 2500 data point
limit is reached.

Group
Waveform

Syntax
DATA:STOP <NR1>

Arguments
<NR1> is an integer value that ranges from 1 to 2500, and specifies the last data point that will be transferred. If you want to transfer
complete waveforms, set DATASTART to 1 and DATASTOP to 2500

Example
DATA:STOP 150
Specifies that the waveform transfer will stop at data point 150

PHYS352_2009, Lab #1 Pg. 3 of 5 Lab:- Prof. G. Lockwood


Related Commands
CURVE?, DATASTART

If you looked through the manual for the digital ‘scope you would discover that the following
sequence of commands are required to collect and transfer a waveform. Before you try using the
commands, connect the function generator to the ‘scope and adjust the ‘scope to display a
waveform of your choice.

fprintf(s,'DATA:ENCDG ASCII'); %set the data format to ASCII


fprintf(s,'DATA:SOURCE CH1'); %set the 'scope channel to CH1
fprintf(s,'DATA:WIDTH 1'); %set the no. of bytes per data point to 1 byte (8 bits)
fprintf(s,'DATA:START 1'); %start at point #1
fprintf(s,'DATA:STOP 25'); %transfer just 25 points from the 2500 points
fprintf(s,'CURVE?'); %transfer the oscilloscope waveform data in ASCII format

Next you need to read the data, which should be in the COM1 input buffer.

data=fscanf(s); %read the data into MATLAB

Have a look at the data. You should see a character string consisting of a header followed by 25
data points. Before you can do anything with the data you need to remove the header. In this
example, the first 5 characters in the string correspond to the header. The total length of the string
can be found using the command: a=size(data), and the header can be removed by forming a new
data array: newdata=data(6:a(2)); Finally, to convert the character string to an array of numbers,
use the strread command: values = strread(newdata,’%d’,’delimiter’,’,’); (You can look it up using
the MATLAB help if you want to figure out what the arguments do.)

If all has gone well, a plot of values should produce a graph that has the same shape as the first 25
points of the oscilloscope trace. (Note: you are plotting just the first 25 points of a 2500 point
waveform, so the waveform may look ragged.) Unfortunately, the axis of the graph will be
incorrect. The problem is that the oscilloscope has transferred the raw 8-bit data samples. To turn
the raw data into numbers corresponding to the voltage of the signal, you need to ask the ‘scope to
send the scaling information (yoff, ymult and yzero). Once this information is obtained, the correct
voltage for the signal can be recovered using the expression:
voltage = (values-yoff)*ymult + yzero;
similarly, the time scale may be obtained using the expression: time = xzero + xincr*(1:1:25);

The ymult parameter is obtained using the following code:

fprintf(s,'WFMPRE:CH1:YMULT?') %ask 'scope for the ymult info


instring = fscanf(s); %read the reply
a = size(instring); %obtain size of string (# of rows, and # of columns)
newstring = instring(14:a(2)); %remove the header; note:- a(2) gives # of cols. in ‘instring’
ymult = strread(newstring, '%f'); %convert to numeric value

You will have to write similar code (cut & paste) to obtain values for yoff, yzero, xincr and xzero.

PHYS352_2009, Lab #1 Pg. 4 of 5 Lab:- Prof. G. Lockwood


Once you have successfully collected all the scaling information, plot the waveform using the
correct time and voltage scale. To end the session, the serial port is closed using the fclose(s)
command.

Finally, create an m-file (cut and paste from the Command History window – the shift key will
allow you to collect more than one line) so that you can collect data in future experiments. You will
need to store the m-file temporarily in the local folder – the MATLAB \work folder or your current
folder – in order to run the programme. The data stop length should be increased to 2500 so that the
entire waveform can be collected. It is important that you include the fclose(s) statement at the end
of your m-file, since the port must be closed before you can open it again. If your m-file has an
error and terminates before the serial port is closed, you can try typing the fclose(s) statement in the
main command window. If this doesn’t work, you will have to close and restart MATLAB to reset
the port.

Demonstrate your code to the TA, save your file to a disk, USB drive or your own account, delete
anything you have created in the local directory, and then you can leave.

There is no write up for this lab.

Assignment (PHYS 352, Lab 1 – Serial Port Communication)


(To be done in the lab OR handed in within 1 week of lab completion)

A. How many sampled points are there in the final ‘scope traces captured? _______________

B. Time between samples:- Note down the time obtained from the “xincr” value and also the
time calculated from the total trace time divided by (# of samples – 1).

xincr  __________________

calculation  __________________

C. Calculate the sampling frequency from the times noted in B.

Frequency:-  __________________

 __________________

PHYS352_2009, Lab #1 Pg. 5 of 5 Lab:- Prof. G. Lockwood

You might also like