Introduction to creating GUI using MATLAB

In this post I’ll be talking about MathWorks MATLAB software and how one can create GUI’s using the software. This GUI creation has been made really simple in MATLAB.

Introduction

MATLAB® is a high-level language and interactive environment for numerical computation, visualization, and programming. Using MATLAB, you can analyse data, develop algorithms, and create models and applications. The language, tools, and built-in math functions enable you to explore multiple approaches and reach a solution faster than with spread sheets or traditional programming languages, such as C/C++ or Java. You can use MATLAB for a range of applications, including signal processing and communications, image and video processing, control systems, test and measurement, computational finance, and computational biology. More than a million engineers and scientists in industry and academia use MATLAB, the language of technical computing.

This paragraph is what is given on their website. So MATLAB is a very versatile software. One can use it for many applications. We learnt MATLAB as a part of our curriculum. We learnt how to make graphs, make simple programs, analyse LTI systems using MATLAB. But recently I learnt how to make GUI using MATLAB because my project needed this. So here I am sharing my knowledge with you all.

GUI

GUI stands for a graphical user interface. This is nothing but a graphical utility that is used to make the life of a common user easier. A graphical user interface takes inputs as mouse clicks and others. Let me give you an example. Those of you who are familiar with present day LINUX operating system have seen the windows/apple like interface. But earlier there used to be a command prompt like terminal in LINUX. Here one had to type in list of commands for performing any task. So if you want to see the calendar you needed to type in the command related to the same. But now there is a GUI available for it. Behind the scene there is extensive coding done so that the user does not have to be a coder in order to use the system. So this was an example of GUI’s making our life easier.

Now let us discuss the scope of GUI’s in our micro controller based projects. There is a huge scope for GUI’s here. For example you can make a GUI that could have just two buttons one Red LED and the other Green LED. You could program it in such a way that whenever you pressed this button the corresponding LED on Launchpad will glow. This is just a simple example you can take this to the next levels by making real time graphs using MATLAB. For example there is a sensor that is collecting data and sending it serially to your computer. You can plot real time graphs of that data and do manipulations on that data. This is the signal processing part. This can be easily done using MATLAB.

Steps for creating a GUI

Step 1: Open MATLAB

Step 2 : New—> Graphical User Interface

Step 3 : Select blank GUI

Step 4 : Create your own GUI using the palette available on the left hand side (for more details view the video tutorial.)

Step 5 : Save the file as ‘.fig’. After this step the ‘.m’ file of your GUI will automatically open in front of you.

Video

For more details refer the documentation provided in MATLAB and http://www.mathworks.in/

Line Follower using msp430g2 launchpad

In this post I’ll be writing about line follower bot. This post covers how a light sensor works and how to make your own light sensor. All criticisms are welcome.

Introduction

A line follower bot is as the name suggests a bot that follows a line. Now this line can be either a dark one on a white surface or a white line on a black surface. So once you switch the bot ON it will keep on following the path that you create using the line.

Sensors

Theory

For this we’ll be needing a light sensor which may be based on visible light or infrared. The concept used is that different colours absorb different wavelengths of light and reflect different wavelengths. Have you ever wondered why a book that appears red to you is that coloured? The physics behind is that a red material will absorb all other colours of white light and reflect the red colour. With that being said it will make sense that black colour absorbs all wavelengths or colours while white reflects all colours. We will use this concept to make our sensors.

Components

We can make the sensor using the following combinations.

  • LED and LDR
  • IR LED and IR diode

What remains common in both the combinations is the use of transistor as a switch. We use transistor as a switch to make the sensor give us digital output i.e. high and low.

The theory on transistor as a switch can be found in the following literatures.

I’ve made one circuit taking reference from Boylestad and the site whose link I’ve posted above. This circuit will give you ~2V when there is no IR light falling on the IR receiver and will give you ~0V when IR light falls on the receiver. So whenever there is any obstacle near the IR led we’ll get logic 0 and whenever there is no obstacle near the IR led we will get logic 1. Note that you can get ready made IR sensors for this application. I’ve given this basic introduction so that those of you who want to know how to make your own sensor get some guidance.

