/* *i2ctest.c * Raspberry Pi I2C test using wiringPi library. * *Copyright (c) Nahid Alam. *********************************************************** *i2ctest is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * i2ctest is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * *********************************************************** */ #include #include #include #include uint8_t solve_challenge(uint8_t arg) { return (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 if (fd == -1) { // Failed to contact device printf("Can't setup the I2C device\n"); return -1; } delay(1); challenge = wiringPiI2CRead(fd); printf("Received %d\n", challenge); response = solve_challenge(challenge); printf("Sending %d\n", response); delay(100); wiringPiI2CWrite(fd, (uint8_t)response); return 0; }