[go: up one dir, main page]

0% found this document useful (0 votes)
7 views27 pages

Lab Set IV

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Microcomputers and Interfacing

Lab Set IV
ADC, UART, PWM

Objective:
In this lab, you will understand how the following three modules of a microcontroller are used:
 ADC (Analog to Digital Converter) to interface sensors,
 UART (Universal Asynchronous Receiver/Transmitter) to communicate with computer or
other microcontroller and
 PWM (Pulse Width Modulation) to control power delivery.

Required knowledge, skill and materials:


● Knowledge of programing in Embedded C and Keil IDE experience is required
● Software
o Keil µVision and Proteus

Grading:
i. Attend the lab session and demonstrate your work (60%), you must sign attendance sheet.
ii. Write a brief report and email (40%) addressing those questions labeled with Q .

Introduction:
In this lab you will use analog to digital converter (ADC) to read in analog signal from photo sensor and convert
to digital value. Unlike in lab III, where you used hardware to set lux value, here, you will use ADC to read
analog signal from the photo sensor and perform switching at any luminous intensity you like as the same
time send the value read to UART interface where you can connect PC or another microcontroller. The ADC
technique is much better because since you can monitor your room’s real-time luminous intensity, you can
do some automation like controlling a window shutter or power to a lighting source to maintain a constant
illumination. In general, ADC gives the digital version of analog values read from sensors.
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Part 1: ADC

a) Use ADC to measure analog signal (illuminance, Ev): Read Appendix A


In this Lab section, we will connect our photo sensor to one of the 14 ADC channel pins (ADC0.6) in
software controlled mode to control LEDs switching (You are advised to try it in Burst mode as well).

Steps to Configure ADC


i. Configure PINSEL register to select the right ADC pin
ii. Configure the ADC Control Register (ADxCR) according to the need of application.
iii. Start ADC conversion by writing appropriate value to START bits in ADxCR. (Example,
writing 001 to START bits of the register 26:24, conversion is started immediately).
iv. Monitor the DONE bit (bit number 31) of the corresponding ADxDRy (ADC Data Register) till
it changes from 0 to 1. This signals completion of conversion. We can also monitor DONE bit
of ADGSR or the DONE bit corresponding to the ADC channel in the ADCxSTAT register.
v. Read the ADC result from the corresponding ADC Data Register.
ADxDRy. E.g. AD0DR1 contains ADC result of channel 1 of ADC0.
I. Configure PINSEL0 bits 8 & 9 to 11 to select pin P0.4 as ADC0.6
PINSEL0 |= 0x000000300; //Select Pin function P0.4 as ADC0.6
II. Configure the ADC Control Register (AD0CR) for Software mode (1<<16); ADC clk = 4MHz
(14<<8); Power UP (1<<21); Select AD0.6 (1<<6); Start conversion ((0<<26)|(0<<25)|(1<<24));
Set resolution to 10 bit (((0<<19)|(0<<18)|(0<<17))).
// CLKDIV = 14, assuming PCLK=15MHz, ADC clk =PCLK/(CLKDIV+1) =1MHz <=4MHz
//Software mode
AD0CR = (14<<8) | (0<<16) | (1<<21) | (1<<6)
AD0CR |= ((0<<26)|(0<<25)|(1<<24));
//Burst mode
AD0CR = (14<<8) | (1<<16) | (1<<21) | (1<<6) | ((0<<19)|(0<<18)|(0<<17));
III. Read result from AD0GDR
//For Software mode:
While ((AD0DR6 & (1UL<<31)) == 0 ); //waits until Done bit =0, till data is ready
int result = (AD0GDR_Read>>6) & 0x3FF; //Extract Conversion Result
voltage = ((float)result*VREF)/1024; //Convert result to volts
//For Burst mode:
For Burst mode, you need to define & install an ISR as Vectored IRQ in main. The ISR
should read result from AD0GDR and clear DONE and ADC interrupt flags.
VICIntEnable |= (1<<18); //18 is VIC channel # for ADC0
VICVectCntl0 = (1<<5) | 18;
VICVectAddr0 = (unsigned) AD0ISR;//
AD0INTEN = (1<<6) //Completion of ADC0.6 generates interrupt

__irq void AD0ISR(void) { //AD0 ISR


unsigned long AD0GDR_Result = AD0GDR; //Read Result
int channel = (AD0GDR_Read>>24) & 0x7; //Extract Channel Number for Burst mode
if(channel == 6){
int result = (AD0GDR_Read>>6) & 0x3FF; //Extract Conversion Result
int dummyRead = ADD0DR6;} //Just to Clear Done flag & clears AD0 interrupt
voltage = ((float)result*VREF)/1024; //Convert result to volts
VICVectAddr = 0x0; }

2|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Now, let’s begin coding.


1. Open Keil µVision5. Create new LPC2148 project with name ADC_UART_PMW.
2. Create ADC_UART_PMW.C file, add it to target and copy the following code into the file
ADC_UART_PMW.C
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <lpc213x.h>
#include <stdio.h>
#include "initClock.h"
#include "LCD.h" //from lab III

int main(void)
{
int result = 0;
float voltage = 0;
float Ev = 0;
float VREF = 3.3;//Reference Voltage = 3.3V
char str[80];

initClocks(); //initialize CCLK = 60Mhz, PCLK = CCLK / 4 =15MHz


LCD_INIT();
LCD_CMD(0xC);
LCD_Write("Voltage= ");
LCD_CMD(0xC0);
LCD_Write("Ev = ");

PINSEL0 |= 0x01000300; //Select Pin P0.4 as ADC0.6


IO1DIR |= 0x00FF0000;

while (1)
{
//Configure ADC clk frequency CLKDIV = 14, assuming PCLK=CCLK/4=15MHz,
Modify the following statement (????????) to configure ADOCR for: software mode; AD0.6
channel; 1MHz ADC clk and to power UP and then start conversion in second line.
AD0CR =????????;
AD0CR |= (1 << 24)); // start conversion

while ((AD0GDR & (1UL << 31)) == 0);


result = (AD0GDR >> 6) & 0x3ff;
voltage = ((float)result*VREF) / 1024; //Convert result to volts.
Formulate the equation relating Ev (illuminance) and V from APDS_9002 datasheet Ev-V curve.
Ev = voltage * ???; //convert voltage to illuminance

//Switching LEDs
if (Ev < 100) {
IO1SET = 0x00FF0000;
}
else {
IO1CLR = 0x00FF0000;
}
//Displaying Reading on LCD
LCD_CMD(0x89);
sprintf(str, "%i mV ", (int)(voltage * 1000));
LCD_Write(str);
LCD_CMD(0xC9);
sprintf(str, "%i Lux ", (int)(Ev));
LCD_Write(str);
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

3|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Q Configure AD0CR register appropriately for software controlled ADC mode in the above code.
3. Create header file with name initClock.h; copy and paste the following code in it save. Then
build your project. If initClock.h doesn’t appear under “Source Group 1”, try adding manually.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#include <lpc214x.h>

#define PLOCK 0x00000400

void delayMS(unsigned int milliseconds);

void initClocks(void)
{
//setupPLL0 Assuming 12Mhz Xtal is connected to LPC2148.
PLL0CON = 0x01;
PLL0CFG = 0x24;

//sequence for locking PLL to desired freq.


PLL0FEED = 0xAA;
PLL0FEED = 0x55;

//connect PLL0
while (!(PLL0STAT & PLOCK));
PLL0CON = 0x03;

//sequence for connecting the PLL as system clock


PLL0FEED = 0xAA;
PLL0FEED = 0x55;
//SysClock is now ticking @ 60Mhz!

VPBDIV = 0x00; // PCLK is CCLK/4 i.e 15Mhz


}
void delayMS(unsigned int milSec)
{
T0CTCR = 0;
T0PR = 60000; //60000 clock cycles = 1 mS CCLOK = 60 MHz
T0TCR = 0x02; //Reset Timer
T0TC = 0;
T0TCR = 0x01; //Enable timer

while (T0TC < milSec); //wait until timer counter reaches the desired delay

T0TCR = 0x00; //Disable timer


}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4. Include LCD.h from lab III and compile your code
5. Start Debugging session (Ctrl+F5). From Peripherals-
>System Control Block menu open “Phase Locked Loop
0” and “VPB Divider”. And check if CCLK (CLOCK)=
60MHz =PCLK fter executing the initClocks() function.
6. From Peripherals menu open A/D Control and set the
value of AD06 to 2.0 Volt; continue debugging line by
line and observe the value of AD0GDR or ADoDR6 and
RESULT or RESULT6.
Q Explain content of AD0GDR (AD0DR6); What is value of A/D clock, reduce it by half in your code.
Q Convert the above ADC code from Software controlled mode to Burst mode. In Burst mode, you
don’t manually force ADC to do conversion, instead, the ADC continuously do conversion and all
you need to do is just read the appropriate register for data inside ISR; whenever conversion is
read ADC generates interrupt.

4|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

b) Use UART to communicate with another device


In this lab section, you will use UART (Universal Asynchronous Receiver Transmitter) interface
to send digital data acquired from the photo sensor on the microcontroller to a personal
computer. Since PCs usually run database servers accessible virtually from any device, the
importance of MCU-PC communication is apparent. This is usually done through serial
communication; read Appendix B for detail explanation of serial communication alternatives.

Steps to Configure UART


i. Select UART pin function using PINSEL register.
ii. Configure the format of the data character that is to be transmitted using Line Control Register
(U0LCR) for
U0LCR = 0x83; //8 bits data, no Parity, 1 Stop bit and DLAB set to 1
iii. The UART0 Divisor Latches [U0DLM:U0DLL] for Fractional Baud Rate Generation.
U0DLL = 0x62;
U0DLM = 0x00;
iv. Configure the UART0 Fractional Divider Register (U0FDR) to fine tune Fractional Baud Rate
Generation
U0FDR = (1<<4) | 0x00 // MULVAL=1(bits - 7:4) , DIVADDVAL=0(bits - 3:0)
v. Disable access to Divisor Latches (DLM, DLL ) by reseting DLAB bit of U0LCR
U0LCR = 0x3;

1. Add the following functions into ADC_UART_PMW.C and declare both function above main.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initUART0(void)
{
//Select pins P0.0 as UART0 TxD and P0.1 as UART0 RxD
PINSEL0 |= (PINSEL0 & 0xFFFFFFF0) | 0x00000005
U0LCR = 0x83; // 8 bits, no Parity, 1 Stop bit | DLAB set to 1

//[U0DLM:U0DLL] holds 16bit [8:8] used to divide clock and generator baud
U0DLL = 0x62;
U0DLM = 0x00; // for 9600 Baud Rate
U0FDR = (1 << 4) | 0x0; // MULVAL=1(bits - 7:4) , DIVADDVAL=0(bits - 3:0)

U0LCR = 0x3; // Disable access to Divisor Latches. (DLM, DLL )


//BaudRate is set to ~9600 (=9566)
}

