79 lines
2.3 KiB
Plaintext
79 lines
2.3 KiB
Plaintext
; Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
|
|
;
|
|
; SPDX-License-Identifier: BSD-3-Clause
|
|
;
|
|
|
|
.program iso7816_tx
|
|
.side_set 1 opt
|
|
|
|
; An ISO7816-3 UART transmit program. Adapted from pico-examples/pio/uart_tx/uart_tx.pio
|
|
; OUT pin 0 and side-set pin 0 are both mapped to UART TX pin.
|
|
|
|
; The general idea is
|
|
|
|
pull side 1 [4] ; Assert stop bit, or stall with line in idle state
|
|
set x, 8 side 0 [4] ; Preload bit counter, assert start bit for 5 clocks
|
|
bitloop: ; This loop will run 8 times (8n1 UART)
|
|
out pins, 1 ; Shift 1 bit from OSR to the first OUT pin
|
|
jmp x-- bitloop [3] ; Each loop iteration is 5 cycles.
|
|
|
|
set x, 8 side 1 [4] ; one additional stop bit so we get to GT=12etu
|
|
|
|
|
|
% c-sdk {
|
|
#include "hardware/clocks.h"
|
|
|
|
static inline void iso7816_tx_program_init(PIO pio, uint sm, uint offset, uint pin_tx, uint baud)
|
|
{
|
|
// Tell PIO to initially drive output-high on the selected pin, then map PIO
|
|
// onto that pin with the IO muxes.
|
|
pio_sm_set_pins_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx);
|
|
pio_sm_set_pindirs_with_mask(pio, sm, 1u << pin_tx, 1u << pin_tx);
|
|
pio_gpio_init(pio, pin_tx);
|
|
|
|
pio_sm_config c = iso7816_tx_program_get_default_config(offset);
|
|
|
|
// OUT shifts to right, no autopull
|
|
sm_config_set_out_shift(&c, true, false, 32);
|
|
|
|
// We are mapping both OUT and side-set to the same pin, because sometimes
|
|
// we need to assert user data onto the pin (with OUT) and sometimes
|
|
// assert constant values (start/stop bit)
|
|
sm_config_set_out_pins(&c, pin_tx, 1);
|
|
sm_config_set_sideset_pins(&c, pin_tx);
|
|
|
|
// SM transmits 1 bit per 5 execution cycles.
|
|
float div = (float)clock_get_hz(clk_sys) / (5 * baud);
|
|
printf("baud=%u, div=%f\n", baud, div);
|
|
sm_config_set_clkdiv(&c, div);
|
|
|
|
pio_sm_init(pio, sm, offset, &c);
|
|
pio_sm_set_enabled(pio, sm, true);
|
|
}
|
|
|
|
static inline bool compute_even_parity_bit(uint8_t x)
|
|
{
|
|
x ^= x >> 4;
|
|
x ^= x >> 2;
|
|
x ^= x >> 1;
|
|
return (x) & 1;
|
|
}
|
|
|
|
static inline void iso7816_tx_program_putc(PIO pio, uint sm, uint8_t c)
|
|
{
|
|
uint32_t c_with_parity = c;
|
|
|
|
if (compute_even_parity_bit(c))
|
|
c_with_parity |= 0x100;
|
|
|
|
pio_sm_put_blocking(pio, sm, c_with_parity);
|
|
}
|
|
|
|
static inline void iso7816_tx_program_puts(PIO pio, uint sm, const uint8_t *s, size_t s_len)
|
|
{
|
|
while (s_len--)
|
|
iso7816_tx_program_putc(pio, sm, *s++);
|
|
}
|
|
|
|
%}
|