2016年10月9日 星期日

i2c - read / write LED - LP55281


The LP55281 device is a RGB LED driver for handheld devices. Follow the "Device Functional Modes" to bring up the LED.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include "i2c-dev.h" //This is copy form i2c-tools-3.1.2.tar.bz2
#include <sys/ioctl.h>

int main(void)
{
    int file,i;
    int addr = 0x4C;
    char *filename = "/dev/i2c-2";
    char wbuf[4];
    char read_start_buf[1];
    char rbuf[1024] = {0};
    if((file = open(filename, O_RDWR)) < 0)
    {
 perror("Failed to open i2c device.\n");
 return -1;
    }
    if(ioctl(file, I2C_SLAVE, addr) < 0)
    {
        printf("Failed to access bus.\n");
        return -1;
    }
    printf("1=0x%x\n", 0x01 << 7 | 0x01 << 6);
    //reset
    wbuf[0] = 0x60;  //address
    wbuf[1] = 0x00;  //value
    write(file, wbuf, 2);
    //standby
    wbuf[0] = 0x11;
    wbuf[1] = 0x01 << 7;
    write(file, wbuf, 2);
    //delay around 10ms and set EN_BOOST=H
    usleep(1000*12);
    wbuf[0] = 0x11;
    wbuf[1] = 0x01 << 6 | 0x01 << 7;
    write(file, wbuf, 2);
    //delay around 10ms
    usleep(1000*12);
    //Enable EN_RGB1~EN_RGB4
    wbuf[0] = 0x11;
    wbuf[1] = 0x01 << 6 | 0x01 << 7 | 0x0F;
    write(file, wbuf, 2);
    //usleep(1000*12);
    //Normal Mode, Set the preferred value for RED3 (write 3Fh, 7Fh, BFh or FFh to register 06h)
    wbuf[0] = 0x06;
    wbuf[1] = 0x3F;
    write(file, wbuf, 2);
    usleep(1000*12);
    wbuf[0] = 0x06;
    wbuf[1] = 0x0;
    write(file, wbuf, 2);


    //read-1
    read_start_buf[0] = 0x18;
    write(file, read_start_buf, 1); //reposition file pointer to register
    read(file, rbuf, 1); 
    printf("reg=0x%x, val=0x%x\n", read_start_buf[0], rbuf[0]);
    usleep(1000*12);
    //read-2
    int val=0, reg=0x18;
    val = i2c_smbus_read_byte_data(file, reg);
    printf("reg=0x%x, val=0x%x\n", reg, val);

    
    close(file);
}


ref:
1. kernel(十一)I2C
2. i2c_example.c
3. I2C_SLAVE ioctl目的

沒有留言:

張貼留言