Circuit

100120141333

Well with that being taken care let’s develop the logic for our line follower.

Line follower logic and concept

Well I’ll be using a sensor that I got after I attended an internship on embedded c and advanced robotics. This sensor gives logic 0 when there is no IR light reflected to it and logic 1 when there is IR light reflection. To keep things simple our track background colour is white and the path is black. So when the sensor is on white background it’ll reflect light and when it is on the path it wont reflect light. Now lets develop our logic. We’ll need two sensors in order for this line follower to work. When there is a straight path both the sensors will point on white surface thus giving logic 1. So when we have this condition satisfied we’ll send data 1010 to the motor driver port pins.(I’ve connected the motors in such a way that 10 corresponds to forward movement and 01 corresponds to backward movement. This is done so that there is no confusion.) Now lets imagine there is a smooth left turn on the path. The left sensor will go on the black path first while the right sensor will be on the white background. Thus l=0 and r=1.(‘l’ corresponds to the left sensor data and ‘r’ corresponds to right sensor data.) To stay on track we need to make a left turn. This can be done in two ways. First is to make the left wheel stop so that the right wheel rotates and the bot takes a left turn. Second is to make left wheel rotate in backward direction and the right wheel move in forward direction. On similar grounds when there is a smooth right turn the bot needs to turn right. This can be achieved by same two methods just the motor data is interchanged. So this is the concept behind a line follower.

Motor driver

A microcontroller can supply limited current, so in order to drive any heavy load requiring high voltage and current we need to connect a motor driver IC between the microcontroller and the load which in this case is a motor. So I’ll be using the driver IC L239D. This IC has four H bridges that will allow us to control two motors using the same IC. The connections are pretty simple. You just need to see the data sheet for the connections. If you find any difficulty just Google how to use that IC you’ll get required information. And you can comment here posting your doubts and I’ll revert as soon as possible.

Code in Embedded C

/*
 *  line_follower.c
 *  Created on	: 10-Jan-2014 4:19:47 PM
 *  Author	  	: Manpreet Singh Minhas
 *  Website		: https://learningmsp430.wordpress.com/
 */

#include <msp430g2553.h>
// P1IN&BIT0 I've connected the left sensor to P1.0
// P1IN&BIT1 right sensor to P1.1
void main()
{
	WDTCTL = WDTPW | WDTHOLD;	// Stop watchdog timer
	P1DIR |= BIT2|BIT3|BIT4|BIT5;// Make P1.2 P1.3 P1.4 P1.5 as output
	P1DIR &= ~BIT0|~BIT1;	// Make P1.0 P1.1 as input
	P1OUT =0;
	for(;;)
	{
		if((P1IN&0x03) == 0x03)
		{
			P1OUT |= BIT2|BIT4;
			P1OUT &= ~(BIT3|BIT5);
		}
		if((P1IN&0x03) == 0x02)
		{
			P1OUT |= BIT4;
			P1OUT &= ~(BIT2|BIT3|BIT5);
		}
		if((P1IN&0x03) ==0x01)
		{
			P1OUT |= BIT2;
			P1OUT &= ~(BIT3|BIT5|BIT4 );
		}
	}

}

Code in Arduino

/*
 *  line_follower.ino
 *  Created on	: 10-Jan-2014 4:19:47 PM
 *  Author	  	: Manpreet Singh Minhas
 *  Website		: https://learningmsp430.wordpress.com/
 */
void setup()
{

  pinMode(2,INPUT);
  pinMode(3,INPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);

}
void loop()
{
  int l = digitalRead(2);
  int r = digitalRead(3);
  if(l==HIGH && r==HIGH)
  {
        digitalWrite(4,HIGH);
        digitalWrite(5,LOW); // 12 and 13 for left motor
        digitalWrite(6,HIGH);// 10 and 11 for right motor
        digitalWrite(7,LOW );
  }

    if(l==LOW && r==HIGH)
  {
        digitalWrite(4,HIGH);
        digitalWrite(5,LOW);
        digitalWrite(6,LOW);  // 
        digitalWrite(7,LOW );
  }

    if(l==HIGH && r==LOW)
  {
        digitalWrite(4,LOW);
        digitalWrite(5,LOW);
        digitalWrite(6,HIGH);
        digitalWrite(7,LOW );
  }
}

I’ve written the code in both embedded C and arduino. You will energia for burning the ‘.ino’ code.

Circuit Diagram

line_follower_circuit

Video

Please visit http://robokart.com/ for the sensors,chassis and other robotics related parts(for people living in India)

Serial Communication

Hello!! Before I start this post I want to say that if anyone of you wants to add me to their linkedin network here is my profile link : in.linkedin.com/in/msminhas93/

Often we need to communicate between two devices. This can be either parallel or serial. In parallel communication there is an individual data line for each bit, so normally there would be 8 data lines for 8 bit data. In asynchronous we require only two lines. One for transmission and the other for reception.

Theory

So the main thing in serial communication is ‘baud rate’. It is nothing but the bits sent per second. In serial asynchronous communication the baud rate of both transmitter and receiver have to be equal. If there is any mismatch there is bound to be error in sending and receiving data.

Now you might wonder what is sent serially? The answer is ASCII values of the character or symbol to be transmitted is sent serially. Now ASCII is a 7 bit hex code. There is the extended ASCII code as well. You can find all the ASCII values here.

Now let us take an example. Suppose I want to send character M serially. The ASCII value of M is 0x4D. The binary equivalent is 0b01001101. Now we send this data as pulses, changing the bits after the time 1/baud_rate.

070120141331

So this is how the serial data looks like. Some of you might have this doubt that how on earth will the processor or controller come to know that the other party is transmitting data and it has to take those bits. This is a very good doubt.

The beginning of serial data is marked by a start bit and on similar grounds there is a stop bit or two. Just like one normally says ‘hello’ at the start of a conversation and ‘bye’ at the end we send the start and stop bits for the same purpose.

The other question that may arise in the mind of the curious is that what if there is noise in the system? This is a valid question as well. So there are error checking bits like parity bits which are sent along with the data serially. (Parity can be even or odd. Now if the system uses even parity, then it will make the number of ‘1’ bits in the data even by adding 1 or 0. So if the data already has even number of ones the even parity bit is 0 and if the data has odd number of ones then the even parity bit is set or is 1 so that the total number of ones in the data is even.) Well this sums up asynchronous serial communication part.

Now this is known as UART module in the microcontrollers. UART stands for universal asynchronous transmitter and receiver. Most modern microcontrollers have a dedicated hardware for asynchronous serial communication called UART. msp430 also has this facility. Now what this means that you have to just configure the peripheral and the baud rate generation, parity bits and all other factors as well as the receiving part is done by this hardware. (If you wanted to send data serially without hardware dedicated for the same you would have to make the port high and low, use delay subroutines and the rotate instructions for doing the same task. The detection will also be tedious.)

This is how the data will look when  you send it via UART module.

w_example

Well let’s begin with the USCI module that provided in the msp430 micro controllers. This provides a UART mode for asynchronous serial communication. There are few basic initialization registers like all peripherals of msp430. Note that you can use grace for initializing the UART mode. But I’ll be covering the normal method by using the command registers and configuring it to meet our needs.

Let us begin.

UART mode features include:
• 7- or 8-bit data with odd, even, or non-parity
• Independent transmit and receive shift registers
• Separate transmit and receive buffer registers
• LSB-first or MSB-first data transmit and receive
• Built-in idle-line and address-bit communication protocols for multiprocessor systems
• Receiver start-edge detection for auto-wake up from LPMx modes
• Programmable baud rate with modulation for fractional baud rate support
• Status flags for error detection and suppression
• Status flags for address detection
• Independent interrupt capability for receive and transmit

The list of all registers related to the UART mode are listed below.

registers_list

Now the procedure how to initialize these registers is given in the msp430g2 user manual.

initializing

Just set those bits which you want as per the explanation given in the user guide.

Then there are the UCA0TXBUF and UCA0RXBUF via which the serial data is transmitted and received respectively. If you want to send any character just put it in the UCA0TXBUF register and it will be transmitted. Just check whether the byte has been sent or not by checking the UCA0TXIFG bit of IFG2 register. If it is set means the module is busy sending the previous byte or data and one has to wait till it is reset.

With this background you should be able to program the controller to send and receive data.

Before we shift to the program there is something that I need to tell you. For hardware UART via launchpad without having to use the rs232 cable and max232 IC. For newer launchpad versions i.e. 1.5 and above there is the position of the jumpers printed on the launchpad itself for hardware UART and software UART respectively.

Hardware UART on Launchpad 1.4

If you have a Launchpad of v1.4 (versions that have no ‘Rev x.x’ printed below the ‘MSP-EXP430G2’ label are pre 1.5) is is possible to use hardware UART by replacing the MSP430 with a newer model, such as the MSP430G2553 and then cross connecting the serial pins in header J3 i.e the TXD and RXD(use a cross jumper or female to female wires for the same.)

Program

#include "serial.h"
#include "lcd.h"
int main(void) {
    WDTCTL = WDTPW | WDTHOLD;	// Stop watchdog timer
    uart_init();
    lcd_init();
    IE2 |= UCA0RXIE;
    println("START");
    __bis_SR_register(LPM0_bits + GIE);
}
#pragma vector=USCIAB0RX_VECTOR
__interrupt void USCI0RX_ISR(void)
{
	if(UCA0RXBUF == '0')
        {
            send_command(0x01);
        }
	else
        send_data(UCA0RXBUF);
}

/*
 *  serial.h
 *  Created on   	: 01-Jan-2014 12:25:06 PM
 *  Author	  	: Manpreet Singh Minhas
 *  Website		: https://learningmsp430.wordpress.com/
 *  This is a standard header for 9600 baud rate serial communication.
 */

#ifndef SERIAL_H_
#define SERIAL_H_

#include<msp430g2553.h>// Change this as per your micro-controller chip.
void uart_init(void);
void send_byte(int data);
void print(char *data);
void println(char *data);
void send_int(int a);
void send_intln(int a);
void uart_init()
{
	P1SEL  |= BIT1|BIT2; // Port for UART transmission and reception purpose.
	P1SEL2 |= BIT1|BIT2;
    UCA0CTL1 |= UCSWRST; // Software reset
    UCA0CTL1 |= UCSSEL_1;// Select ACLK
    UCA0BR0 = 3;// This is the count for getting 9600 baud rate 32768/9600 = 3.4133
    UCA0BR1 = 0;
    UCA0MCTL = UCBRS1 + UCBRS0;// Modulation bits = 0b00000011
    UCA0CTL1 &= ~UCSWRST;	// Start the UART
}
void send_byte(int data)
{
	while (!(IFG2&UCA0TXIFG));
	UCA0TXBUF = data;
}
void print(char *data)
{
	while(*data)
	{
		send_byte(*data);
		data++;
	}
}
void println(char *data)
{
	while(*data)
	{
		send_byte(*data);
		data++;
	}
	send_byte('\n');
	send_byte('\r');
}
void send_int(int a)
{
	int temp;
	int rev=0;
	int dummy =a;
	 while (dummy)
	   {
	      rev = rev * 10;
	      rev = rev + dummy%10;
	      dummy = dummy/10;
	   }
	while(rev)
	{
		temp=rev%10;
		send_byte(0x30+temp);
		rev /=10;
	}
}
void send_intln(int a)
{
	int temp;
	int rev=0;
	int dummy =a;
	 while (dummy)
	   {
	      rev = rev * 10;
	      rev = rev + dummy%10;
	      dummy = dummy/10;
	   }
	while(rev)
	{
		temp=rev%10;
		send_byte(0x30+temp);
		rev /=10;
	}
	 send_byte('\n');
	 send_byte('\r');
}
#endif/* SERIAL_H_ */

Well this program will send the data received serially to lcd. For sending data you will require a software like hyper terminal, putty, energia serial monitor, arduino serial monitor etc. So just configure that to 9600 baud rate with no parity bits and only one stop bit and you are all set to send data serially. If you have any problem you can comment or send me mail.

Video

Thermometer using LM35

Hello there in this post I’ll be talking about how to interface a temperature sensor to msp430 launchpad. So we’ll be requiring a temperature sensor for this project. I am using LM35 IC. Well as I always say that one needs the datasheet of the IC he is using. Here is the link to the datasheet. The LM35 series are precision integrated-circuit Calibrated Directly in ° Celsius (Centigrade) temperature sensors, with an output voltage linearly proportional to the Centigrade temperature. Thus the LM35 has an advantage over linear temperature sensors calibrated in ° Kelvin, as the user is not required to subtract a large constant voltage from the output to obtain convenient Centigrade scaling.

• Linear + 10 mV/°C Scale Factor

• 0.5°C Ensured Accuracy (at +25°C)

• Rated for Full −55°C to +150°C Range

• Suitable for Remote Applications

These are few features of this sensor. The pin out is given below.

pin_out

Please take care while connecting the +Vs and GND. The given view is bottom view. So just hold the IC properly to identify the terminals. I connected them thinking that this was top view(idiotic on my part), but still so that you don’t make the same mistake I am sharing this.

The connection diagram is given below.

connection_diagram

We have a voltage reading available from lm35. So we use the inbuilt 10 bit ADC of msp430g2553. Using this ADC we can get a digital value for the analog voltage. Now we need to find the relation between this digital value and the centigrade scale. I’ve chosen 3.6V as the Vref, so 1024 corresponds to 3.6V. Now the scale is  10 mV/°C, so 3.6V corresponds to 360°C.

010120141329

So we need to multiply the digital reading by 0.35, but since there is no inbuilt multiplication hardware we multiply by 35 then divide by 100 to avoid floating multiplication. Now all that is left is to display this reading on an LCD.

I’ve started using Energia recently so I’ll posting its code here as well. Regarding the ADC initialization I’ll be writing a separate tutorial for that. (Note the LCD header file used has a new function send_integer to send integer values.)

The circuit:
=================================
LCD pin              Connect to
———————————
01 – GND             GND, pot
02 – VCC             +5V, pot
03 – Contrast        Pot wiper
04 – RS               P1.4
05 – R/W              P1.5
06 – EN               P1.6
07 – DB0             GND
08 – DB1             GND
09 – DB2             GND
10 – DB3             GND
11 – DB4             P2.0
12 – DB5             P2.1
13 – DB6             P2.2
14 – DB7             P2.3
15 – BL+             +5V
16 – BL-             GND
=================================

Temperature sensor output goes to P1.0 (A0) pin.

CCS Code

/*
*  temperature_sensor.c
*  Created on     : 01-Jan-2014 1:26:21 PM
*  Author         : Manpreet Singh Minhas
*  Website        : https://learningmsp430.wordpress.com
*/
#include "lcd.h"
void main()
{

WDTCTL = WDTPW|WDTHOLD; //Stop watchdog timer
lcd_init();// Initialize the LCD
ADC10CTL0 |= ADC10ON;//ADC setup
ADC10CTL1 |= INCH_0|ADC10SSEL_1|CONSEQ_1;
ADC10AE0  |= BIT0|BIT1;
ADC10CTL0 |= ENC|ADC10SC;
TA0CCR0 = 0x1000;
TA0CTL = TASSEL_1|ID_3|MC_1|TAIE;// Timer setup
send_command(0x80);
send_string("Temperature:");
_BIS_SR(LPM3_bits + GIE);// Enter Low power mode

}
#pragma vector=TIMER0_A1_VECTOR
__interrupt void Timer_A(void)
{
ADC10CTL0 |= ENC|ADC10SC;
send_command(0xC0);
int temp = (ADC10MEM*35)/100;
send_integer(temp);
send_data(0xDF);
send_string("C");
TA0CTL &= ~(TAIFG);
}

