I2c register bitwise operations

I am having a spot of bother with converting i2c register manipulations from Arduino to Squirrel. I want to do this:

`c = readByte(i2cAddr, ACCEL_CONFIG);
//  writeRegister(ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5] 
  i2c.write(i2cAddr, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
  i2c.write(i2cAddr, ACCEL_CONFIG, c | Ascale << 3); // Set full scale range for the accelerometer `

That is, read a register, clear the bits I am about to set and only them, then write those bits to their proper value. I am getting hung up with the difference between strings and integers in squirrel and it’s either complaining during run or not changing the register as I want.

I tried something like this:

`// Set accelerometer full-scale range configuration
  local c = i2c.read(i2cAddr, ACCEL_CONFIG, 1);
//  i2c.write(i2cAddr, ACCEL_CONFIG + (c & ~"\\x18")); // Clear AFS bits [4:3]
  i2c.write(i2cAddr, ACCEL_CONFIG + "(c | Ascale << 3)"); // Set full scale range for the accelerometer `

which compiles and runs, but doesn’t show any change to the register.

Please help if you can. Thanks.

I’d do it this way, I think:

`// Set accelerometer full-scale range configuration
local c = i2c.read(i2cAddr, ACCEL_CONFIG, 1);
local i = c[0].tointeger();

// Clear AFS bits [4:3]
i = i & 0xE7;

i2c.write(i2cAddr, ACCEL_CONFIG + i.tochar()); `

What’s the type of ACCEL_CONFIG? This should be the sort of thing you’re looking for:

`const ACCEL_CONFIG="\\x30"; // type string

local s = i2c.read(i2cAddr, ACCEL_CONFIG, 1); // s has type string
local c = s[0]; // c has type integer -- the first (only) byte returned over I2C

// c is an integer, (c & ~0x18) is an integer, so convert it to a
// one-character string to add it to the ACCEL_CONFIG string
i2c.write(i2cAddr, ACCEL_CONFIG + (c & ~0x18).tochar());
i2c.write(i2cAddr, ACCEL_CONFIG + (c | (Ascale<<3)).tochar());`

Peter

Woops, sorry Tony, had this thread sitting about in a tab for ages and didn’t notice you’d already answered.

Peter

Great! Thanks to you both.