1 // SPDX-License-Identifier: GPL-2.0+
4 * Gerald Van Baren, Custom IDEAS, vanbaren@cideas.com
8 * SPI Read/Write Utilities
17 /*-----------------------------------------------------------------------
22 # define MAX_SPI_BYTES 32 /* Maximum number of bytes we can handle */
26 * Values from last command.
28 static unsigned int bus;
29 static unsigned int cs;
30 static unsigned int mode;
31 static unsigned int freq;
33 static uchar dout[MAX_SPI_BYTES];
34 static uchar din[MAX_SPI_BYTES];
36 static int do_spi_xfer(int bus, int cs)
38 struct spi_slave *slave;
41 #if CONFIG_IS_ENABLED(DM_SPI)
45 snprintf(name, sizeof(name), "generic_%d:%d", bus, cs);
49 ret = spi_get_bus_and_cs(bus, cs, freq, mode, "spi_generic_drv",
54 slave = spi_setup_slave(bus, cs, freq, mode);
56 printf("Invalid device %d:%d\n", bus, cs);
61 ret = spi_claim_bus(slave);
64 ret = spi_xfer(slave, bitlen, dout, din,
65 SPI_XFER_BEGIN | SPI_XFER_END);
66 #if !CONFIG_IS_ENABLED(DM_SPI)
67 /* We don't get an error code in this case */
72 printf("Error %d during SPI transaction\n", ret);
76 for (j = 0; j < ((bitlen + 7) / 8); j++)
77 printf("%02X", din[j]);
81 spi_release_bus(slave);
82 #if !CONFIG_IS_ENABLED(DM_SPI)
83 spi_free_slave(slave);
93 * spi {dev} {num_bits} {dout}
94 * {dev} is the device number for controlling chip select (see TBD)
95 * {num_bits} is the number of bits to send & receive (base 10)
96 * {dout} is a hexadecimal string of data to send
97 * The command prints out the hexadecimal string received via SPI.
100 int do_spi(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
107 * We use the last specified parameters, unless new ones are
113 if ((flag & CMD_FLAG_REPEAT) == 0)
116 mode = CONFIG_DEFAULT_SPI_MODE;
117 bus = dectoul(argv[1], &cp);
119 cs = dectoul(cp + 1, &cp);
122 bus = CONFIG_DEFAULT_SPI_BUS;
125 mode = dectoul(cp + 1, &cp);
127 freq = dectoul(cp + 1, &cp);
130 bitlen = dectoul(argv[2], NULL);
133 for(j = 0; *cp; j++, cp++) {
136 tmp -= ('A' - '0') - 10;
140 printf("Hex conversion error on %c\n", *cp);
144 dout[j / 2] = (tmp << 4);
151 if ((bitlen < 0) || (bitlen > (MAX_SPI_BYTES * 8))) {
152 printf("Invalid bitlen %d\n", bitlen);
156 if (do_spi_xfer(bus, cs))
162 /***************************************************/
166 "SPI utility command",
167 "[<bus>:]<cs>[.<mode>][@<freq>] <bit_len> <dout> - Send and receive bits\n"
168 "<bus> - Identifies the SPI bus\n"
169 "<cs> - Identifies the chip select\n"
170 "<mode> - Identifies the SPI mode to use\n"
171 "<freq> - Identifies the SPI bus frequency in Hz\n"
172 "<bit_len> - Number of bits to send (base 10)\n"
173 "<dout> - Hexadecimal string that gets sent"