MATLAB to PIC serial interface using PIC16F877 microcontroller

PIC serial interface

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. Enjoy.
PIC serial interface

Code with comments

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).

Schematic PIC serial interface

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.

Leave a Comment

Your email address will not be published. Required fields are marked *