You are on page 1of 67

Tiva C TM4C123G

Parte 2
Punteros
• Definición
unsigned int * nombrepuntero;

• Asignarle dirección
nombrepuntero = (int *) 0x2000000U;

• Darle valor
*nombrepuntero = 0x20U;

Preprocesadores
#define clock_register (*((unsigned int*) 0x4000u))
Variables con ancho específico
• Incluir librería estándar C99 stdint.h
#include <stdint.h>

int8_t = int 8 bits


uint8_t = unsigned int 8 bits
int16_t = int 16 bits
uint16_t = unsigned int 16 bits
int32_t = int 32 bits
uint32_t = unsigned int 32 bits
Estructuras
Struct Boy{ elementos} boy1, boy2;

Struct Boy{ uint8_t age; uint8_t height; } boy1, boy2;

Struct { uint8_t age; uint8_t height; } boy1, boy2;

Struct Boy{ uint8_t age; uint8_t height; };


Struct Boy boy1, boy2;
Tipo de datos
Typedef

typedef uint8_t weight;


weight Hugo; uint8_t Hugo_weight;
weight Paco; uint8_t Paco_weight;
weight Luis; uint8_t Luis_weight;
Typedef
typedef struct Boy Boy;
Boy boy1, boy2;

typedef struct { uint8_t age; uint8_t height; } Boy;


Boy boy1, boy2;
Operandos Bit Wise
• Son 6: • Ejemplos:
1. AND &
2. OR | #define green 1U << 3
#define bit1 1U << 1
3. EOR ^
4. NOT ~ GPIOF_DATA |= green;
5. SHIFT+L << GPIOF_DIR &= ~(bit1);
6. SHIFT+R >>
Arquitectura
Arquitectura
Memoria
Arquitectura Load-Store Registro
Memoria
1.
Banco de Registros
2.
RAM 120
120 300 420 300
3. 120 + 300 = 420

4.
Banco de Registros R0
R1
• 16 Registros: R2
• 13 Registros de propósito general LR
R3
• 3 Registros de funciones especiales R4
• Registros (R0 – R12) pueden contener datos o GPR R5
direcciones.
R6
• R13 es el Stack Pointer (SP)
R7
• R14 es el Link Register (LR)
R8
• R15 es el Program Counter (PC) R9 HR
R10
• Existen otros registros de funciones especiales: R11
• PSR (APSR, EPSR, IPSR) Program Status Register
R12
• PRIMASK
• FAULTMASK Exception Mask Register SFR R13 SP
• BASEPRI R14 LR
• CONTROL Control Register
R15 PC
Development Tools para la
Tiva C
Development Tools for Tiva C Series MCUs

30-day full 32KB code size 32KB code size Full function.
Eval Kit License function. limited. limited. Onboard emulation
Upgradeable Upgradeable Upgradeable limited

Compiler GNU C/C++ IAR C/C++ RealView C/C++ TI C/C++

Debugger / IDE gdb / Eclipse C-SPY / Embedded µVision CCS/Eclipse-based


Workbench suite

99 USD
personal MDK-Basic (256
Full Upgrade edition / 2800 2700 USD KB) = €2000 (2895 445 USD
USD full USD)
support

JTAG Debugger J-Link, 299 USD U-Link, 199 USD XDS100, 79 USD

TI SW Ecosystem …
Formas de Programar
TivaWare™ for C Series Features
Peripheral Driver Library
 High-level API interface to complete peripheral set
 License & royalty free use for TI Cortex-M parts
 Available as object library and as source code
 Programmed into the on-chip ROM

USB Stacks and Examples Extras


 Wireless protocols
 USB Device and Embedded Host compliant
 IQ math examples
 Device, Host, OTG and Windows-side examples  Bootloaders
 Free VID/PID sharing program  Windows side applications

Ethernet
 lwip and uip stacks with 1588 PTP modifications
 Extensive examples
Graphics Library Sensor Library
 Graphics primitive and widgets  An interrupt driven I2C master driver for
handling I2C transfers
 153 fonts plus Asian and Cyrillic
 A set of drivers for I2C connected sensors
 Graphics utility tools
 A set of routines for common sensor operations
 Three layers: Transport, Sensor and
Processing

ISP Options...
CMSIS Cortex Microcontroller Software
Interface Standard
• La ventaja de utilizar CMSIS, es que es adaptable a cualquier
microcontrolador ARM.
• Documentación
• Directorio de instalación de Keil
C:\Keil_v5\ARM\PACK\ARM\CMSIS\5.4.0\CMSIS\Documentation\index.html
Fuentes de Reloj
Fundamental Clock Sources

Precision Internal Oscillator (PIOSC)


 16 MHz ± 3%
Main Oscillator (MOSC) using…
 An external single-ended clock source
 An external crystal
Internal 30 kHz Oscillator
 30 kHz ± 50%
 Intended for use during Deep-Sleep power-saving modes
Hibernation Module Clock Source
 32,768Hz crystal
 Intended to provide the system with a real-time clock source

SysClk Sources...
System (CPU) Clock Sources
The CPU can be driven by any of the fundamental clocks …
 Internal 16 MHz
 Main
 Internal 30 kHz
 External Real-Time
- Plus -
 The internal PLL (400 MHz) (La TivaC puede operar a máximo 80MHz)
 The internal 16MHz oscillator divided by four (4MHz ± 3%)

Clock Source Drive PLL? Used as SysClk?


Internal 16MHz Yes Yes
Internal 16Mhz/4 No Yes
Main Oscillator Yes Yes
Internal 30 kHz No Yes
Hibernation Module No Yes
PLL - Yes

Clock Tree...
Tiva C Series Clock Tree
Pág. 222 Datasheet

driverLib API SysCtlClockSet() selects:  SYSDIV divider setting


 OSC or PLL
 Main or Internal oscillator
 Crystal frequency GPIO...
Configuración TivaWare Pág. 493
489
 SystCtlClockSet(SYSCTL_SY
SDIV_5 | SYSCTL_USE_PLL |
SYSCTL_XTAL_16MHZ |
SYSCTL_OSC_MAIN);
400MHz / 2 / 5 (Prescaler) = 40 MHz

 Se utilizará un prescaler de 5
 Se utilizará el PLL
 Estará utilizando un reloj
externo de 16 MHz
 Se asignará este reloj al
sistema
Configuración TivaWare Pág. 493
489

16 MHz

5 40 MHz

SystCtlClockSet(SYSCTL_SYSDIV_5 | SYSCTL_USE_PLL | SYSCTL_XTAL_16MHZ | SYSCTL_OSC_MAIN);


GPIOS
Entradas y Salidas
General Purpose IO
Pág. 653 datasheet
General Purpose IO

 Any GPIO can be an interrupt:


 Edge-triggered on rising, falling or both
 Level-sensitive on high or low values
 Can directly initiate an ADC sample sequence or µDMA transfer
 Toggle rate up to the CPU clock speed on the Advanced
High-Performance Bus. ½ CPU clock speed on the Standard.
 5V tolerant in input configuration (No es aconsejable... Se queman fácilmente)
 Programmable Drive Strength (2, 4, 8mA or 8mA with slew rate
control)
 Programmable weak pull-up, pull-down, and open drain
 Pin state can be retained during Hibernation mode

Pin Mux Utility...


Herramienta de configuración de pines

- Hacer una cuenta en www.dev.ti.com

- Seleccionar el Board EK-TM4C123GXL

- Seleccionar herramienta SysConfig

- Configurar pines
Pin Mux Utility
 Allows the user to graphically configure the device pin-out
 Generates source and header files for use with any of the supported IDE’s

- Cuenta en www.dev.ti.com

http://www.ti.com/tool/tm4c_pinmux
Masking...
Advanced Peripheral Bus (APB) vs Advanced High-
Performance Bus (AHB)

Los puertos GPIO pueden accederse


en cada ciclo de reloj utilizando el
AHB, si se utiliza el APB, se acceden
en dos ciclos.

Pero en APB el consumo es menor.


GPIO Address Masking
Each GPIO port has a base address. You can write an 8-bit value directly to this base
address and all eight pins are modified. If you want to modify specific bits, you can use a
bit-mask to indicate which bits are to be modified. This is done in hardware by mapping
each GPIO port to 256 addresses. Bits 9:2 of the address bus are used as the bit mask.

