PCF8574擴展樹莓派io口



由於樹莓派GPIO數量有限,可以通過i2c總線io擴展芯片增加io口數量。

PCF8574零售5塊錢左右,可以擴展出8個io口,挺划算的。

 

PCF8574引腳:

連接到樹莓派:

PCF8574的15腳SDA連接到樹莓派3腳

PCF8574的14腳SCL鏈接到樹莓派5腳

 PCF8574的8腳VSS、16腳VDD可根據實際連接

 注意:A0 A1 A2 是地址選擇引腳,三個腳都接GND時芯片地址是0x20,如果使用多片PCF8574拓展時,可通過控制這三個腳電平高低決定芯片的地址。

 

樹莓派操作:

通過i2cdetect查看i2c設備

sudo i2cdetect -y 1

回車后顯示:

  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: 20 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --

注意:0x20即當前PCF8574芯片地址。

 C語言實現流水燈:

//demo.c
#include <stdio.h> #include <fcntl.h> #include <linux/i2c-dev.h> #include <errno.h> #define I2C_ADDR 0x20 int main (void) { int i,value; int fd; // 打開設備 fd = open("/dev/i2c-1", O_RDWR); if (fd < 0) { printf("Error opening file: %s\n", strerror(errno)); return 1; } // 設置I2C從設備地址 if (ioctl(fd, I2C_SLAVE, I2C_ADDR) < 0) { printf("ioctl error: %s\n", strerror(errno)); return 1; } while(1){ for( i = 0 ; i < 8 ; i++ ){ value = (1<<i); if( write( fd , &value, 1 ) != 1) { printf("Error writing file: %s\n", strerror(errno)); } // 延時500ms usleep(500000); } } return 0; }

編譯:

gcc -o demo demo.c

執行:

sudo ./demo

 

可將二極管接在PCF8574 io腳的任意兩腳驗證。

 

使用wiringPi庫實現流水燈:

(wiringPi庫安裝:http://www.cnblogs.com/wjne/p/3748735.html)

//test.c
#include <stdio.h> #include <wiringPi.h> #include <pcf8574.h> //起始PIN地址,占用 100-107 #define EXTEND_BASE 100 int main (void) { // wiringPi初始化 wiringPiSetup( ); // pcf8574初始化,pcf8574的I2C地址為0x20 pcf8574Setup( EXTEND_BASE, 0x20 ); int i; //設置為輸出狀態 for ( i = 0 ; i < 8 ; i++ ) { pinMode( EXTEND_BASE + i, OUTPUT ); } //流水燈 for (;;) { for( i = 0 ; i < 8; i++) { digitalWrite ( EXTEND_BASE + i, HIGH); delay (500); digitalWrite ( EXTEND_BASE + i, LOW); delay (500); } } return 0 ; }

 編譯:

gcc -o test test.c -l wiringPi

 

執行:

sudo ./test

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM