Use Matlab to read serial data

29 Oct 2013

Matlab can be configured to read serial data that can be send through a microcontroller. Here is the code for Matlab to read a single line and print. Assume that you are sending ascii character values through microcontroller separated by new line.Here is the Matlab code to receive the data.

obj1 = instrfind('Type', 'serial', 'Port', 'COM13', 'Tag', '');   
% Create the serial port objectif it does not exist   
% otherwise use the object that was found.   
if isempty(obj1)   
 obj1 = serial('COM13');   
else   
 fclose(obj1);   
 obj1 = obj1(1)   
end  
obj1.BaudRate=4800;  
set(obj1, 'Parity', 'even');  
set(obj1, 'StopBits', 2.0);  
fopen(obj1);  
data1=fscanf(obj1, '%s');  
data1=fscanf(obj1, '%s'); %Assume that you are sending characters and 8 bit binary no.s  
data1;                    %Use a=fread(obj1); if it's not charecter  
fclose(obj1);  
delete(obj1);    
clear obj1;

Here is the code for AVR Microcontroller to send ‘1024’ through serial port.

 /*   
 * Ploting_ADC_Values.c   
 *   
 * Created: 22-10-2013 

 54   
 *  Author: ANANTHAKRISHNAN U S   
 */   



 #define F_CPU 1000000UL  
 #define FOSC 1000000   
 #define BAUD 4800  
 #define MYUBRR FOSC/16/BAUD-1  

 #include <avr/io.h>  
 #include <util/delay.h>  
 #include <stdio.h>  

 staticint uart_putchar(char c, FILE *stream);  
 static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL,_FDEV_SETUP_WRITE);  


 void USART_Init( unsignedint ubrr);  
 staticint uart_putchar(char c, FILE *stream);  
 char uart_getchar(FILE *stream);  

 int main(void)  
 {  
 	USART_Init(MYUBRR);                  //Initializing USART  
 	stdout = &mystdout;  
 	int i =1024;  
 	while(1)  
 	{  
 		printf("%d\n",i);  
 		_delay_ms(50);  
 	}  
 }  

 void USART_Init( unsignedint ubrr)  
 {  
 	/*Set baud rate */  
 	UBRR0H = (unsignedchar)(ubrr>>8);  
 	UBRR0L = (unsignedchar)ubrr;  
 	//Enable receiver and transmitter */  
 	UCSR0B = (1<<TXEN0) | (1<<RXEN0);  
 	/* Set frame format: 8data, 2stop bit */  
 	UCSR0C = (1<<USBS0)|(3<<UCSZ00)|(1<<UPM01);//Asynchronous 8bit data Even parity 2 stop bit  
 }  

 staticint uart_putchar(char c, FILE *stream)  
 {  
 	if (c == '\n') {  
 		uart_putchar('\r', stream);  
 	}  
 	// Wait for empty transmit buffer */  
 	while ((UCSR0A & (1 << UDRE0)) == 0) {};  
 	// Put data into buffer, sends the data */  
 	UDR0 = c;  
 }  


 char uart_getchar(FILE *stream) {  

 	while ((UCSR0A & (1 << RXC0)) == 0) {};  
 	/* Wait until data exists. */  
 	return UDR0;  
 }