GPIO Port D (0x4005.8000)


The register we want to change is GPIO Port D (0x4005.8000) 00011101
Current contents of the register is:

Write Value (0xEB)


The value we will write is 0xEB:
11101011

Instead of writing to GPIO Port D directly, write to


0x4005.8098. Bits 9:2 (shown here) become a bit-mask …0 0 0 0 0 1 0 0 1 1 0 0 0
for the value you write.

Only the bits marked as “1” in the bit-mask are


changed. 00111011
New value in GPIO Port D (note
that only the red bits were written)

GPIOPinWrite(GPIO_PORTD_BASE, GPIO_PIN_5|GPIO_PIN_2|GPIO_PIN_1, 0xEB);


Note: you specify base address, bit mask, and value to write.
The GIPOPinWrite() function determines the correct address for the mask.
GPIOLOCK ...
Critical Function GPIO Protection
 Six pins on the device are protected against accidental programming:
• PC3,2,1 & 0: JTAG/SWD
• PD7 & PF0: NMI
 Any write to the following registers for these pins will not be stored unless the
GPIOLOCK register has been unlocked:
• GPIO Alternate Function Select register
• GPIO Pull Up or Pull Down select registers
• GPIO Digital Enable register
 The following sequence will unlock the GPIOLOCK register for PF0 using direct
register programming:

HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;


HWREG(GPIO_PORTF_BASE + GPIO_O_CR) |= 0x01;
HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = 0;

 Reading the GPIOLOCK register returns it to lock status

Lab...
Configuración de periféricos
 Antes de llamar a cualquier función de la librería
Driverlib es necesario habilitar el reloj para ese
periférico. Si no se hace de esta forma tendremos una
interrupción de Fault ISR.

 Enable ADC
 Enable GPIO
 Enable UART
 Config ADC
 Config GPIO
 Config UART
Ejemplo de configuración Pág. 275
273

 SysCtlPeripheralEnable(SYSCTL_
PERIPH_GPIOF); (Pág. 509)
 GPIOPinTypeGPIOOutput(GPIO_P
ORTF_BASE, GPIO_PIN_1 |
GPIO_PIN_2 | GPIO_PIN_3);
(Pág. 275)

 De primero habilitamos la señal


del reloj para el Puerto F
 Establecemos que los pines 1, 2 y
3 del Puerto F serán salidas
Comparación

TivaWare
 SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
 GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1);

CMSIS** C**
 SYSCTL->RCGCGPIO = R5;  SYSCTL_RCGCGPIO_R |= R5;
 GPIOF->DIR |= PF1;  GPIO_PORTF_DIR_R |= PF1;
 GPIOF->DEN |= PF1;  GPIO_PORTF_DEN_R |= PF1;

** Se definió lo siguiente: #define PF1 (1U << 1) y #define R5 (1U << 5)


Ejemplo de configuración

PF1, PF2, PF3

GPIO_PORTF_DIR_R

GPIO_PORTF_DEN_R

SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3);
Ejemplo de escritura en el puerto Pág. 287
285
TivaWare
 Encendido
 GPIOPinWrite(GPIO_PORTF_BAS
E, GPIO_PIN_1, GPIO_PIN1);
 Apagado
 GPIOPinWrite(GPIO_PORTF_BAS
E, GPIO_PIN_1, 0X00);

CMSIS**
 Encendido
C**
 GPIOF->DATA |= PF1;  Encendido
 GPIO_PORTF_DATA_R|= PF1;
 Apagado
 GPIOF->DATA &= ~ PF1;  Apagado
 GPIO_PORTF_DATA_R &= ~ PF1;
** Se definió lo siguiente: #define PF1 (1U << 1)
Tiva C TM4C123G
Timers
Timer vs. Contador
• Es el pulso de reloj para que incrementen
• Los usos de los timers:
• Crear delays
• Contar eventos
• Medir tiempo entre eventos
Timers

Systick 12x GPTimers


