Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Test for i2c mcp23017 bus expander Antonio Villanueva Segura
- #include <iostream>
- #include <fcntl.h>
- #include <stdlib.h> // exit
- #include <linux/i2c-dev.h>//I2C_SLAVE
- #include <sys/ioctl.h>//ioctl
- #include <unistd.h> //read write usleep
- #define I2C_ADDR 0x20 //Address mcp23017 expander
- #define DEV_I2C "/dev/i2c-0" //device in linux /de
- using namespace std;
- class mcp23017{
- public:
- mcp23017();
- unsigned char I2CRead () ;//Read GPIOA
- void I2CWrite (unsigned char data);//write GPIOB
- private:
- int fd;//file descriptor
- char buffer[2];//buffer[0] register ,buffer[1] data
- int I2COpen();//Try open file descriptor
- void I2CSetup (int fd);//Setup mcp23017
- };
- /*--------------------------------------------------------------------*/
- mcp23017::mcp23017(){
- fd=I2COpen();//Try open file descriptor
- if (fd<0){exit(0);}//fd error !
- I2CSetup (fd);//Setup mcp23017
- }
- /*--------------------------------------------------------------------*/
- int mcp23017 ::I2COpen(){//Try open file descriptor
- fd = open(DEV_I2C, O_RDWR);//open file descriptor
- if (fd < 0) {//test fd
- cout <<"Error opening file: "<<DEV_I2C<<endl;
- return -1;
- }
- if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0) {
- cout <<"ioctl error: "<<I2C_ADDR<<" "<< endl;
- return -1;
- }
- return fd;
- }
- /*--------------------------------------------------------------------*/
- void mcp23017::I2CSetup (int fd){//Setup mcp23017
- buffer[1]=0x00;//Valeur register
- ////Clr.regs.mcp23017 IODIRB(0x01)=0x00 => GPIOB OUTPUT
- for( size_t reg=0x01 ;reg<0x10;reg++){
- buffer[0]=reg;//load register
- write(fd,buffer,2);
- usleep(1000);
- }
- //IODIRA (0x00)=0xFF => GPIOA INPUT
- buffer[0]=0x00;//Register IODIRA
- buffer[1]=0xFF;// Value INPUT
- write(fd,buffer,2);
- }
- /*--------------------------------------------------------------------*/
- unsigned char mcp23017::I2CRead () {//Read GPIOA
- buffer[0]=0x12;//GPIOA
- write(fd,buffer,1);
- read(fd, &buffer[1], 1);
- return buffer[1];
- }
- /*--------------------------------------------------------------------*/
- void mcp23017::I2CWrite ( unsigned char data){//write GPIOB
- buffer[0]=0x13;//GPIOB
- buffer[1]=data;
- write(fd,buffer,2);
- }
- /*--------------------------------------------------------------------*/
- /*--------------------------------------------------------------------*/
- int main (){
- unsigned char data(0);//data for test outs
- unsigned char read(0);//read data from GPIOA
- mcp23017 strac;
- while (true){//Bucle test
- std::cout.flags ( std::ios::right | std::ios::hex | std::ios::showbase );
- std::cout.width (4);
- if (strac.I2CRead()!=read){//only show if I2CRead change !
- cout <<"INPUT GPIOA = " <<(int) (read=strac.I2CRead())<<endl;//Read GPIOA
- }
- usleep(500000);
- strac.I2CWrite (data++);//WRITE GPIOB
- usleep(500000);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement