1 // SPDX-License-Identifier: GPL-2.0+
4 * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
8 * SPI Read/Write Utilities
16 /*-----------------------------------------------------------------------
21 # define MAX_SPI_BYTES 32 /* Maximum number of bytes we can handle */
25 * Values from last command.
27 static unsigned int bus;
28 static unsigned int cs;
29 static unsigned int mode;
30 static unsigned int freq;
32 static uchar dout[MAX_SPI_BYTES];
33 static uchar din[MAX_SPI_BYTES];
35 static int do_spi_xfer(int bus, int cs)
37 struct spi_slave *slave;
40 #if CONFIG_IS_ENABLED(DM_SPI)
44 snprintf(name, sizeof(name), "generic_%d:%d", bus, cs);
48 ret = _spi_get_bus_and_cs(bus, cs, freq, mode, "spi_generic_drv",
53 slave = spi_setup_slave(bus, cs, freq, mode);
55 printf("Invalid device %d:%d\n", bus, cs);
60 ret = spi_claim_bus(slave);
63 ret = spi_xfer(slave, bitlen, dout, din,
64 SPI_XFER_BEGIN | SPI_XFER_END);
65 #if !CONFIG_IS_ENABLED(DM_SPI)
66 /* We don't get an error code in this case */
71 printf("Error %d during SPI transaction\n", ret);
75 for (j = 0; j < ((bitlen + 7) / 8); j++)
76 printf("%02X", din[j]);
80 spi_release_bus(slave);
81 #if !CONFIG_IS_ENABLED(DM_SPI)
82 spi_free_slave(slave);
92 * spi {dev} {num_bits} {dout}
93 * {dev} is the device number for controlling chip select (see TBD)
94 * {num_bits} is the number of bits to send & receive (base 10)
95 * {dout} is a hexadecimal string of data to send
96 * The command prints out the hexadecimal string received via SPI.
99 int do_spi(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
106 * We use the last specified parameters, unless new ones are
112 if ((flag & CMD_FLAG_REPEAT) == 0)
115 return CMD_RET_USAGE;
118 mode = CONFIG_DEFAULT_SPI_MODE;
119 bus = dectoul(argv[1], &cp);
121 cs = dectoul(cp + 1, &cp);
124 bus = CONFIG_DEFAULT_SPI_BUS;
127 mode = dectoul(cp + 1, &cp);
129 freq = dectoul(cp + 1, &cp);
132 bitlen = dectoul(argv[2], NULL);
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>][@<freq>] <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 "<freq> - Identifies the SPI bus frequency in Hz\n"
174 "<bit_len> - Number of bits to send (base 10)\n"
175 "<dout> - Hexadecimal string that gets sent"