Class: I2c

Inherits:
Object
  • Object
show all
Defined in:
ext/bonekit/i2c_class.c

Instance Method Summary collapse

Constructor Details

#initialize(address) ⇒ I2c

Returns a new I2c object associated with a given address



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'ext/bonekit/i2c_class.c', line 59

static VALUE I2c_initialize(int argc, VALUE* argv, VALUE self)
{
  if (argc > 1 || argc == 0)  // there should only 1 argument
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
  
  i2c_t * ptr;
  Data_Get_Struct(self, i2c_t, ptr);
  
  int address = NUM2INT(argv[0]);
  
  if(i2c_init(ptr, address) < 0) // check i2c bus and device address
    rb_raise(rb_eArgError, "I2c bus error");
  
  return self;
}

Instance Method Details

#read(n) ⇒ Array

Reads n bytes from the device.



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'ext/bonekit/i2c_class.c', line 81

static VALUE I2c_read(VALUE self, VALUE nBytes)
{
  i2c_t * ptr;
  Data_Get_Struct(self, i2c_t, ptr);
  
  int n = NUM2INT(nBytes);
  uint8_t * buffer = (uint8_t *)calloc(n, sizeof(uint8_t));
  i2c_read(ptr, buffer, n);
  
  VALUE bytes = rb_ary_new2(n);
  
  int i;
  for(i=0;i<n;++i)
    rb_ary_push(bytes, INT2FIX(buffer[i]));
  
  return bytes;
}

#write(Array) ⇒ Object

Write the bytes in Array to the device.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'ext/bonekit/i2c_class.c', line 105

static VALUE I2c_write(VALUE self, VALUE bytes)
{
  i2c_t * ptr;
  Data_Get_Struct(self, i2c_t, ptr);
  
  int n = RARRAY_LEN(bytes);
  uint8_t * buffer = (uint8_t *)calloc(n, sizeof(uint8_t));
  
  int i;
  for(i=0;i<n;++i)
    buffer[i] = NUM2INT(rb_ary_entry(bytes, i));
    
  VALUE nBytes = INT2FIX(i2c_write(ptr, buffer, n));
  
  return nBytes;
}