Skip to content

Commit e715429

Browse files
committed
refactor command with the issue
1 parent fd0e8e4 commit e715429

File tree

1 file changed

+27
-19
lines changed

1 file changed

+27
-19
lines changed

main.c

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -193,34 +193,42 @@ static void command_loop(void)
193193
break;
194194
case S_CMD_O_SPIOP:
195195
{
196-
static uint8_t buf[4096];
196+
uint32_t slen, rlen;
197+
readbytes_blocking(&slen, 3); // Read send length
198+
readbytes_blocking(&rlen, 3); // Read receive length
197199

198-
uint32_t wlen = 0;
199-
readbytes_blocking(&wlen, 3);
200-
uint32_t rlen = 0;
201-
readbytes_blocking(&rlen, 3);
200+
uint8_t tx_buffer[MAX_BUFFER_SIZE]; // Buffer for transmit data
201+
uint8_t rx_buffer[MAX_BUFFER_SIZE]; // Buffer for receive data
202202

203-
sendbyte_blocking(S_ACK);
203+
// Ensure buffer sizes are adequate
204+
if (slen > MAX_BUFFER_SIZE || rlen > MAX_BUFFER_SIZE) {
205+
sendbyte_blocking(S_NAK);
206+
break;
207+
}
204208

205-
cs_select(SPI_CS);
209+
// Read data to be sent (if slen > 0)
210+
if (slen > 0) {
211+
readbytes_blocking(tx_buffer, slen);
212+
}
206213

207-
while (wlen) {
208-
uint32_t cur = MIN(wlen, sizeof buf);
209-
readbytes_blocking(buf, cur);
210-
spi_write_blocking(SPI_IF, buf, cur);
211-
wlen -= cur;
214+
// Perform SPI operation
215+
cs_select(SPI_CS);
216+
if (slen > 0) {
217+
spi_write_blocking(SPI_IF, tx_buffer, slen);
212218
}
219+
if (rlen > 0) {
220+
spi_read_blocking(SPI_IF, 0, rx_buffer, rlen);
221+
}
222+
cs_deselect(SPI_CS);
213223

214-
while (rlen) {
215-
uint32_t cur = MIN(rlen, sizeof buf);
216-
spi_read_blocking(SPI_IF, 0, buf, cur);
217-
sendbytes_blocking(buf, cur);
218-
rlen -= cur;
224+
// Send ACK followed by received data
225+
sendbyte_blocking(S_ACK);
226+
if (rlen > 0) {
227+
sendbytes_blocking(rx_buffer, rlen);
219228
}
220229

221-
cs_deselect(SPI_CS);
230+
break;
222231
}
223-
break;
224232
case S_CMD_S_SPI_FREQ:
225233
{
226234
uint32_t want_baud;

0 commit comments

Comments
 (0)