lcd.h code

// Author : Manpreet Singh Minhas
// This file is for 4 bit mode LCD interfacing with msp430g2553 chip
// 16x2 LCD is used   
#include <msp430g2553.h>
#define DR     P1OUT = P1OUT | BIT4  // define RS high
#define CWR        P1OUT = P1OUT &(~BIT4)// define RS low
#define READ       P1OUT = P1OUT | BIT5  // define Read signal R/W = 1 for reading
#define WRITE      P1OUT = P1OUT &(~BIT5)// define Write signal R/W = 0 for writing
#define ENABLE_HIGH     P1OUT = P1OUT | BIT6  // define Enable high signal
#define ENABLE_LOW      P1OUT = P1OUT &(~BIT6)// define Enable Low signal
unsigned int i;
unsigned int j;
void delay(unsigned int k)
{
    for(j=0;j<=k;j++)
    {
        for(i=0;i<100;i++); } } void data_write(void) { ENABLE_HIGH; delay(2); ENABLE_LOW; } void data_read(void) { ENABLE_LOW; delay(2); ENABLE_HIGH; } void check_busy(void) { P2DIR &= ~(BIT3); // make P2.3 as input while((P2IN&BIT3)==1) { data_read(); } P2DIR |= BIT3; // make P2.3 as output } void send_command(unsigned char cmd) { check_busy(); WRITE; CWR; P2OUT = (P2OUT & 0xF0)|((cmd>>4) & 0x0F);   // send higher nibble
        data_write();                              // give enable trigger
        P2OUT = (P2OUT & 0xF0)|(cmd & 0x0F);      // send lower nibble
        data_write();                            // give enable trigger

}

void send_data(unsigned char data)
{
        check_busy();
        WRITE;
        DR;
        P2OUT = (P2OUT & 0xF0)|((data>>4) & 0x0F);    // send higher nibble
        data_write();                                // give enable trigger
        P2OUT = (P2OUT & 0xF0)|(data & 0x0F);       // send lower nibble
        data_write();                              // give enable trigger
}

void send_string(char *s)
{
    while(*s)
    {
        send_data(*s);
        s++;
    }
}
void send_integer(int a)
{
    {
        int temp;
        int rev=0;
        int dummy =a;
         while (dummy)
           {
              rev = rev * 10;
              rev = rev + dummy%10;
              dummy = dummy/10;
           }
        while(rev)
        {
            temp=rev%10;
            send_data(0x30+temp);
            rev /=10;
        }
    }
}
void lcd_init(void)
{
        P2DIR |= 0xFF;
        P1DIR |= BIT4|BIT5|BIT6;
        P2OUT &= 0x00;
        send_command(0x33);
        send_command(0x32);
        send_command(0x28); // 4 bit mode
        send_command(0x0E); // clear the screen
        send_command(0x01); // display on cursor on
        send_command(0x06); // increment cursor
        send_command(0x80); // row 1 column 1
}

Energia Code

#include LiquidCrystal.h;
/*
*  temperature_sensor.c
*  Created on    : 01-Jan-2014
*  Author          : Manpreet Singh Minhas
*  Website        : https://learningmsp430.wordpress.com
*/

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(P2_0, P2_1, P2_2, P2_3, P2_4, P2_5);
byte degree[8] = {
0b00111,
0b00101,
0b00111,
0b00000,
0b00000,
0b00000,
0b00000,
0b00000
};

void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("Temperature:");
Serial.begin(9600);
pinMode(A0,INPUT);
lcd.createChar(1, degree);
}

void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:

int temperature = analogRead(A0);
Serial.println(temperature);
int temp = (temperature*35)/100;
lcd.print(temp);
lcd.write(1);
lcd.print('C');
delay(3000);
}

Output

010120141328