Before you can use the I2C interface, you may need to use the gpio utility to load the I2C drivers into the kernel:
gpio load i2c
如果訊息如下: 要去 把 device-tree 的功能關掉....
sudo raspi-config ->Advance options -> Device tree disable and I2C enable
sudo reboot
再輸入一次 ...看看能不能用
gpio load i2c
如果訊息如下....就代表可以
他抓到的 裝置為 /dev/i2c-1
如果要確定i2c 的裝置有沒有連上去...可以打
i2cdetect -y 1可以看到i2c 的 device number
可以看到目前i2c 的裝置號碼為 0x53.....(AXDL345)
gpio load i2c 1000
will set the baud rate to 1000Kbps – ie. 1,000,000 bps. (K here is times 1000)
sample code 如下: 以 grove rgb lcd 為例子
==================================================
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <wiringPiI2C.h> // 要多加這個函式庫
#include <string.h>
class rgb_lcd {
public:
rgb_lcd(int fd_rgb, int fd_text);
int FD_RGB_ADDR ;
int FD_TEXT_ADDR ;
void setRGB(int r,int g,int b);
void textCommand(int cmd);
void setText(char* text);
};
rgb_lcd::rgb_lcd(int fd_rgb, int fd_text)
{
FD_RGB_ADDR = fd_rgb;
FD_TEXT_ADDR = fd_text;
}
void rgb_lcd::setRGB(int r ,int g ,int b)
{
wiringPiI2CWriteReg8(FD_RGB_ADDR,0,0);
wiringPiI2CWriteReg8(FD_RGB_ADDR,1,0);
wiringPiI2CWriteReg8(FD_RGB_ADDR,0x08,0xaa);
wiringPiI2CWriteReg8(FD_RGB_ADDR,4,r);
wiringPiI2CWriteReg8(FD_RGB_ADDR,3,g);
wiringPiI2CWriteReg8(FD_RGB_ADDR,2,b);
}
void rgb_lcd::textCommand(int cmd)
{
wiringPiI2CWriteReg8 (FD_TEXT_ADDR, 0x80, cmd) ;
}
void rgb_lcd::setText(char *text)
{
textCommand(0x01); // clear display
delay(50);
textCommand(0x08 | 0x04); // display on, no cursor
textCommand(0x28);// 2 lines
delay(50);
int count = 0;
int row = 0;
//for c in text:
int lens = strlen(text);
for(int i =0;i< lens;i++)
{
char c = text[i];
if ( (c == '\n') || (count == 16))
{
count = 0;
row += 1;
if (row == 2)
break;
textCommand(0xc0);
if(c == '\n')
continue;
}
count++;
wiringPiI2CWriteReg8(FD_TEXT_ADDR,0x40,c);
}
}
int main (void)
{
int fd_rgb, fd_text;
int DISPLAY_RGB_ADDR = 0x62;
int DISPLAY_TEXT_ADDR = 0x3e;
fd_rgb = wiringPiI2CSetup(DISPLAY_RGB_ADDR);
fd_text = wiringPiI2CSetup(DISPLAY_TEXT_ADDR);
if(fd_rgb==-1){
printf("I2C setup error");
return 0;}
if(fd_text==-1){
printf("I2C setup error");
return 0; }
rgb_lcd lcd(fd_rgb,fd_text);
lcd.setRGB(128,128,128);
lcd.setText("Hello world");
}
Reference : http://wiringpi.com/reference/i2c-library/