File indexing completed on 2025-05-11 08:24:19
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037 #include <dev/i2c/i2c.h>
0038 #include <fcntl.h>
0039 #include <stdio.h>
0040 #include <stdlib.h>
0041
0042 #include <rtems/shell.h>
0043
0044 static const char rtems_i2cget_shell_usage [] =
0045 "i2cget <I2C_BUS> <CHIP-ADDRESS> <DATA-ADDRESS> [<NR-BYTES>]\n"
0046 "\tGet one or more bytes from an EEPROM like i2c device.\n"
0047 "\tNote that multiple bytes will be read in continuous mode.\n";
0048
0049 static int read_bytes(
0050 int fd,
0051 uint16_t i2c_address,
0052 uint8_t data_address,
0053 uint16_t nr_bytes
0054 )
0055 {
0056 int rv;
0057 uint8_t value[nr_bytes];
0058 i2c_msg msgs[] = {{
0059 .addr = i2c_address,
0060 .flags = 0,
0061 .buf = &data_address,
0062 .len = 1,
0063 }, {
0064 .addr = i2c_address,
0065 .flags = I2C_M_RD,
0066 .buf = value,
0067 .len = nr_bytes,
0068 }};
0069 struct i2c_rdwr_ioctl_data payload = {
0070 .msgs = msgs,
0071 .nmsgs = sizeof(msgs)/sizeof(msgs[0]),
0072 };
0073 uint16_t i;
0074
0075 rv = ioctl(fd, I2C_RDWR, &payload);
0076 if (rv < 0) {
0077 perror("ioctl failed");
0078 } else {
0079 for (i = 0; i < nr_bytes; ++i) {
0080 printf("0x%02x ", value[i]);
0081 }
0082 printf("\n");
0083 }
0084
0085 return rv;
0086 }
0087
0088 static int rtems_i2cget_shell_main(int argc, char *argv[])
0089 {
0090 int fd;
0091 int rv;
0092 const char *bus;
0093 uint16_t chip_address;
0094 uint8_t data_address;
0095 uint16_t nr_bytes;
0096
0097 if (argc < 4 || argc > 5) {
0098 printf(rtems_i2cget_shell_usage);
0099 return 1;
0100 }
0101
0102 errno = 0;
0103 chip_address = (uint16_t) strtoul(argv[2], NULL, 0);
0104 if (errno != 0) {
0105 perror("Couldn't read chip address");
0106 return 1;
0107 }
0108
0109 errno = 0;
0110 data_address = (uint8_t) strtoul(argv[3], NULL, 0);
0111 if (errno != 0) {
0112 perror("Couldn't read data address");
0113 return 1;
0114 }
0115
0116 nr_bytes = 1;
0117 if (argc == 5) {
0118 errno = 0;
0119 nr_bytes = (uint16_t) strtoul(argv[4], NULL, 0);
0120 if (errno != 0) {
0121 perror("Couldn't read number of bytes");
0122 return 1;
0123 }
0124 }
0125
0126 bus = argv[1];
0127 fd = open(bus, O_RDWR);
0128 if (fd < 0) {
0129 perror("Couldn't open bus");
0130 return 1;
0131 }
0132
0133 rv = read_bytes(fd, chip_address, data_address, nr_bytes);
0134
0135 close(fd);
0136
0137 return rv;
0138 }
0139
0140 rtems_shell_cmd_t rtems_shell_I2CGET_Command = {
0141 .name = "i2cget",
0142 .usage = rtems_i2cget_shell_usage,
0143 .topic = "misc",
0144 .command = rtems_i2cget_shell_main,
0145 };