#ifndef _MRBC_I2C_H #define _MRBC_I2C_H #include "mrbc_api.h" #include "mrubyc.h" #ifdef __cplusplus extern "C" { #endif extern uint8_t * make_output_buffer(mrb_vm *vm, mrb_value v[], int argc, int start_idx, int *ret_bufsiz); #if !MRBC_USE_STRING extern mrbc_value mrbc_array_new_alloc(mrbc_vm *vm, const uint8_t *c_array, int size); #endif #ifdef __cplusplus } #endif void c_i2c_new(mrb_vm *vm, mrb_value *v, int argc){ #if defined(NO_I2C_HANDLE) void* handle = NULL; #else v[0] = mrbc_instance_new(vm, v[0].cls, sizeof(I2C_HANDLE)); int unit_num = 0; if( argc > 0 ) unit_num = GET_INT_ARG(1); MRBC_KW_ARG( unit ); if( MRBC_KW_ISVALID(unit) ) unit_num = mrbc_integer(unit); MRBC_KW_DELETE( unit ); I2C_HANDLE *handle = (I2C_HANDLE *)v[0].instance->data; handle->unit_num = unit_num; #endif int scl=-1,sda=-1; uint32_t freq_num=100000; MRBC_KW_ARG(frequency, freq, scl_pin, sda_pin); if( MRBC_ISNUMERIC(scl_pin) ) scl = MRBC_TO_INT(scl_pin); if( MRBC_ISNUMERIC(sda_pin) ) sda = MRBC_TO_INT(sda_pin); //MRBC_KW_ARG(frequency, freq); if( MRBC_ISNUMERIC(frequency) ) freq_num = MRBC_TO_INT(frequency); if( MRBC_ISNUMERIC(freq) ) freq_num = MRBC_TO_INT(freq); mrbcI2cInit(handle, freq_num, scl, sda); MRBC_KW_DELETE(frequency, freq, scl_pin, sda_pin); //MRBC_KW_DELETE(frequency, freq); } void c_i2c_write(mrb_vm *vm, mrb_value *v, int argc){ #if defined(NO_I2C_HANDLE) void* handle = NULL; #else I2C_HANDLE *handle = (I2C_HANDLE *)v[0].instance->data; #endif uint8_t *buf = 0; int size = 0; if( argc>0 ){ uint8_t adrs = GET_INT_ARG(1); mrbcI2cStart(handle, adrs, 0); if(argc>1){ buf = make_output_buffer( vm, v, argc, 2, &size ); mrbcI2cWrite(handle, buf, size); mrbc_free( vm, buf ); } mrbcI2cStop(handle); } SET_RETURN( mrbc_integer_value(size) ); } void c_i2c_read(mrb_vm *vm, mrb_value *v, int argc){ #if defined(NO_I2C_HANDLE) void* handle = NULL; #else I2C_HANDLE *handle = (I2C_HANDLE *)v[0].instance->data; #endif uint8_t *buf = 0; int size = 0; mrbc_value ret = mrbc_nil_value(); if( argc>1 ){ int adrs = GET_INT_ARG(1); int len = GET_INT_ARG(2); if( argc > 2 ) { mrbcI2cStart(handle, adrs, 0); buf = make_output_buffer( vm, v, argc, 3, &size ); mrbcI2cWrite(handle, buf, size); mrbc_free( vm, buf ); } buf = (uint8_t*) mrbc_alloc(vm, len); mrbcI2cStart(handle, adrs, len); // len>0 in read mode mrbcI2cRead(handle, buf, len); #if MRBC_USE_STRING ret = mrbc_string_new_alloc(vm, buf, len); #else ret = mrbc_array_new_alloc( vm, buf, len); mrbc_free( vm, buf ); #endif } SET_RETURN(ret); } void mrbc_init_class_i2c(void){ mrb_class *i2c = mrbc_define_class(0, "I2C", mrbc_class_object); mrbc_define_method(0, i2c, "new", c_i2c_new); mrbc_define_method(0, i2c, "read", c_i2c_read); mrbc_define_method(0, i2c, "write", c_i2c_write); } #endif