Systick – System Tick Timer
• Contador de 24 bits
• Down Counter
• Corre de la frecuencia del reloj del sistema
• Es utilizado principalmente para medir tiempo
Systick – System Tick Timer (Pg. 123 y 138)
SYSCTRL • SysTick Control and Status: registro para configurar el reloj,
habilitarlo, habilitar interrupciones, y determinar el estado del
contador.

STRELOAD • SysTick Reload: registro para recargar valor del contador

STCURRENT • SysTick Current value: valor actual del contador


Systick – System Tick Timer (Pg. 123)
Configuración:

1. Programar el valor en el registro STRELOAD

2. Borrar el registro STCURRENT escribiéndole cualquier valor

3. Configurar el registro STCTRL con la operación requerida


Systick – Ejemplo desborde a 1 seg
Clock Speed = 16 MHz

Systick->Load = 16,000,000 - 1 porque empieza a contar desde 0

16 MHz => 16,000,000 ciclos = 1 seg

16,000,000 = 1,000 mS

1mS = 16,000

Systick -> LOAD = 16,000 -1 Cada 1 mS

Systick->Load = tiempo deseado x Frecuencia Reloj - 1 Max 24 bits = 16,777,215


Timers de Propósito General (GP)
• 12 Timers
• 6 normal Timers de 16/32 bits
• 6 wide Timers de 32/64 bits
• Cada Timer tiene dos bloques TimerA y TimerB
Para modo normal:
• TimerA + TimerB = 32 bits modo normal
TIMER1A = 16 bits y TIMER1B = 16 bits
• TimerB + TimerB = 64 bits modo wide TIMER1 = 32 bits

• Individuales: Para modo wide:


TIMERxB = 32 bits y TIMERxB = 32 bits
• 8 bit prescaler normal TIMERx = 64 bits
• 16 bit prescaler wide
Nota: los prescalers solo se pueden utilizar TIMER1A = 16 bit + 8 bit = 24 bit
cuando se utilizan de forma individual TIMER1B = 32 bit + 16 bit = 48 bit
Modos de timers
• One-Shot • Periodic
• Timer deja de contar
VS • Timer sigue contando después del
después del timeout. timeout.
Timer++ Timeout STOP
Timer++ Timeout Reset Timer

• Down Counter VS • Up Counter

n n

0 0
Tamaño de Timer en segundos
16 MHz = 16,000,000 ciclos
• 16 bits = 2^16 = 65,536
65536 x 1 / 16 MHz = 65,536 x ( 6.25x1E-8 ) = 4.096 x1E-3 = 4.096 mSeg

• 32 bits = 2^32 = 4,294,967,296


4,294,967,296 x 1 / 16 MHz = 4,294,967,296 x ( 6.25x1E-8 ) = 268.435 Seg

• 16bits + 8bits prescaler = 2^24 = 16,777,216


16,777,216 x 1 / 16 MHz = 16,777,216 x ( 6.25x1E-8 ) = 1.048 Seg
Registros Involucrados GPTM Registers (pg. 727)
GPTMCFG • GPTM Configuration (16/32 – 32/64 timer)
GPTMCTL • GPTM Control (Configuración, Output Trigger)
GPTMIMR • GPTM Interrupt Mask (Enable/Disable Interrupciones)
GPTMRIS • GPTM RAW Interrupt Status (Estado de Interrupciones)
GPTMICR • GPTM Interrupt Clear (Borrar el bit de estado de ISR)
GPTMTAMATCHR • GPTM Timer A Match (Cargar un Valor de comparación para ISR)
GPTMTAILR • GPTM Timer A Interval Load (Cargar el valor del timeout/inicio)
GPTMTAR • GPTM Timer A (Valor actual / número de flancos)
GPTMTAMR • GPTM Timer A Mode (Up/Down – Periodic/One-shot)
GPTMTAPR • GPTM Timer A Prescale
Pasos para configuración
1. Habilitar el reloj para el bloque del Timer
2. Deshabilitar el Timer antes de cambiar su configuración
3. Seleccionar el modo del timer (16 o 32 bits)
4. Seleccionar modo (One-Shot o Periodic / Up – Down Counter)
5. Establecer el valor de intervalo de tiempo en el registro de carga
6. Borrar la bandera de timeout
7. Habilitar el Timer
8. Esperar a que la bandera del timeout se active
Tiva C TM4C123G
Interrupciones
Nested Vectored Interrupt Controller (NVIC) (pg. 50)(pg. 124)
• Handles exceptions and interrupts
• 8 programmable priority levels, priority grouping
• 7 exceptions (system handlers) and 78 Interrupts
• Automatic state saving and restoring
• Automatic reading of the vector table entry
• Pre-emptive/Nested Interrupts
• Deterministic: always 12 cycles or 6 with tail-chaining

