This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
EEE527Embedded Systems
Lecture 6 UARTs and applying PPS
Ian McCrum Room 5B18, Tel: 90 366364 voice mail on 6th ringEmail: [email protected] Web site: http://www.eej.ulst.ac.uk
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
Simplified UART block diagram
figure 19-1 (DS61143)
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
Baud Rate setting
In our case this translates to the following expression:U2BREG = (25,000,000 / 4 / 115,200) -1 = 53.25 To decide how to best round out the result, use the reverse formula to calculate the actual baud-rate and determine the percentage error:Error = ((Fpb / 4 / (U2BREG + 1)) – baud rate) / baud rate %
With a value of 53 -> 115,740 Baud with an error of just 0.47%, With a value of 54 -> 113,636 baud, 1.82% error, Both are within the acceptable tolerance range for a standard RS232 port (+/- 2%) .We can therefore define the constant BRATE as:
#define BRATE 53 // 115,200 Bd (BREGH=1)
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
Use Excel to Calculate values
SYS_CLK PB divisor PBCLK Baudrate UxBRG Actual Baudrate Error Actual Baudrate Error =PBCLK/(4*baud) -1' Round Down for Rounded down Round up for Rounded up =PBCLK/(4*(UxBRG+1))'
Number Number Formula Number Formula Formula Formula Formula Formula Formula Formula e.g e.g e.g e.g e.g e.g e.g e.g C8=A8/B8 E8=C8/(4*D8) - 1 =roundown(E8,0) G8=C8/((4*(F8+1)) (G8-D8)/D8 =roundup(E8,0) J8=C8/(4*(I8+1)) (G8-D8)/D8
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
UxSTA register
register 18-2 (DS61168E)
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
ADM_EN (bit 24) 0 = no automatic address detect
ADDR<7:0> (bits 23-16) only matter when bit above is set
UTXISEL<1:0> (bits15-14) 01 = raise interrupt when all chars transmitted
UTXINV (bit 13) 0 = UxTX idle state is ‘1’ (if not in IrDA mode)
URXEN (bit 12) 1 = UARTx receiver is enabled
UTXBRK (bit 11) 0 = send no break {1=send start, 12 ‘0’ and stop}
UTXEN (bit 10) 1 = UARTx transmitter is enabled
UTXBF (bit 9) 1 = Transmit buffer is full {0 = room for at least 1 char}
TRMT (bit 8) 0 = Transmit Shift Register is not empty, tx in progress
URXISEL<1:0> (bit 7-6) 00 = Int flag is asserted while rx buffer not empty
ADDEN (bit 5) 0 = Address detect mode disabled
RIDLE (bit 4) 0 = Data is being received {1=receiver is idle}
PERR (bit 3) 1 = Parity error detected for current character
FERR (bit 2) 1 = Framing error detected for current character
OERR (bit 1) 1 = Receiver buffer overrun. Can only be cleared in s/w
URXDA (bit 0) 1 = Receive buffer data available, at least one char.
Important BITs of UxSTA
e.g. U2STA = 0x1400;
RB0/PGDRB1/PGC
RB2RB3
RB4
RB7
RB15(AN9)
RB13(AN11)
LED 3LED 2LED 1LED 0
LEDs all via4k7 to base of transistors‘1’ lights LED
BTN2
BTN3
10k seriesResistors and 10k pullups,Switches to ground
VR1
10k Variable resistor 3v3 to 0v, feed to slider via 1k
IC3Supplies temperature as Voltage, MCP9701ASensor, 3 pin TO92
PGCPGDMCLR 3V3 0V
ICSP to PICKIT3Programmer
Pin 1
RB5/USBID (for USB OTG)
VBUS
D-/RB11
D+/RB10
VCAP
VUSB
VDD
AVDD
VSS
VSS
AVSS
RA2/OSC1
RA3/OSC2To 8MHz XTAL Via 680R and With 30pF caps
JP3
JP2
JP1
MINI –USBFor power & bootloading
PIC32MX250F128B28 PIN DIL PACKAGE
3V3 REG
(SDA1)RB9
(SCL1)RB8
(SCK1)RB14
(SD0)RA4
(SDI)RA1
(CS)RA0
10k
2k22k2
JP5JP6
JP7
DC IN J6
NB, link only One of these
2320
13 28 8 19 27 1
MCLR
18 17 25 12 3 2
24
26
16
11
7654
15
22
21
14
9
10
I2C – or use PPS to set them to UART2 SPI – or use PPS to set them to UART1
Diagram of DP32 board, see full schematic for details!
Further restraints – the DP32 schematic
using PPS you can wire U1RX to RA2,RA4,RB2 ,or RB13. U1TX to RA0,RB3,RB4,RB7 or RB15 U2RX to RA1,RB1,RB5,RB8,RB11 and U2TX to RA3,RB0,RB9,RB10 or RB14 (lose USB or I2C?)
USB – or use PPS to set them to UART1
In the DP32 it is simpler to use UART2 – it shares pins with the I2C pins going to JP4 & 5
Use UART2 and PPS -> U2TX/RPB9U2RX/RPB8 NB
Remove jumpers JP4 & 5And do not insert IC2C, the 8 pin chip
You need to program which pins go where – look up Peripheral Pin Select (PPS) in the datasheet. Also the PPS LOCK and UNLOCK sequences.
Next 4 slides give working code; create a project called UART_1 and either
wire RB8 and RB9 to a USB TTL 3.3V Usart,
or a PICKIT2
or to another DP32 - but wire
RB8_board1 to RB9_board2
And
RB9_board2 to RB8_board2
(on the PC run PUTTY or PICKIT2 v2.6.1 (NOT PICKIT3 s/w!)
Code to demo serial i/o
Modified from http://umassamherstm5.org/tech-tutorials/pic32-tutorials/pic32mx220-tutorials/uart-to-serial-terminal
Exercises• Send data every second to another DP32 and
display it there. (The sending board can be called DP32_1 and the receiver DP32_2)
• Send data only when a pushbutton on DP32_1 is pressed.
• Send data only when the receiving end says it is ready. (hint wire another wire from a spare i/o line from Dp32_2 to DP32_1.
• Use LEDs to show various things
Timer delays• These can use an interrupt – see notes for a 1 second ISR using a flag variable that
main polls. • A simple delay is a “blocking” wait. E.g
#define DELAY 39062 // assuming 40Mhz clock…// In main near startT1CON = 0x8030; // prescale 256:1, 40Mhz=25nSec and 25/256=> 6.4usec
Then for a delay use in your code the following two lines (or put in a function)
TMR1=0;PR1=0xFFFF; // Note the 39062 gives a slight inaccuracy. while(TMR1 < DELAY){;}// wait here for 39062 * 6.4uSecs// you arrive here after a quarter second…(reasonably accurate…)
You can also use the plib library (this code needs modified for the DP32! Do not use as is
Sending and Receiving Data using handshake lines – CTS and RTS (manually)
int putU2( int c){ while ( CTS); // wait for !CTS, clear to send while ( U2STAbits.UTXBF); // wait while Tx buffer full U2TXREG = c; return c;} // putU2
char getU2( void){ RTS = 0; // assert Request To Send !RTS while ( !U2STAbits.URXDA); // wait for a new char to arrive RTS = 1; return U2RXREG; // read char from receive buffer}// getU2
Could be worth adding the lines, just before the return c;
while( !U2STAbits.TRMT);
Serial terminal programs on the PC• Hyperterminal – pre windows 7 in all versions• RealTerm - most excellent, doesn’t work W8• Putty – usually used for network login but can use serial ports, use
this in block 6 lab PCs• MPIDE has a good serial monitor
Use USB to serial convertors if the PC has no serial ports• PICKit 2 can do USB to Serial conversion (but not yet working on the
PICKit 3) Select 3.3V before plugging in.• You can buy USB to Serial convertors, either full RS232 or just TTL
UART. Be careful you do not damage the board! You want 3.3Volts maximum Also several I have used output on pins labelled RCV and input on TX – I had to use a scope to check!
HyperTerminal Setup (windows XP only)
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
RealTerm runs on XP and windows 7 (but not 8)
PUTTY can perform serial terminal functions
When programming the PIC32 and with the UART output connected to Putty many random characters are sent from the PIC to PUTTY.
If the handshaking is left at the default XON/XOFF then PUTTY may receive a XOFF (control-S) from the PIC and you have to quit and restart PUTTY after every programming
Alternatively select the correct handshaking protocol. Such as clicking on the Serial menu option and selecting “NONE” or “HARDWARE RTS/CTS”
Use the Device manager to check the COM port of the USB-TTL adaptor
Ensure the Speed is correct
PICKit2 comes with UART Software – NB NOT the PICKit3 yet, (Oct 2k14)
Wire up the PICKit2 asPICKit Pin 1 - No ConnectionPICKit Pin 2 - 3V3PICKit Pin 3 - GNDPICKit Pin 4 – DP32 Pin 7 (Tx) RB14PICKit Pin 5 - DP32 Pin 10 (Rx) RA1PICKit Pin 6 - No Connection
Start the PICKit 2 application and select Tools-->UART Tool
The PICKit2 has other uses;You can also use the Logic Analyzer Mode.
Click 'Exit UART Tool' and start the Logic ToolSelect 'Analyser' if it is not on by default.Set the Sample rate to 100 Khz and the Trigger to Ch1 \ (falling edge)Click Capture and, When your code sends 'Hello World!' you should see…
Tips and TricksTo re-direct the output stream of the standard C library (stdio.h) functions such as printf() to a UART:
•Define the function: _mon_putc() – Note that a “weak” definition is already provided in the library to send
the default output stream (stdout) to UART2 (convenient for all Explorer16 users).
•Similarly define: _mon_getc() – A default “weak” version is already provided in the library as well,
connecting UART2 receiver to the input stream (stdin).– Weak means that the compiler won’t complain when you define a new
function with the same name, it will simply replace it with the new one you provide.
NOTE•You are responsible for the UART initialization! •Before the first call to any stdio function (printf()…) make sure the UART2 is enabled and the baud rate is set correctly.
Code for serial i/o, allowing printf & puts
By adding a function called _mon_putc() the linker will use it for calls to printf() and puts()
Once you define _mon_putc() any call to printf or puts will just work
I couldn’t get it working for _mon_getc() – I expected gets to work… instead use
code below
From : Di Jasio - Programming 32-bit Microcontrollers in C with additions by Ian McCrum
Device Drivers
• It is good practice to partition big systems into smaller sub-systems
• Each sub-system should do one function, easy to describe (easy to test!)
• The interaction between these “modules” should be minimised, clear and simple.
• For input-output devices this is straightforward (usually)
• We can call these i/o modules “Device Drivers” (these become VERY important when we use embedded Operating Systems)
Using multiple files in C• If working on a large project, you can split it into
several sections – you need only recompile one part if you only change that part.
• The linker bundles together all the object files and any library files that are needed.
• The “make” program can automate this• IDEs use the concept of “projects” to bundle
related files together and ease building a complete executable.
• In the project navigator, ensure your .c files are listed under sources and your .h files under the header file section.
What belongs in a header file?• A good “google topic” as opinions vary, but only when very complex programs are
• http://www0.egr.uh.edu/courses/ece4437/labsupport/Notes/What%20belongs%20in%20a%20header%20file.pdf where Michael Barr refers to his book on “Embedded C Coding Standards”
.h files• DO create one .h file for each module of a system apart from main.c. Include it first in
the .c file before the .c #includes anything else.• DO use “guards” to avoid preprocessing a .h more than once
#ifndef headername_h #define headername_h… rest of .h goes here#endif
• DO include all function prototypes required to use the module. You can “hide” private functions by declaring them static.
• DO NOT add anything that creates code (usually)• SOME say never have variables shared between modules – use functions to access
another module’s variables. Such data hiding and abstraction is good practice – see C++ for better examples.
• Declare global variables as extern in the .h, then declare and initialise them in the .cextern uint8_t varx ; // extern means memory&content is allocated elsewhereuint8_t varx=42; // inside the .c Hence memory gets allocated here
• Every header should include every other header needed to allow compilation of itself but the .c should include whatever other headers that are needed. This is needed where a stuct declaration needs to know information from another .h file. In general we will NOT have to #include other .h files within our .h files
Our Embedded System
• Create ADC.h and ADC.c – initialiseADC() and readADC().• Create UART.h and .c with initialiseUART(), and all other
UART functions.• timer.h & .c initialiseTIMERS()
– SPI.h&.c (week 6)• network.h&.c (we will create a UART or IIC system later)• interrupts.h&.c to initialise interrupts and all ISRs (this is
a marginal design choice as you could put ISRs in main or with each associated peripheral)
• You might (often) have a single setup.h&c to setup all hardware. The method above eases porting code to a new system
Exercises• Write code that prints ADC values to serial port 2. Print
one value per line.• Sample 100 values from the ADC into a buffer and then
output this to the PC when a button has been pushed.• Configure UART1 using PPS and pins RB13 and RA0.
Print from one UART to another. (hint: make sure you only output one character, then wait for it to be received before outputting the next)
• Create UART, ADC and timer device libraries, (uart.c, uart.h, adc.c, adc.h, timer.c and timer.h)