1 // SPDX-License-Identifier: GPL-2.0+
8 * SPI Read/Write Utilities
17 /*-----------------------------------------------------------------------
22 # define MAX_SPI_BYTES 32 /* Maximum number of bytes we can handle */
25 #ifndef CONFIG_DEFAULT_SPI_BUS
26 # define CONFIG_DEFAULT_SPI_BUS 0
28 #ifndef CONFIG_DEFAULT_SPI_MODE
29 # define CONFIG_DEFAULT_SPI_MODE SPI_MODE_0
33 * Values from last command.
35 static unsigned int bus;
36 static unsigned int cs;
37 static unsigned int mode;
39 static uchar dout[MAX_SPI_BYTES];
40 static uchar din[MAX_SPI_BYTES];
42 static int do_spi_xfer(int bus, int cs)
44 struct spi_slave *slave;
51 snprintf(name, sizeof(name), "generic_%d:%d", bus, cs);
55 ret = spi_get_bus_and_cs(bus, cs, 1000000, mode, "spi_generic_drv",
60 slave = spi_setup_slave(bus, cs, 1000000, mode);
62 printf("Invalid device %d:%d\n", bus, cs);
67 ret = spi_claim_bus(slave);
70 ret = spi_xfer(slave, bitlen, dout, din,
71 SPI_XFER_BEGIN | SPI_XFER_END);
73 /* We don't get an error code in this case */
78 printf("Error %d during SPI transaction\n", ret);
82 for (j = 0; j < ((bitlen + 7) / 8); j++)
83 printf("%02X", din[j]);
87 spi_release_bus(slave);
89 spi_free_slave(slave);
99 * spi {dev} {num_bits} {dout}
100 * {dev} is the device number for controlling chip select (see TBD)
101 * {num_bits} is the number of bits to send & receive (base 10)
102 * {dout} is a hexadecimal string of data to send
103 * The command prints out the hexadecimal string received via SPI.
106 int do_spi (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
113 * We use the last specified parameters, unless new ones are
117 if ((flag & CMD_FLAG_REPEAT) == 0)
120 mode = CONFIG_DEFAULT_SPI_MODE;
121 bus = simple_strtoul(argv[1], &cp, 10);
123 cs = simple_strtoul(cp+1, &cp, 10);
126 bus = CONFIG_DEFAULT_SPI_BUS;
129 mode = simple_strtoul(cp+1, NULL, 10);
132 bitlen = simple_strtoul(argv[2], NULL, 10);
135 for(j = 0; *cp; j++, cp++) {
138 tmp -= ('A' - '0') - 10;
142 printf("Hex conversion error on %c\n", *cp);
146 dout[j / 2] = (tmp << 4);
153 if ((bitlen < 0) || (bitlen > (MAX_SPI_BYTES * 8))) {
154 printf("Invalid bitlen %d\n", bitlen);
158 if (do_spi_xfer(bus, cs))
164 /***************************************************/
168 "SPI utility command",
169 "[<bus>:]<cs>[.<mode>] <bit_len> <dout> - Send and receive bits\n"
170 "<bus> - Identifies the SPI bus\n"
171 "<cs> - Identifies the chip select\n"
172 "<mode> - Identifies the SPI mode to use\n"
173 "<bit_len> - Number of bits to send (base 10)\n"
174 "<dout> - Hexadecimal string that gets sent"