Motor control ISRs (e.g. PWM, ADC)

Communication ISRs (e.g. CAN)

Main application (foreground)


t
Interrupt Latency - Tail Chaining
Highest
Priority IRQ1

IRQ2

PUS PO PUS
Typical processor ISR 1 ISR 2 POP
H P H

Tail-chaining
PUS PO
Cortex-M4 ISR 1 ISR 2
Interrupt handling in H P
HW 12 6 12
Cycles Cycles Cycles

Pre-emption …
Interrupt Latency – Pre-emption
Highest
Priority IRQ1

IRQ2

Typical processor PO PUS PO


ISR 1 ISR 2
P H P

PO PO
Cortex-M4 ISR 1 ISR 2
P P
1- 6 12
12 Cycles
Cycles Cycles

Late arrival...
Interrupt Latency – Late Arrival

Highest IRQ1
Priority

IRQ2

PUS PUS PO PUS PO


Typical processor ISR 1 ISR 2
H H P H P

PUS PO
Cortex-M4 ISR 1 ISR 2
H P
6 12
Cycles Cycles

Interrupt handling...
®
Cortex-M4 Interrupt Handling
Interrupt handling is automatic. No instruction overhead.

Entry
• Automatically pushes registers R0–R3, R12, LR, PSR, and PC onto the stack
• In parallel, ISR is pre-fetched on the instruction bus. ISR ready to start
executing as soon as stack PUSH complete

Exit
• Processor state is automatically restored from the stack
• In parallel, interrupted instruction is pre-fetched ready for execution upon
completion of stack POP

Exception types...
®
Cortex-M4 Exception Types (pg. 103)
Vector Exception Priority Vector Descriptions
Number Type address
1 Reset -3 0x04 Reset
2 NMI -2 0x08 Non-Maskable Interrupt
3 Hard Fault -1 0x0C Error during exception processing
4 Memory Programmable 0x10 MPU violation
Management
Fault
5 Bus Fault Programmable 0x14 Bus error (Prefetch or data abort)
6 Usage Fault Programmable 0x18 Exceptions due to program errors
7-10 Reserved - 0x1C - 0x28
11 SVCall Programmable 0x2C SVC instruction
12 Debug Monitor Programmable 0x30 Exception for debug
13 Reserved - 0x34
14 PendSV Programmable 0x38
15 SysTick Programmable 0x3C System Tick Timer
16 and above Interrupts Programmable 0x40 External interrupts (Peripherals)

Vector
Table...
Tabla 2-9. Interrupts Pg. 104
Tiva C TM4C123G
UART
UART Features (Pg. 893)
• 8 módulos UART
• Separate 16x8 bit transmit and receive FIFOs
• Generador de Baudrate programable (hasta 5Mbps o 10Mbps)
• Auto generation and stripping of start, stop, and parity bits
• Line break generation and detection
• Programmable serial interface
• 5, 6, 7, or 8 data bits
• even, odd, stick, or no parity bits
• 1 or 2 stop bits
• baud rate generation, from DC to processor clock/16
• Soporte 9 bits

Block Diagram...
Block Diagram