void transmitUART0(char *s)


{
int i = 0;
while (s[i] != 0x00)
{
while (!(U0LSR & 0x20));//waits until U0THR is empty
U0THR = s[i];
i++;
}
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

2. Add “transmitUART0(str);” in main function to send voltage and Ev values to UART0.


Now, whatever data you wright to LCD, will also appear to UART0 port as well.

5|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

3. Start debugging and run your code (F5); from Peripherals, open UART0 and check correctness
of fields: (a) “line control” values (b) Baudrate =9566~9600.
4. From View->Serial Windows menu open UART #1; you shall see
what ever value you set in AD06 analog input under A/D Converter
0 peripheral window.
Q Write a function “receiveUART0(char * str, int size)” to receive
data from UART0 and print to the LCD screen. It should be very
similar to the transmit function except it additionally takes size of
the character array as argument.
Q Try to discuss at least 2 ways to double the baudrate of your
UART, show the calculation. Note that Peripheral Clock (PCLK) can
be increased up to CPU Clock (CCLK) frequency.

c) Simulate your code on Proteus


1. Open lab III Proteus project or create a new
firmware project for LPC2138 with name
“ADC_UART”. If it’s new, just connect 2 LEDs
to one of LED and LCD pins as shown on the
figure to the right. Load HEX file.
2. Connect the photo sensor to AD0.6 pin of
LPC2138 as shown below; and connect 3.3V
supply to Vref (pin 63)

Q What is the purpose of the 10µF capacitor and the 3.3V Zener Diode?
3. Run simulation and observe the LCD output by varying photo sensor value.
4. Connect Virtual terminal and COMPIM from parts to UART0 pins as shown in the figure below.
5. Double click on both Virtual terminal and COMPIM and configure baudrate = 9600, data bit = 8,
stop bit =1 and set the rest to none. For COMPIM set com port to COM4 or the last available
from the list.
6. Run simulation and, From Debug menu open Virtual terminal window; you shall see UART
output on the terminal window.

6|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

The COMPIM sends the digital data to the serial port of your computer. You can read this data from serial
port of your computer (COM5) using any programming language. Now, lest use terminal emulators to
read the data.
7. Download terminal emulators of your preference and open. Configure the terminal with the
appropriate line control parameter values (baudrate = 9600, data bit = 8, stop bit =1 and set
the rest to none)
8. Download Virtual Serial Port Driver and pair COM4 and COM5
9. Connect the terminal on COM5 and observe.
Q Wright a python or c++ code that sends data to be displayed into LCD within you Proteus
project.

d) PWM to control room light illuminance.

Steps to Configure PWM


i. Select PWM pin function using PINSEL register.
PINSEL0 |= (PINSEL0 & 0xFFFF3FFF) | (1<<15); //Select P0.7 as PWM2
ii. Reset PWM Timer Counter and the PWM Prescale Counter
PWMTCR = (1<<1); // PWMTC and PWMPC are reset
iii. Reset the prescale register content.
PWMPR = 0X00; //Setting PWM prescale value;
iv. Configure Match Control Register, PWMMCR
PWMMCR = (1<<0)|(1<<1); //Setting PWM Match Control Register for PWMMR0
v. The maximum period of the PWM channel is set using PWMMR0.
PWMMR0 = 255; //8 bit PWM  28
vi. Set the Latch Enable to the corresponding match registers using PWMLER
PWMLER = (1<<0); //Enalbe PWM latch
(We use PWMMR0) So enable the corresponding bit by setting 1 in PWMLER
vii. To enable the PWM output to the pin we need to use the PWMTCR for enabling the PWM
Timer counters and PWM modes.
PWMTCR = (1<<0) | (1<<3); //Enabling PWM and PWM counter

7|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

1. Add the following functions as “initPWM()” in to your code


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void initPWM()
{
PINSEL0 = (PINSEL0 & 0xFFFF3FFF) | (1 << 15); //Setting pin P0.0 for PWM output
PWMTCR = (1 << 1); //Setting PWM Timer Control Register as counter
reset
PWMPR = 0X00; //Setting PWM prescale value
PWMMCR = (1 << 0) | (1 << 1); //Setting PWM Match Control Register
PWMMR0 = 250; //Giving PWM value Maximum value
PWMPR = 60000;
PWMLER = (1 << 0); //Enalbe PWM latch
PWMTCR = (1 << 0) | (1 << 3); //Enabling PWM and PWM counter
}//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2. Add the following code fragment in the main function inside while loop.
//in main function
initPWM();
PWMPCR |= (1 << 10); //Enable PWM2 output at pin P0.7

//in while loop


dutycycle = result / 4; //
PWMMR2 = dutycycle;
PWMLER |= (1 << 2); //Enable PWM Match 2 latch
3. Start debugging and run(F5); from peripheral menu open Pulse Width Modulation and observe how
match channel 2 changes. From A/D converter peripheral, set AD06 to different values to change
duty cycle of the PWM signal and observe.
Q The frequency of PWM is about 1 Hz; modify this frequency to the extent that makes it invisible to
the human eyes.
Q Modify the code so that brightness of the led increase proportional to photo sensor illuminance
instead of decrease.
Q (optional - Bonus) Try to control windows shutter attached to a motor to control room illuminance.

8|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Appendix A: ADC in LPC2148


Analog to Digital Converter(ADC) is used to convert analog signal into digital form. LPC2148
has two inbuilt 10-bit ADC, ADC0 & ADC1. Read lecture slides.
Features of ADC module in LPC2148:
• Two 10 bit successive approximation analog to digital converter (ADC0 & ADC1)
• ADC0 has 6 channels &ADC1 has 8 channels.
• Power-down mode.
• Measurement range 0 V to VREF (typically 3 V; not to exceed VDDA voltage level).
• 10 bit conversion time ≥ 2.44 µs.
• Burst conversion mode for single or multiple inputs.
Analog input of ADC must be between 0 and Vref; To protect the input pins from over voltage, one can
use a zener diode (usually 3 or 3.3 V for LPC2148). A typical value of 1.2K ohms can also be used to
limit the zener current. A 100nF decoupling capacitor can also be added to act as a low pass RC filter
with the series zener current limiting resistor; it helps to remove high frequency noise from the input.

Successive approximation ADC


ADC Operating modes in LPC2148
Software controlled mode:
In Software mode only one conversion will be done at a time. This conversion can be controlled
in software. To perform another conversion, you will need to re-initiate the process. In software
mode only 1 bit in the SEL field of AD0CR can be 1 i.e. only 1 Channel (i.e. Pin) can be selected
for conversion at a time. You can do conversions on multiple Channels (one at a time) by
selecting a particular Channel along with appropriate bit in SEL field and then do the same for
rest of the channels.
Burst or Hardware mode:
In Burst or Hardware mode conversions are performed continuously on the selected channels
in round-robin fashion. Since the conversions cannot be controlled by software, overrun may
occur in this mode. Overrun is the case when a previous conversion result is replaced by new
conversion result without previous result being read i.e. the conversion is lost. Usually an
interrupt is used in Burst mode to get the latest conversion results. This interrupt is triggered
when conversion in one of the selected channel ends

9|26
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

ADC Pin description


ADC Port Pin Functions Associated
Channel Pin PINSEL Register
ADC 0.1 P0.28 GPIO, AD0.1, CAP0.2, MAT0.2 24,25 bits of PINSEL1
ADC 0.2 P0.29 GPIO, AD0.2, CAP0.3, MAT0.3 26,27 bits of PINSEL1
ADC 0.3 P0.30 GPIO, AD0.3, EINT3, CAP0.0 28,29 bits of PINSEL1
ADC 0.4 P0.25 GPIO, AD0.4, AOUT 18,19 bits of PINSEL1
ADC 0.6 P0.4 GPIO, SCK0, CAP0.1 , AD0.6 08,09 bits of PINSEL0
ADC 0.7 P0.5 GPIO, MISO0, MAT0.1 , AD0.7 10,11 bits of PINSEL0
ADC 1.0 P0.6 GPIO, MOSI0, CAP0.2, AD1.0 12,13 bits of PINSEL0
ADC 1.1 P0.8 GPIO, TXD1, PWM4, AD1.1 16,17 bits of PINSEL0
ADC 1.2 P0.10 GPIO, RTS1, CAP1.0, AD1.2 20,21 bits of PINSEL1
ADC 1.3 P0.12 GPIO, DSR1, MAT1.0, AD1.3 24,25 bits of PINSEL1
ADC 1.4 P0.13 GPIO, DTR1, MAT1.1 , AD1.4 26,27 bits of PINSEL3
ADC 1.5 P0.15 GPIO, RI1, EINT2 , AD1.5 30,31 bits of PINSEL3
ADC 1.6 P0.21 GPIO, PWM5, AD1.6, CAP1.3 10,11 bits of PINSEL1
ADC 1.7 P0.22 GPIO, AD1.7, CAP0.0, MAT0.0 12,13 bits of PINSEL1

10 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

ADC Registers description


REGISTER DESCRIPTION
ADxCR A/D Control Register: Used for Configuring the ADC
A/D Global Data Register: This register contains the ADC’s DONE bit and the result of the
ADxGDR most recent A/D conversion
ADxINTEN A/D Interrupt Enable Register
ADxDR0 - ADxDR7 A/D Channel Data Register: Contains the recent ADC value for respective channel
ADxSTAT A/D Status Register: Contains DONE & OVERRUN flag for all the ADC channels
A/D Global Start Register: This address can be written (in the AD0 address range) to start
ADxGSR conversions in both A/D converters simultaneously.

A/D Control Register (ADxCR)

11 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

A/D Global Data Register (ADxGDR)

12 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

A/D Global Start Register (ADGSR)

A/D Status Register (ADxSTAT)

13 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

A/D Data Registers (ADxDR0 - ADxDR7)


The A/D Data Register hold the result when an A/D conversion is complete, and also
include the flags that indicate when a conversion has been completed and when a
conversion overrun has occurred.

A/D Interrupt Enable Register (ADxINTEN)

:
:

14 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Appendix B: Serial Communication


LPC2148 supports 4 serial communication interfaces: UART, SPI, I2C and USB.

UART vs SPI vs I2C


The following table compares the 3 serial communication interfaces.
Features UART SPI I2C
Universal Asynchronous Serial Peripheral Interface Inter-Integrated Circuit
Full Form
Receiver/Transmitter

Interface
Diagram

TxD: Transmit Data SCLK: Serial Clock SDA: Serial Data


RxD: Receive Data MOSI: Master Output, Slave SCL: Serial Clock
Pin Input
Designations MISO: Master Input, Slave
Output
SS: Slave Select (chip select)
Maximum data rate Maximum data rate limit is not I2C supports 100 kbps, 400
supported is about 230 Kbps specified in SPI interface. kbps, 3.4 Mbps. Some variants
Data rate to 460kbps. also supports 10 Kbps and 1
Usually supports about 10
Mbps to 20 Mbps Mbps.
Distance Lower about 50 feet highest Higher
Type of Asynchronous Synchronous Synchronous
communication
Number of -- One One or more than One
masters
For 8 bits of data one start manufacturer specific protocols start and stop bits.
Protocol bit and one stop bit is used. ACK bit for each 8 bits of data.
one to one connection Slave select lines are used to all masters can communicate
Software between two devices, address slaves connected with with all the slaves. Up to 27
addressing addressing is not needed. the master. slave devices can be addressed
in the I2C interface circuit.(*)
• Smple communication • Full duplex •Needs fewer i.e. only 2
UART support devices with 9 •SPI uses push-pull and hence wires, Clock & Bidirectional
Advantages pin connector (PC DB-9). It is higher data rates and longer Data. But it is half duplex
also referred as RS232 ranges are possible.
interface. • less power than I2C

(*) I2C sends devise and register address together with data serially (only two wire required) while SPI uses
extra CS (Chip Select) wiring which number of wire depends on number of slaves.

15 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

USB (Universal Serial Bus)


USB in LPC2148 is a USB 2.0 Full Speed specification; it can connect up to 127 devises.
However, it is more complex than the former 3 and it needs driver software development to use.
USB device can transfer data on the bus without any request on the host computer. USB
transfer the data different modes; first one is slow speed mode 10kbps to 100 kbps; second
one is full speed mode 500kbps to 10mbps, high speed mode 25mbps to 400 mbps. USB
maximum cable length of 4 meters. Read USB specification for more detail.

Other serial commination protocols


There are other serial commination protocols that LPC2148 doesn’t provide dedicated interface
for:
CAN (Controller Area Network) Protocol: CAN protocol is often used for in-vehicle
networking of electronic components

Refer Introduction to CAN or CAN Specification documentation for more detail.


Microwire (μWire): μWire is a subset of SPI. It is synchronous master/slave serial
communication interface.
1-Wire: Asynchronous master/slave half duplex serial
communication bus system. It provides low-speed
data, signaling, and power over a single conductor Pull-up
(two wire, one data and one ground). The difference
between 1-Wire and I2C is that I2C supports
multiple master, high speed but shorter cable
distance; I2C devices requires have 4 wires (GND
& power plus SCK clock & SDA data), whereas 1- Fig: 1-wire bus system
wire needs only 2 (data and GND) and draws
power from data line because both uses a pull-up resistor on the data line.
One can implement 1-wire using UARS

Fig: 1-Wire implementation using UART

In this lab, however, we will cover only UART for its simplicity and wide usage.

16 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

17 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

UART
UART (Universal Asynchronous Receiver Transmitter) is a serial communication which provide
a cost effective simple and reliable communication between one microcontroller to another or
between a microcontroller and PC. It is also called RS-232 (except for logic level mismatch).
In UART there is no synchronizing clock, however
any rising or falling edge can be used to sync the
communicating devises; to the worst, the data being
sent could be all zeros, in this case a logic 1 stop bit
and a logic 0 start bit creates falling edge for sync.

If synchronization is required, one can use USART (Universal Synchronous/Asynchronous


Receiver/Transmitter) protocol adding extra clock signal line. The following figure depicts
the USART protocol data flow.

Fig: USART protocol data flow.

Baud rate
Baud rate is the number of symbols transmitted per second. If number of bits per symbol (baud)
is one, then baud rate and bit rate (bps) will be the same. If number of bits per symbol is say
two, then baud rate will be half of bit rate; bits per symbol depends on modulation schemes.
Baud rate doesn’t refer to the actual data transfer rate. In a protocol frame, the data is called
the payload and non-data bits are known as the overhead. Overload includes bits representing
source address, destination address, error detection and correction codes, and other
information or control bits. Hence baud rate refers to the rate for the whole frame, payload and
overload.
One of very important requirement to communicate using UART is to configure both ends to
use the same baud rate out of the standard baud rates: 1200, 2400, 4800, 9600, 19200, 38400,
57600, 115200, 230400, etc. (bauds). 9600 is usually used in embedded systems.

Interfacing PC to MCU using UART


Most desktop computers come with serial port (DB-9) which uses 9 RS-232 version of
serial I/O standard. In RS232, high and low bits are represented by flowing voltage
ranges:
Bit Voltage Range (in V)
0 +3 +25
1 -25 -3

18 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

The range -3V to +3V is undefined in RS-232. The TTL and


CMOS standards came a long time after the RS-232 standard
was set. Due to this reason RS-232 voltage levels are not
compatible with TTL and CMOS logics. Therefore, you need
a voltage converter while connecting an RS-232 to
Fig: DB-9 pins
microcontroller system. This converter converts
the microcontroller output level to the RS-232 1 2 3 4 5
voltage levels, and vice versa. IC MAX232 is 6 7 8 9
commonly used for this purpose.
The simplest connection between a PC and
microcontroller requires a minimum of three pins,
RxD (receiver, pin2), TxD (transmitter, pin3) and
ground (pin5) of the serial port of computer (DB-
9). While interfacing two serial devises, make sure
to cross the RX and TX lines the between serial
devices once.
Unfortunately, new computers don’t come with serial port; in this case one can use a USB to
UART Bridge ICs to interface MCUs to laptops.

