Created
September 17, 2012 05:08
-
-
Save guyc/3735664 to your computer and use it in GitHub Desktop.
Testing driving a SwitecX25 stepper over i2c using an MCP23008 I/O chip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <linux/i2c-dev.h> | |
#include <fcntl.h> | |
#include <string.h> | |
#include <sys/ioctl.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
int main(int argc, char **argv) | |
{ | |
const char *i2cDevice = "/dev/i2c-0"; | |
const int i2cAddress = 0x20; | |
unsigned char buf[2]; | |
unsigned char i; | |
int fd; | |
/* | |
* ref: http://www.kernel.org/doc/Documentation/i2c/dev-interface | |
*/ | |
if ((fd = open(i2cDevice, O_RDWR)) < 0) { | |
printf("Failed to open i2c port\n"); | |
exit(1); | |
} | |
// set address | |
if (ioctl(fd, I2C_SLAVE, i2cAddress) < 0) { | |
printf("Unable to configure i2c address\n"); | |
exit(1); | |
} | |
for (i=0;i<=10;i++) { | |
buf[0] = i; // set register | |
if (write(fd, buf, 1) != 1) { | |
printf("error writing i2c register address\n"); | |
exit; | |
} | |
// I could of course read all 10 registers in one read here instead. | |
if (read(fd, buf, 1) != 1) { // read back data into buf | |
printf("Short read from i2c\n"); | |
exit(1); | |
} | |
printf("Register %u = %u\n", i, buf[0]); | |
} | |
printf("[done]\n"); | |
#define REG_GPIO 0x0A | |
#define REG_IODIR 0x00 | |
buf[0] = REG_IODIR; | |
buf[1] = 0x00; // all pins set to output | |
if (write(fd, buf, 2) != 2) { | |
printf("error writing i2c iodir register\n"); | |
exit; | |
} | |
static unsigned char stateMap[] = {0x9, 0x1, 0x7, 0x6, 0xE, 0x8}; | |
unsigned char state = 0; | |
while (1) { | |
buf[0] = REG_GPIO; | |
buf[1] = stateMap[state]; | |
//printf("state %d bits %u\n", state, buf[1]); | |
if (write(fd, buf, 2) != 2) { | |
printf("error writing i2c gpio register\n"); | |
exit; | |
} | |
usleep(400); | |
state = (state + 1) % 6; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment