3 * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
5 * SPDX-License-Identifier: GPL-2.0+
9 * SPI Read/Write Utilities
16 /*-----------------------------------------------------------------------
21 # define MAX_SPI_BYTES 32 /* Maximum number of bytes we can handle */
24 #ifndef CONFIG_DEFAULT_SPI_BUS
25 # define CONFIG_DEFAULT_SPI_BUS 0
27 #ifndef CONFIG_DEFAULT_SPI_MODE
28 # define CONFIG_DEFAULT_SPI_MODE SPI_MODE_0
32 * Values from last command.
34 static unsigned int bus;
35 static unsigned int cs;
36 static unsigned int mode;
38 static uchar dout[MAX_SPI_BYTES];
39 static uchar din[MAX_SPI_BYTES];
45 * spi {dev} {num_bits} {dout}
46 * {dev} is the device number for controlling chip select (see TBD)
47 * {num_bits} is the number of bits to send & receive (base 10)
48 * {dout} is a hexadecimal string of data to send
49 * The command prints out the hexadecimal string received via SPI.
52 int do_spi (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
54 struct spi_slave *slave;
61 * We use the last specified parameters, unless new ones are
65 if ((flag & CMD_FLAG_REPEAT) == 0)
68 mode = CONFIG_DEFAULT_SPI_MODE;
69 bus = simple_strtoul(argv[1], &cp, 10);
71 cs = simple_strtoul(cp+1, &cp, 10);
74 bus = CONFIG_DEFAULT_SPI_BUS;
77 mode = simple_strtoul(cp+1, NULL, 10);
80 bitlen = simple_strtoul(argv[2], NULL, 10);
83 for(j = 0; *cp; j++, cp++) {
86 tmp -= ('A' - '0') - 10;
90 printf("Hex conversion error on %c\n", *cp);
94 dout[j / 2] = (tmp << 4);
101 if ((bitlen < 0) || (bitlen > (MAX_SPI_BYTES * 8))) {
102 printf("Invalid bitlen %d\n", bitlen);
106 slave = spi_setup_slave(bus, cs, 1000000, mode);
108 printf("Invalid device %d:%d\n", bus, cs);
112 spi_claim_bus(slave);
113 if(spi_xfer(slave, bitlen, dout, din,
114 SPI_XFER_BEGIN | SPI_XFER_END) != 0) {
115 printf("Error during SPI transaction\n");
118 for(j = 0; j < ((bitlen + 7) / 8); j++) {
119 printf("%02X", din[j]);
123 spi_release_bus(slave);
124 spi_free_slave(slave);
129 /***************************************************/
133 "SPI utility command",
134 "[<bus>:]<cs>[.<mode>] <bit_len> <dout> - Send and receive bits\n"
135 "<bus> - Identifies the SPI bus\n"
136 "<cs> - Identifies the chip select\n"
137 "<mode> - Identifies the SPI mode to use\n"
138 "<bit_len> - Number of bits to send (base 10)\n"
139 "<dout> - Hexadecimal string that gets sent"