below is some code I pasted in. Download the .txt file if you want the code. See the pictures for help witht he serial interface. One shows the 22kohm resistor method of connecting your serial port to a PIC. The other shows the max232 method of connecting your serial port to a PIC.
With serial connections the most common problem is not setting the computer and the PIC to the same Baud Rate, so make sure you do that (as it's done in my code).
Also, make sure you've connected all of the GNDs together (PIC, MAX232, and Computer GNDs all connected).
Also, make sure that you're using the right capacitor value for the max232 (max232 vs. max232A), see diagram in the instructable for the proper values.
Also, make sure that your computer is sending the values you think it is sending. To do this, stick wires into your DB9 cable to make a serial loopback. This will make the computer get back exactly what it has just sent. Here's a diagram of how to wire this up:
http://electrosofts.com/serial/loopback.jpg
So make your matlab code do a serial read right after the serial write.
You can also use free serial port monitoring software to makesure serial communications are occuring properly (here's one example http://www.batchconverter.com/FreeSerialPortMonitor-download-20643.shtml).
Anyway, here's the code:
%##########################################################################
%########################--MATLAB CODE--###################################
%##########################################################################
%This code assumes that you have MATLAB hooked up to a PIC microcontroller via the PC's serial port through a
%MAX232 IC _OR_ if you don't use a max232 all you need is a 22 kohm limiting resistor on
%the serial line which connects the computer to the PIC (aka Pin 3 and/or Pin 2, see below).
%Pin 3 or the DB-9 port is the TX line, aka the line that carries serial data from the PC to the PIC.
%Pin 2 carries serial data the other way (PIC to PC) if you want to do that.
%Pin 5 is the DB-9 ground pin which you should use to connect the PC ground with the PIC ground.
%This code also assumes that you're using COM3 for serial communication with the PIC.
SerPIC = serial('COM3'); %<--change this appropriately
set(SerPIC,'BaudRate', 9600, 'DataBits', 8, 'Parity', 'none','StopBits', 1, 'FlowControl', 'none');
fopen(SerPIC); %--open the serial port to the PIC
fprintf(SerPIC, '%s', '003'); %--send a _three_ digit string to the PIC with no terminator ('%s')
%-- 003 = 00000011 in binary, so first two LEDs of PIC will light
fclose(SerPIC) %--close the serial port when done
delete(SerPIC)
clear SerPIC
%NOTE 1:
%if MATLAB ever gives a serial error, it will most likely say 'unable to open serial port' next time you
%run the program, so you have to restart MATLAB
%NOTE 2:
%the number must always be sent as a three digit number because for some reason I couldn't get my PIC to receive
%the number when it wasn't of a specified length (see PIC code: DEC3)
%
%
'##########################################################################
'#############################--PIC16F877 CODE--###########################
'##########################################################################
'This code assumes you have the PIC16F877 set up with one LED on each line of Port D (8 lines).
'This way the PIC will light up a different pattern of LEDs according to the number send via serial from MATLAB.
'Each LED should be in series with a 470 ohm resistor (see pic below)
'_
' '
' '------LED--- 470 ohm
'PIC' >------///------GND
' '------LED---/
'---'
'
'This code also assumes that you have the TX line of the DB-9 serial port connected to pin 0 of port C (PORTC.0)
Include 'bs2defs.bas' 'has some useful stuff in it
'DEFINE OSC 4 'Oscillator speed in MHz, this isn't needed I guess
SerI var PORTC.0 'make an easy name to refer to the serial pin
TRISD = %00000000 'set PortD as an output port
PortD = %00000000 'set LED port to all zeros
GetGhost:
Serin2 SerI, 84, (DEC3 B0) 'get a three digit number from serial pin and put it into B0 variabl
PortD = B0 'set the lines of PortD according to this three digit number
GOTO GetGhost
'
'
With serial connections the most common problem is not setting the computer and the PIC to the same Baud Rate, so make sure you do that (as it's done in my code).
Also, make sure you've connected all of the GNDs together (PIC, MAX232, and Computer GNDs all connected).
Also, make sure that you're using the right capacitor value for the max232 (max232 vs. max232A), see diagram in the instructable for the proper values.
Also, make sure that your computer is sending the values you think it is sending. To do this, stick wires into your DB9 cable to make a serial loopback. This will make the computer get back exactly what it has just sent. Here's a diagram of how to wire this up:
http://electrosofts.com/serial/loopback.jpg
So make your matlab code do a serial read right after the serial write.
You can also use free serial port monitoring software to makesure serial communications are occuring properly (here's one example http://www.batchconverter.com/FreeSerialPortMonitor-download-20643.shtml).
Anyway, here's the code:
%##########################################################################
%########################--MATLAB CODE--###################################
%##########################################################################
%This code assumes that you have MATLAB hooked up to a PIC microcontroller via the PC's serial port through a
%MAX232 IC _OR_ if you don't use a max232 all you need is a 22 kohm limiting resistor on
%the serial line which connects the computer to the PIC (aka Pin 3 and/or Pin 2, see below).
%Pin 3 or the DB-9 port is the TX line, aka the line that carries serial data from the PC to the PIC.
%Pin 2 carries serial data the other way (PIC to PC) if you want to do that.
%Pin 5 is the DB-9 ground pin which you should use to connect the PC ground with the PIC ground.
%This code also assumes that you're using COM3 for serial communication with the PIC.
SerPIC = serial('COM3'); %<--change this appropriately
set(SerPIC,'BaudRate', 9600, 'DataBits', 8, 'Parity', 'none','StopBits', 1, 'FlowControl', 'none');
fopen(SerPIC); %--open the serial port to the PIC
fprintf(SerPIC, '%s', '003'); %--send a _three_ digit string to the PIC with no terminator ('%s')
%-- 003 = 00000011 in binary, so first two LEDs of PIC will light
fclose(SerPIC) %--close the serial port when done
delete(SerPIC)
clear SerPIC
%NOTE 1:
%if MATLAB ever gives a serial error, it will most likely say 'unable to open serial port' next time you
%run the program, so you have to restart MATLAB
%NOTE 2:
%the number must always be sent as a three digit number because for some reason I couldn't get my PIC to receive
%the number when it wasn't of a specified length (see PIC code: DEC3)
%
%
'##########################################################################
'#############################--PIC16F877 CODE--###########################
'##########################################################################
'This code assumes you have the PIC16F877 set up with one LED on each line of Port D (8 lines).
'This way the PIC will light up a different pattern of LEDs according to the number send via serial from MATLAB.
'Each LED should be in series with a 470 ohm resistor (see pic below)
'_
' '
' '------LED--- 470 ohm
'PIC' >------///------GND
' '------LED---/
'---'
'
'This code also assumes that you have the TX line of the DB-9 serial port connected to pin 0 of port C (PORTC.0)
Include 'bs2defs.bas' 'has some useful stuff in it
'DEFINE OSC 4 'Oscillator speed in MHz, this isn't needed I guess
SerI var PORTC.0 'make an easy name to refer to the serial pin
TRISD = %00000000 'set PortD as an output port
PortD = %00000000 'set LED port to all zeros
GetGhost:
Serin2 SerI, 84, (DEC3 B0) 'get a three digit number from serial pin and put it into B0 variabl
PortD = B0 'set the lines of PortD according to this three digit number
GOTO GetGhost
'
'
'port'
— Serial port name
character vector | string
Serial port name, specified as a character vector or string. The
seriallist
function provides a list of available serial ports. You must specify the port to create a serial port object.The port name depends on the platform that the serial port is on. This list is an example of serial constructors on different platforms:
Platform | Serial Port Constructor |
---|---|
Linux® 64 | s = serial('/dev/ttyS0') |
macOS 64 | s = serial('/dev/tty.KeySerial1') |
Windows® 64 | s = serial('COM1') |
MATLAB and Simulink support communication with any instrument that has a serial interface through Instrument Control Toolbox. The toolbox provides the tools that let you communicate with, configure, and transfer data with your serial device without writing code. MATLAB to PIC Serial Interface: some code to let MATLAB talk to a PIC16f877 via the serial port. This isn't that hard nor is it much code, but I spent a decent amount of time figuring it all out (starting from scratch), so I figured it would be helpful. Serial port name, specified as a character vector or string. The seriallist function provides a list of available serial ports. You must specify the port to create a serial port object. The port name depends on the platform that the serial port is on.
Example:
s = serial('COM1')
- MATLAB and Simulink support communication with any instrument that has a serial interface through Instrument Control Toolbox. The toolbox provides the tools that let you communicate with, configure, and transfer data with your serial device without writing code.
- Mar 29, 2006 MATLAB to PIC Serial Interface: some code to let MATLAB talk to a PIC16f877 via the serial port. This isn't that hard nor is it much code, but I spent a decent amount of time figuring it all out (starting from scratch), so I figured it would be helpful.
Name-Value Pair Arguments
Specify optional comma-separated pairs of
Example: Name,Value
arguments. Name
is the argument name and Value
is the corresponding value. Name
must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,..,NameN,ValueN
.s = serial('COM2','BaudRate',1200,'DataBits',7);
For a list of serial port object properties that you can use with
serial
, refer to Property Reference.Note
Port must be the first argument used to create the serial object. You can then follow port with any number of supported name-value pairs.
'BaudRate'
— Rate at which bits are transmitted
9600 (default) | double
Rate at which bits are transmitted, specified as the comma-separated pair consisting of
'BaudRate'
and a double. You configure baud rate as bits per second. The transferred bits include the start bit, the data bits, the parity bit (if used), and the stop bits. However, only the data bits are stored.The baud rate is the rate at which information is transferred in a communication channel. In the serial port context, 9600 baud means that the serial port is capable of transferring a maximum of 9600 bits per second. If the information unit is one baud (one bit), the bit rate and the baud rate are identical. If one baud is given as 10 bits, (for example, eight data bits plus two framing bits), the bit rate is still 9600 but the baud rate is 9600/10, or 960. You always configure
BaudRate
as bits per second.Note
Both the computer and the peripheral device must be configured to the same baud rate before you can successfully read or write data.
Standard baud rates include 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200, 128000, and 256000 bits per second.
You can also set the
BaudRate
property after creating the serial object using this syntax:Example:
s = serial('COM1','BaudRate',4800);
Data Types:
double
'ByteOrder'
— Byte order of the device
littleEndian (default) | bigEndian
Byte order of the device, specified as the comma-separated pair consisting of
'ByteOrder'
and littleEndian
or bigEndian
. If ByteOrder
is littleEndian
, the device stores the first byte in the first memory address. If ByteOrder
is bigEndian
, the device stores the last byte in the first memory address.For example, suppose the hexadecimal value 4F52 is to be stored in device memory. Because this value consists of two bytes, 4F and 52, two memory locations are used. Using big-endian format, 4F is stored first in the lower storage address. Using little-endian format, 52 is stored first in the lower storage address.
The byte order of
littleEndian
is the default and is used in read and write operations if you do not specify the property. You need to specify the property only to change the byte order to bigEndian
.You can also set the
ByteOrder
property after creating the serial object using this syntax:Note
Configure
ByteOrder
to the appropriate value for your device before performing a read or write operation. Refer to your device documentation for information about the order in which it stores bytes.Example:
s = serial('COM1','ByteOrder','bigEndian');
Data Types:
char
| string
'DataBits'
— Number of data bits to transmit
8 (default) | 5 | 6 | 7
Matlab Serial Example
Number of data bits to transmit, specified as the comma-separated pair consisting of
'DataBits'
and 5
, 6
, 7
, or 8
, which is the default. Data is transmitted as a series of five, six, seven, or eight bits with the least significant bit sent first. At least seven data bits are required to transmit ASCII characters. Eight bits are required to transmit binary data. Five-bit and six-bit data formats are used for specialized communications equipment.Note
Both the computer and the peripheral device must be configured to transmit the same number of data bits.
In addition to the data bits, the serial data format consists of a start bit, one or two stop bits, and possibly a parity bit. You specify the number of stop bits with the
StopBits
property, and the type of parity checking with the Parity
property.You can also set the
DataBits
property after creating the serial object using this syntax:Example:
s = serial('COM1','DataBits',7);
Data Types:
double
'Parity'
— Type of parity checking
none (default) | odd | even | mark | space
Type of parity checking, specified as the comma-separated pair consisting of
'Parity'
and none
, odd
, even
, mark
, or space
.{none} | Default. No parity checking. Parity checking is not performed and the parity bit is not transmitted. |
odd | Odd parity checking. The number of mark bits (1s) in the data is counted, and the parity bit is asserted or unasserted to obtain an odd number of mark bits. |
even | Even parity checking. The number of mark bits in the data is counted, and the parity bit is asserted or unasserted to obtain an even number of mark bits. |
mark | Mark parity checking. The parity bit is asserted. |
space | Space parity checking. The parity bit is unasserted. |
Parity checking can detect errors of one bit only. An error in two bits might cause the data to have a seemingly valid parity, when in fact it is incorrect.
In addition to the parity bit, the serial data format consists of a start bit, between five and eight data bits, and one or two stop bits. You specify the number of data bits with the
DataBits
property, and the number of stop bits with the StopBits
property.You can also set the
Parity
property after creating the serial object using this syntax:Example:
s = serial('COM1','Parity','even');
Data Types:
char
| string
'StopBits'
— Number of bits used to indicate the end of a byte
1 (default) | 1.5 | 2
Number of bits used to indicate the end of a byte, specified as the comma-separated pair consisting of
'StopBits'
and 1
, 1.5
, or 2
. If StopBits
is 1
, one stop bit is used to indicate the end of data transmission. If StopBits
is 2
, two stop bits are used to indicate the end of data transmission. If StopBits
is 1.5
, the stop bit is transferred for 150% of the normal time used to transfer one bit.Note
Both the computer and the peripheral device must be configured to transmit the same number of stop bits.
Summary of the possible values:
{1} | Default. One stop bit is transmitted to indicate the end of a byte. |
1.5 | The stop bit is transferred for 150% of the normal time used to transfer one bit. |
2 | Two stop bits are transmitted to indicate the end of a byte. |
In addition to the stop bits, the serial data format consists of a start bit, between five and eight data bits, and possibly a parity bit. You specify the number of data bits with the
DataBits
property, and the type of parity checking with the Parity
property.You can also set the
StopBits
property after creating the serial object using this syntax:Example:
s = serial('COM1','StopBits',2);
Data Types:
double
Terminator character, specified as the comma-separated pair consisting of
'Terminator'
and a string. You can configure Terminator
to an integer value ranging from 0 to 127, which represents the ASCII code for the character, or you can configure Terminator
to the ASCII character. For example, to configure Terminator
to a carriage return, specify the value to be CR
or 13
. To configure Terminator
to a linefeed, specify the value to be LF
or 10
. You can also set Terminator
to CR/LF
or LF/CR
. If Terminator
is CR/LF
, the terminator is a carriage return followed by a line feed. If Terminator is LF/CR
, the terminator is a linefeed followed by a carriage return. Note that there are no integer equivalents for these two values.Additionally, you can set
Terminator
to a 1-by-2 cell array. The first element of the cell is the read terminator and the second element of the cell array is the write terminator.When performing a write operation using the
fprintf
function, all occurrences of n
are replaced with the Terminator
property value. Note that %sn
is the default format for fprintf
. A read operation with fgetl
, fgets
, or fscanf
completes when the Terminator
value is read. The terminator is ignored for binary operations.You can also use the terminator to generate a bytes-available event when the
BytesAvailableFcnMode
is set to terminator
.You can also set the
Terminator
property after creating the serial object, using this syntax:Example:
s = serial('COM1','Terminator','CR');
Data Types:
char
| string