UART in LPC2148
There are two UART modules in LPC2148, UART0 and UART1.
Both UART0 & UART1 blocks internally have a 16-byte FIFO structure to hold the Rx and Tx
data in 2 registers each THR (Transmit Holding Register) and TSR (Transmit Shift Register).
When we Data to be sent is write into THR, it is then transferred to TSR which assembles the
data to be transmitted via Tx Pin.
Similarly, Rx has RSR (Receive Shift Register) and RBR (Receive Buffer Register). When a
valid data is Received at Rx Pin, it is first assembled in RSR and then passed in to Rx FIFO
which can be then accessed via RBR
UARTx pin description
Pin UART0 UART1 Type Description
RXD: P0.1 P0.9 Input Serial Input. Serial receive data.
TXD: P0.0 P0.9 Output Serial Output. Serial transmit data.

UART1 is identical to UART0, with the addition of a modem interface hence has 6 additional pins.

Registers for UART

19 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

U0DLL and U0DLM – Divisor Latch registers:


The UART0 Divisor Latch is part of the UART0 Fractional Baud Rate Generator and holds the
value used to divide the clock supplied by the fractional prescaler in order to produce the baud
rate clock, which must be 16x the desired baud rate. These register together form a 16-bit
divisor value “[U0DLM:U0DLL] “. Since these form a divisor value and division by zero is
invalid, the starting value should be 0x0001.
U0FDR – Fractional Divider Register:
The UART0 Fractional Divider Register (U0FDR) controls the clock pre-scaler for the baud rate
generation and can be read and written at user’s discretion. This pre-scaler takes the APB clock
and generates an output clock per specified fractional requirements.
Important: If the fractional divider is active (DIVADDVAL > 0) and DLM = 0, the value of the
DLL register must be 3 or greater.
Bit [3 to 0] DIVADDVAL: This is the prescale divisor value. If this value is 0 then
fractional baud rate generator won’t have any effect on UART
Baud rate.
Bit [7 to 4] MULVAL: This is prescale multiplier value. Even if fractional baud rate
generator is not used the value in this register must be more
than or equal to 1 else UART0 will not operate properly.
Bit [31 to 8] reserved.

 0 < MULVAL ≤ 15; 0 < DIVADDVAL≤ 15; PCLK is the peripheral clock
Example 2: Using UART0 baud rate formula from above, it can be determined that system

20 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

with PCLK = 20 MHz, U0DL = 93 (U0DLM = 0x00 and U0DLL = 0x5D),


DIVADDVAL = 2 and MULVAL = 5 will enable UART0 with UART0 baud rate =
9600 bauds. Refer manual for table of baud rate generation.
Refer lookup table in LPC2148 manual for generation of different bauds rates (pp 151 Rev.4)
U0FCR – FIFO Control Register:
The U0FCR controls the operation of the UART0 Rx and TX FIFOs. Bit 0 – FIFO Enable: 1 to
Enable both Rx and Tx FIFOs and 0 to disable.
Bit 1 Rx FIFO Reset : Writing a 1 will clear and reset Rx FIFO.
Bit 2 Tx FIFO Reset : Writing a 1 will clear and reset Tx FIFO.
Bits [7 to 6] : RX Trigger Level Used to determine that how many UART0 Rx FIFO
characters must be written before an interrupt is activated.
[00] (i.e trigger level 0) for 1 character.
[01] (i.e trigger level 1) for 4 characters.
[10] (i.e trigger level 2) for 8 characters.
[11] (i.e trigger level 3) for 14 characters.
Others bits are reserved.
U0LCR – Line Control Register:
The U0LCR determines the format of the data character that is to be transmitted or received.
Bit [1 to 0]Word Length Select: Used to select the length of an individual data
chunk. [00] for 5 bit character length. Similarly [01] , [10] , [11]
for 6 , 7 , 8 bit character lengths respectively.
Bit 2 Stop bit select: 0 for using 1 stop bit and 1 for using 2 stop bits.
Bit 3 Parity Enable: 0 to disabled parity generation & checking and 1 to
enable it.
Bit [5 to 4] Parity Select: [00] to Odd-parity, [01] for Even-parity, [10] for forced “1”
(Mark) parity and [11] for forced “0”(Space) parity.
Bit 6 Break Control: 0 to disable break transmission and 1 to enable it. TxD
pin will be forced to logic 0 when this bit is 1!
Bit 7 Divisor Latch Access bit: 0 to disable access to divisor latches and 1
to enable access.
U0LSR – Line Status Register:
The U0LSR is a read-only register that provides status information on the UART0 TX and RX blocks

Bit 0 Receiver Data Ready(RDR): 0 means U0RBR is empty (i.e. Rx FIFO is


empty) and 1 means U0RBR contains valid data.
Bit 1 Overrun Error(OE): 0 means Overrun hasn’t occurred and 1 means Overrun
has occurred. Overrun is the condition when RSR (Receive Shift
Register) [See note 1] has new character assembled but the RBR
FIFO is full and the new assembled character is eventually lost since
no data is written into FIFO if its full. (Note: Reading U0LSR clears
this bit)
Bit 2 Parity Error(PE): 0 mean no parity error and 1 mean a parity error has
occurred. When the value of the parity bit in the received character is
in wrong state then a parity error occurs. (Note: Reading U0LSR

21 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

clears this bit)


