i2c.c 2.15 KB
Newer Older
1 2
#include "types.h"
#include "board.h"
3
#include "syscon.h"
4

5
#define I2C_DELAY 300
6

7
void mi2c_delay()
8 9 10 11 12
{
    int i;
    for(i=0;i<I2C_DELAY;i++) asm volatile ("nop");
}

13 14 15
#define M_SDA_OUT(i, x) { gpio_out(i2c_if[i].sda, x); mi2c_delay(); }
#define M_SCL_OUT(i, x) { gpio_out(i2c_if[i].scl, x); mi2c_delay(); }
#define M_SDA_IN(i) gpio_in(i2c_if[i].sda)
16

17
void mi2c_start(uint8_t i2cif)
18
{
19 20
  M_SDA_OUT(i2cif, 0);
  M_SCL_OUT(i2cif, 0);
21 22
}

23
void mi2c_repeat_start(uint8_t i2cif)
24
{
25 26 27 28
  M_SDA_OUT(i2cif, 1);
  M_SCL_OUT(i2cif, 1);
  M_SDA_OUT(i2cif, 0);
  M_SCL_OUT(i2cif, 0);
29 30
}

31
void mi2c_stop(uint8_t i2cif)
32
{
33 34 35
  M_SDA_OUT(i2cif, 0);
  M_SCL_OUT(i2cif, 1);
  M_SDA_OUT(i2cif, 1);
36 37
}

38
unsigned char mi2c_put_byte(uint8_t i2cif, unsigned char data)
39 40 41 42 43 44
{
  char i;
  unsigned char ack;

  for (i=0;i<8;i++, data<<=1)
    {
45 46 47
      M_SDA_OUT(i2cif, data&0x80);
      M_SCL_OUT(i2cif, 1);
      M_SCL_OUT(i2cif, 0);
48 49
    }

50 51
  M_SDA_OUT(i2cif, 1);
  M_SCL_OUT(i2cif, 1);
52

53
  ack = M_SDA_IN(i2cif);	/* ack: sda is pulled low ->success.	 */
54

55 56
  M_SCL_OUT(i2cif, 0);
  M_SDA_OUT(i2cif, 0);
57 58 59 60

  return ack!=0;
}

61
void mi2c_get_byte(uint8_t i2cif, unsigned char *data, uint8_t last)
62 63 64 65 66
{

  int i;
  unsigned char indata = 0;

67
  M_SDA_OUT(i2cif, 1);
68
  /* assert: scl is low */
69
  M_SCL_OUT(i2cif, 0);
70 71 72

  for (i=0;i<8;i++)
    {
73
      M_SCL_OUT(i2cif, 1);
74
      indata <<= 1;
75 76
      if ( M_SDA_IN(i2cif) ) indata |= 0x01;
      M_SCL_OUT(i2cif, 0);
77 78
    }

79 80 81 82 83 84 85 86 87 88 89 90 91
  if(last)
  {
    M_SDA_OUT(i2cif, 1);  //noack
    M_SCL_OUT(i2cif, 1);
    M_SCL_OUT(i2cif, 0);
  }
  else
  {
    M_SDA_OUT(i2cif, 0);  //ack
    M_SCL_OUT(i2cif, 1);
    M_SCL_OUT(i2cif, 0);
  }

92 93 94
  *data= indata;
}

95
void mi2c_init(uint8_t i2cif)
96
{
97 98
  M_SCL_OUT(i2cif, 1);
  M_SDA_OUT(i2cif, 1);
99
}
100

101 102 103 104 105 106 107 108 109 110
uint8_t mi2c_devprobe(uint8_t i2cif, uint8_t i2c_addr)
{
  uint8_t ret;
  mi2c_start(i2cif);
  ret = !mi2c_put_byte(i2cif, i2c_addr<<1);
  mi2c_stop(i2cif);

  return ret;
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124
//void mi2c_scan(uint8_t i2cif)
//{
//    int i;
//    
//    //for(i=0;i<0x80;i++)
//    for(i=0x50;i<0x51;i++)
//    {
//     mi2c_start(i2cif);
//     if(!mi2c_put_byte(i2cif, i<<1)) mprintf("found : %x\n", i);
//     mi2c_stop(i2cif);
//  
//    }    
//    mprintf("Nothing more found...\n");
//}