Basic Operation...
Puertos (Pg. 1351)
Módulo TX RX
UART0 PA1 PA0
UART1 PB1 PB0
UART2 PD7 PD6
UART3 PC7 PC6
UART4 PC5 PC4
UART5 PE5 PE4
UART6 PD5 PD4
UART7 PE1 PE0
Operación Básica (Tivaware)
• Configuración
1. Enable the UART peripheral, e.g.
SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
2. Set the Rx/Tx pins as UART pins
GPIOPinConfigure(GPIO_PA0_U0RX);
GPIOPinConfigure(GPIO_PA1_U0TX);
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
3. Configure the UART baud rate, data configuration
ROM_UARTConfigSetExpClk(UART0_BASE, ROM_SysCtlClockGet(), 115200,
UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE |
UART_CONFIG_PAR_NONE));
4. Configure other UART features (e.g. interrupts, FIFO)
• Listos para mandar o recibir
• Single register used for transmit/receive
• Blocking/non-blocking functions in driverlib:
UARTCharPut(UART0_BASE, ‘a’);
newchar = UARTCharGet(UART0_BASE);
UARTCharPutNonBlocking(UART0_BASE, ‘a’);
newchar = UARTCharGetNonBlocking(UART0_BASE);

Interrupts...
UART Interrupts
Single interrupt per module, cleared automatically
Interrupt conditions:
• Overrun error
• Break error
• Parity error
• Framing error
• Receive timeout – when FIFO is not empty and no further data is received over a 32-bit period
• Transmit – generated when no data present
• Receive – generated when character is received
Interrupts on these conditions can be enabled individually
Your handler code must check to determine the source
of the UART interrupt and clear the flag(s)
Cálculo Baudrate (Pg. 896)
• Utilizamos la siguiente ecuación

Donde:
• UARTSysClk : es el reloj del sistema
• CLKDiv: Puede ser 8 o 16 según la opción que tengamos configurada
según el bit HSE Si
HSE : 0 ClkDiv :16
• Tenemos dos registros que componen BRD = BRDI + BRDF HSE : 1 ClkDiv : 8
Ejemplo Cálculo Baudrate (Pg. 896)

Baudrate : 9600 baudios


XTAL : 16 MHz
ClkDiv : 16

BRD = 16,000,000 / (16 * 9,600) = 104.1667


• BRDI = 104
• BRDF = UARTFBRD[DIVFRAC] = integer(0.1667 * 64 + 0.5) = 11
Registros Involucrados UART Registers (pg. 905)
UARTDR • UART Data (Buffer)
UARTFR • UART Flag (Banderas relacionadas al funcionamiento)
UARTIBRD • UART Integer Baud-Rate Divisor (Parte entera BRD)
UARTFBRD • UART Fractional Baud-Rate Divisor (Parte Flotante BRD)
UARTLCRH • UART Line Control (Modo: 8bits, paridad, stop bits)
UARTCTL • UART Control (Habilitar módulo, habilitar TX y RX)
UARTCC • UART Clock (Seleccionar reloj )
Pasos para configuración
1. Habilitar el módulo UART RCGCUART (Pg. 344)
2. Habilitar el reloj al módulo GPIO correspondiente (Pg. 340) (ver
tabla 23-5 Pg. 1351)
3. Configurar los Bits del Registro GPIO AFSEL (pg. 671) (ver tabla 23-5
Pg. 1344)
4. Configurar el nivel de corriente del GPIO (pg. 673 y 681)
5. Configurar los campos PMCn en el registro GPIOCTL (pg. 688) (ver
tabla 23-5 Pg. 1351)
Pasos para configuración
6. Calcular los valores para generar el Baudrate deseado.
7. Deshabilitar el módulo UART poniendo en 0 el bit UARTEN del
registro UARTCTL (Pg. 688)
8. Colocar el valor entero del BRD en el registro UARTIBRD
9. Colocar la parte fraccional del BRD en el registro UARTFBRD
10. Colocar los parámetros deseados en el registro UARTLCRH
11. Configurar la fuente de reloj del módulo UART en el registro
UARTCC
12. Habilitar el módulo UART poniendo en 1 el bit UARTEN del registro
UARTCTL
Pasos para Leer y Escribir
Leer:
1. Revisar que la bandera RXFE del registro UARTFR Pg. 911 este en 0
2. Leer el dato del registro de datos UARTDR

Escribir
1. Revisar que la bandera TXFF del registro UARTFR Pg. 911 este en 0
2. Cargar el dato a escribir en el registro de datos UARTDR

You might also like