Serial communication with Matlab

From Mech
Revision as of 22:43, 4 February 2008 by ScottMcLeod (Talk | contribs)
Jump to: navigation, search

Contents

Original Assignment

Matlab has a "serial" function that allows it to communicate through a serial port. This project is to establish serial port connection with the PIC and demonstrate bidirectional communication between the PIC and a Matlab program, using, for example, a USB to RS232 adapter and level shifter chip. The Matlab program could simply log data from the PIC (e.g., the angle of a potentiometer knob), or plot it on a user interface in real time. Keystrokes from the user of the Matlab program should be obviously received by the PIC, perhaps by lighting the LEDs on the PIC board.

Overview

Circuit

Code

/*
   SerialComm.c Scott McLeod, Sandeep Prabhu, Brett Pihl 2/4/2008
   This program is designed to communicate to a computer using RS232 (Serial) Communication.
   
   The main loop of this program waits for a data transmission over the Serial port, and
   responds with a current reading of an analog input (potentiometer) and the last received data.
  
   Note the analog input is only for testing purposes, and is not necessary for serial communication.
   Lines unnecessary for RS232 communication are commented with enclosing asterisks ('*..*').
 */
#include <18f4520.h>
#fuses HS,NOLVP,NOWDT,NOPROTECT
#DEVICE ADC=8                          // *set ADC to 8 bit accuracy*
#use delay(clock=20000000)             // 20 MHz clock
#use rs232(baud=19200, UART1)          // Set up PIC UART on RC6 (tx) and RC7 (rx)  
int8 data_tx, data_rx = 0;             // Set up data_tx (transmit value), data_rx (recieve value)
void main()
{
   setup_adc_ports(AN0);               // *Enable AN0 as analog potentiometer input*
   setup_adc(ADC_CLOCK_INTERNAL);      // *the range selected has to start with AN0*
   set_adc_channel(0);                 // *Enable AN0 as analog input*
   delay_us(10);                       // *Pause 10us to set up ADC*
   
   while (TRUE)
   {
      data_tx = read_adc();            // *Read POT on analog port (0-255)*
      output_d(data_rx);               // Output last recieved value from computer
      delay_ms(10);
      
      if (kbhit())                     // If PIC senses data pushed to serial buffer
      {
         data_rx = fgetc();            // Read in recieved value from buffer
         printf("Pot: %u Char: %u\n", data_tx, data_rx);  // Once data sent and read, PIC sends data back
         delay_ms(100);
      }
   }
}
Personal tools