From d3fb7aae2716b66cd0191d1f749c1a5fe603eb85 Mon Sep 17 00:00:00 2001 From: Davide Bongiovanni Date: Thu, 19 Jan 2017 00:12:31 +0100 Subject: [PATCH] Added argument parse. The I2C address is now passed as an argument on program call. --- RPi/i2c_challenge.c | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/RPi/i2c_challenge.c b/RPi/i2c_challenge.c index 381103d..6b92a05 100644 --- a/RPi/i2c_challenge.c +++ b/RPi/i2c_challenge.c @@ -21,20 +21,43 @@ #include #include -#define I2C_ADDR 0x20 - uint8_t solve_challenge(uint8_t arg) { return (arg >> 3) ^ (arg << 3); } +uint8_t parse_int(const char *s) { // Convert string to hex + uint8_t result = 0; + int c; + if ('0' == *s && 'x' == *(s + 1)) { + s += 2; + while (*s) { + result = result << 4; + if (c = (*s - '0'), (c >= 0 && c <= 9)) result |= c; + else if (c = (*s - 'A'), (c >= 0 && c <= 5)) result |= (c + 10); + else if (c = (*s - 'a'), (c >= 0 && c <= 5)) result |= (c + 10); + else break; + ++s; + } + } + return result; +} + int main(int argc, char *argv[]) { int fd; // Linux filehandle to the i2c device uint8_t challenge; uint8_t response; + uint8_t i2c_addr; + + if (argc != 2) { + printf("Usage: \n\ti2c_challenge "); + return 1; + } + i2c_addr = parse_int(argv[1]); + wiringPiSetup(); - fd = wiringPiI2CSetup(I2C_ADDR); // Initialize the i2c protocol with the address + fd = wiringPiI2CSetup(i2c_addr); // Initialize the i2c protocol with the address if (fd == -1) { // Failed to contact device printf("Can't setup the I2C device\n"); return -1;