Bit 3 Framing Error(FE): 0 means no framing error has occurred and 1 means
that a framing error has taken place. Framing error occurs when the
stop bit of a received character is zero. (Note: Reading U0LSR
clears this bit)
Bit 4 Break Interrupt: 0 means no Break Interrupt occurs and 1 means that it has
occurred. A Break Interrupt occurs when the RxD line is pulled low
(i.e. all 0s) i.e. held in spacing state for 1 full character after which Rx
Block goes into Idle state. Rx Block gets back to active state when
RxD pin is pulled high (i.e. all 1s) i.e. held in marking state for 1 full
character. (Note: Reading U0LSR clears this bit)
Bit 5 Transmit Holding Register Empty(THRE) : 0 means U0THR contains valid
data and 1 means its empty.
Bit 6 Transmitter Empty (TEMT): 0 means U0THR and/or U0RSR contains valid
data and 1 means that both U0THR and U0RSR are empty.
Bit 7 Error in RX FIFO(RXFE): 0 means that U0RBR has no Rx Errors or Rx FIFO
is disabled (i.e. 0th bit in U0FCR is 0) and 1 means that U0RBR has
at least one error. (Note: This bit is cleared only if U0LSR is read and
there are no other subsequent errors in Rx FIFO else this bit stay 1)
U0TER – Transmit Enable Register:
This register is used to enable UART transmission. When bit-7 (i.e. TXEN) is set to 1 Tx block will be
enabled and will keep on transmitting data as soon as its ready. If bit-7 is set to 0 then Tx will stop
transmission. Other bits are reserved.

U0IER – Interrupt Enable Register:


Set a bit to 0 to disable and 1 to enable the corresponding interrupt.
Bit 0 RBR Interrupt Enable
Bit 1 THRE Interrupt Enable
Bit 2 RX Line Status Interrupt Enable
Bit 3 ATBOInt Enable
Bit 4 ATEOInt Enable
Where ATBOInt = Auto Baud Time-Out Interrupt, ATEO = End of Auto Baud Interrupt and rest of
the bits are reserved.
U0IIR – Interrupt Identification Register:
Refer User Manual when in doubt. In some application the usage of this register might get a bit
complicated.
Bit 0 Interrupt Pending: 0 means atleast one interrupt is pending, 1 means no
interrupts are pending. Note: This bit is ACTIVE LOW!
Bits [3 to 1] Interrupt Identification: [011] is for Receive Line Status(RLS) ,
[010] means Receive Data Available(RDA) , 110 is for Character
Time-out Indicator(CTI) , [001] is for THRE Interrupt.
Bits [7 to 6] FIFO Enable.
Bit 8 ABEOInt: 1 means Auto Baud Interrupt has successfully ended and 0
otherwise.
Bit 9 ABTOInt: 1 means Auto Baud Interrupt has Timed-out.

22 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Appendix C: Pulse Width Modulation (PWM)

What is PWM
Pulse Width Modulation (PWM), a type of digital signal, is a technique that modulates the width
of a rectangular pulse wave in order to get a variation in the average value of the resulting wave
in a fixed period of time and having fixed frequency.
PWM is a powerful technique for controlling analog circuits with a microprocessor's digital
outputs. PWM is employed in a wide variety of applications, ranging from measurement and
communications to power control and conversion.
power control
In power control application, PWM is used to control the amount of power delivered to a load
without incurring the losses that would result from linear power delivery by resistive means. For
example, to control power delivered to LEDs, you can use variable current limiting or voltage
divider resistor which dissipate power while controlling power delivered to LEDs; however, if
you use PWM this power dissipation will no longer be there. Motor speed control is also another
power control application. In this lab we will focus on power control application aspect of PWM.
Communication
In communication, the widths of the pulses are used to encode specific data values. For
example, one may encode ‘0’ as 25% duty cycle signal and ‘1’ as 75% duty cycle; this may
have synchronization advantage over UART which encodes ‘0’ as 0V and ‘1’ as 5V while
transmitting continuous ‘0’s and very close to Manchester Encoding (that your LAN cables use)
in which ‘0’ is encoded with 5v to 0v transition and the reverse for ‘1’.
Voltage Regulation
In voltage regulation (as in switched-mode power supply, the one your desktop PC power
supply uses), PWM is used to maintain constant output voltage by controlling an inverter by
varying duty cycle based on feedback from the output.
In the graphic below, you can see PWM signals with different duty cycle all representing a fixed
frequency square wave signal; the green lines represent a regular time period.
𝑡𝑜𝑛
DutyCycle = × 100% ; 𝑇 = 1/𝑓
𝑇

RMS of the sinusoidal signal has same


value as average of its corresponding
PWM signal.

23 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

PWM in LPC2148
LPC2148 has 6 PWM output pins which can be used as 6-Single edged or 3-Double edged.
There as seven-match registers to support these 6-PWM output signals. It uses a 32-bit
Timer/Counter which can be used as a standard timer (third timer) if the PWM mode is not
enabled.
Below block diagram shows the PWM pins and the associated Match (Duty Cycle) registers.

PWM Port Pin Functions Associated PINSEL Corresponding


Channel Pin Register Match Register
PWM_1 P0.0 0-GPIO, 1-TXD0, 2-PWM1, 0,1 bits of PINSEL0 PWMMR1

