Skip to content

Commit 90a884e

Browse files
committed
add read_timeout
1 parent d0aca27 commit 90a884e

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

include/tkey/proto.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,5 @@ void writebyte(uint8_t b);
4040
void write(const uint8_t *buf, size_t nbytes);
4141
uint8_t readbyte();
4242
int read(uint8_t *buf, size_t bufsize, size_t nbytes);
43+
size_t read_timeout(uint8_t *buf, size_t nbytes, uint32_t timeout, uint32_t prescaler);
4344
#endif

libcommon/proto.c

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,14 @@
88
#include <tkey/tk1_mem.h>
99

1010
// clang-format off
11-
static volatile uint32_t* const can_rx = (volatile uint32_t *)TK1_MMIO_UART_RX_STATUS;
12-
static volatile uint32_t* const rx = (volatile uint32_t *)TK1_MMIO_UART_RX_DATA;
13-
static volatile uint32_t* const can_tx = (volatile uint32_t *)TK1_MMIO_UART_TX_STATUS;
14-
static volatile uint32_t* const tx = (volatile uint32_t *)TK1_MMIO_UART_TX_DATA;
11+
static volatile uint32_t* const can_rx = (volatile uint32_t *)TK1_MMIO_UART_RX_STATUS;
12+
static volatile uint32_t* const rx = (volatile uint32_t *)TK1_MMIO_UART_RX_DATA;
13+
static volatile uint32_t* const can_tx = (volatile uint32_t *)TK1_MMIO_UART_TX_STATUS;
14+
static volatile uint32_t* const tx = (volatile uint32_t *)TK1_MMIO_UART_TX_DATA;
15+
static volatile uint32_t* const timer = (volatile uint32_t *)TK1_MMIO_TIMER_TIMER;
16+
static volatile uint32_t* const timer_prescaler = (volatile uint32_t *)TK1_MMIO_TIMER_PRESCALER;
17+
static volatile uint32_t* const timer_status = (volatile uint32_t *)TK1_MMIO_TIMER_STATUS;
18+
static volatile uint32_t* const timer_ctrl = (volatile uint32_t *)TK1_MMIO_TIMER_CTRL;
1519
// clang-format on
1620

1721
uint8_t genhdr(uint8_t id, uint8_t endpoint, uint8_t status, enum cmdlen len)
@@ -94,3 +98,35 @@ int read(uint8_t *buf, size_t bufsize, size_t nbytes)
9498

9599
return 0;
96100
}
101+
102+
size_t read_timeout(uint8_t *buf, size_t nbytes, uint32_t timeout, uint32_t prescaler)
103+
{
104+
int n;
105+
106+
*timer = timeout;
107+
*timer_prescaler = prescaler;
108+
109+
// Start timer
110+
*timer_ctrl |= (1 << TK1_MMIO_TIMER_CTRL_START_BIT);
111+
for (n = 0; n < nbytes; n++) {
112+
113+
for (;;) {
114+
if (*can_rx) {
115+
buf[n] = *rx;
116+
break;
117+
}
118+
119+
if (*timer_status == 1) {
120+
// Timer expired
121+
return n;
122+
}
123+
}
124+
}
125+
126+
// Stop and reset timer
127+
if (*timer_status != 1) {
128+
*timer_ctrl |= (1 << TK1_MMIO_TIMER_CTRL_START_BIT);
129+
}
130+
131+
return n;
132+
}

0 commit comments

Comments
 (0)