PWM_2 P0.7 0-GPIO, 1-SSEL0, 2-PWM2, 3-EINT2 14,15 bits of PINSEL0 PWMMR2

PWM_3 P0.1 0-GPIO, 1-RXD0, 2-PWM3, 3-EINT0 2,3 bits of PINSEL0 PWMMR3

PWM_4 P0.8 0-GPIO, 1-TXD1, 2-PWM4, 16,17 bits of PINSEL0 PWMMR4

PWM_5 P0.21 0-GPIO, 1-PWM5, 2-CAP1.3, 10,11 bits of PINSEL1 PWMMR5

PWM_6 P0.9 0-GPIO, 1-RXD1, 2-PWM6, 3-EINT3 18,19 bits of PINSEL0 PWMMR6

Source: https://www.arduino.cc/en/tutorial/PWM

PWM Registers
The below table shows the registers associated with LPC2148 PWM.

REGISTER DESCRIPTION
PWM Interrupt Register. The PWMIR can be written to clear interrupts. The
PWMIR PWMIR can be read to identify which of the possible interrupt sources are
pending.. Writing Logic-1 will clear the corresponding interrupt.
Timer Control Register: The PWMTCR is used to control the Timer Counter
PWMTCR functions(enable/disable/reset).
Timer Counter: The 32-bit TC is incremented every PR+1 cycles of PCLK.
PWMTC The PWMTC is controlled through the PWMTCR.

Prescaler Register: This is used to specify the Prescaler value for


PWMPR incrementing the PWMTC.
Prescale Counter: The 32-bit PC is a counter which is incremented to the
PWMPC value stored in PR. When the value in PR is reached, the TC is incremented.
Match Control Register: The PWMMCR is used to control the resetting of
PWMMCR PWMTC and generating of interrupt whenever a Match occurs.

PWMMR0 Match Register: This register hold the max cycle Time(Ton+Toff).

PWMMR1- Match Registers: These registers holds the Match value(PWM Duty) for
PWMMR6 corresponding PWM channels(PWM1-PWM6).

PWM Control Register: PWM Control Register. Enables PWM outputs and
PWMPCR selects PWM channel types as either single edge or double edge controlled.

PWMLER Load Enable Register: Enables use of new PWM values once the match

24 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

occurs.
Refer LPC2148 user manual pp 263 for detail of these registers.

PWMTCR
31:4 3 2 1 0
Reserved PWM Enable Reserved Counter Reset Counter Enable

Bit 0 – Counter Enable


This bit is used to Enable or Disable the PWM Timer and PWM Prescalar Counters
0- Disable the Counters
1- Enable the Counter incrementing.

Bit 1 – Counter reset


This bit is used to clear the PWM Timer and PWM Prescaler Counter values.
0- Do not Clear.
1- The PWM Timer Counter and the PWM Prescale Counter are synchronously reset on the
next positive edge of PCLK.

Bit 3 – PWM Enable


Used to Enable or Disable the PWM Block.
0- PWM Disabled
1- PWM Enabled

PWMMCR
31:21 20 19 18 - 2 1 0

Reserved PWMMR6S PWMMR6R PWMMR6I - PWMMR0S PWMMR0R PWMMR0I

PWMMRxI
This bit is used to Enable or Disable the PWM interrupts when the PWMTC matches
PWMMRx (x:0-6)
0- Disable the PWM Match interrupt
1- Enable the PWM Match interrupt.

PWMMRxR
This bit is used to Reset PWMTC whenever it Matches PWMRx(x:0-6)
0- Do not Clear.
1- Reset the PWMTC counter value whenever it matches PWMRx.

PWMMRxS
This bit is used to Stop the PWMTC,PWMPC whenever the PWMTC matches
PWMMRx(x:0-6).
0- Disable the PWM stop o match feature
1- Enable the PWM Stop feature. This will stop the PWM whenever the PWMTC reaches
the Match register value.

PWMPCR

25 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

31:15 14-9 8-7 6-2 1-0


Unused PWMENA6-PWMENA1 Unused PWMSEL6-PWMSEL2 Unused

PWMSELx
This bit is used to select the single edged and double edge mode form PWMx (x:2-6)
0- Single Edge mode for PWMx
1- Double Edge Mode for PWMx.

PWMENAx
This bit is used to enable/disable the PWM output for PWMx(x:1-6)
0- PWMx Disable.
1- PWMx Enabled.

PWMLER
31-7 6 5 4 3 2 1 0
Unused LEN6 LEN5 LEN4 LEN3 LEN2 LEN1 LEN0

LENx
This bit is used Enable/Disable the loading of new Match value whenever the PWMTC is
reset(x:0-6)
PWMTC will be continously incremented and whenever it reaches the PWMMRO, timer
will be reset depeding on PWMTCR configuraion. Once the Timer is reset the New Match
values will be loaded from MR0-MR6 depending on bits set in this register.
0- Disable the loading of new Match Values
1- Load the new Match values from MRx when the timer is reset

The match register selections for various PWM outputs is shown in Table 246. And a sample
of how PWM values relate to waveform outputs is shown in Figure bellow. This implementation
supports up to N-1 single edge PWM outputs or (N-1)/2 double edge PWM outputs, where N is
the number of match registers that are implemented. PWM types can be mixed if desired.

26 | 2 6
AAiT, SECE
Microcomputers and Interfacing - Lab Set IV - Draft II- Kinde M. 2021

Single Edge

Double Edge

27 | 2 6

You might also like