Registers

I have a sensor with sample code that uses I2C interface with the Arduino.

In the sample code, there is a routine meant to "wake the sensor up", that addresses several registers. There is also a warning that microcontrollers that have a different AVR may have different registers. Their routine, below, was written for ATmega168, I have a Mega2560. Do I need to make changes to this routine in order to account for the different AVR?

void wakeSensor(){
TWCR &= ~(1<<2);
DDRC |= (1<<4);
PORTC &= ~(1<<4);
delay(1);
PORTC |= (1<<4);
TWCR |= (1<<2);
delay(1);
}

Hi,

Yes, I'm pretty sure it will need to change.

I think that all the code is doing is setting an output to LOW, followed by a short delay, setting the output HIGH and delaying again. The output is pin 4 of the AVR's C port. Presumably this pin was connected to whatever pin on the sensor that wakes it up.

In Arduino style, this would be:

void wakeSensor () {
  Wire.end (); // does this command exist?
  pinMode (sensorWakePin, OUTPUT);
  digitalWrite (sensorWakePin, LOW);
  delay (1);
  digitalWrite (sensorWakePin, HIGH);
  delay (1);
  Wire.begin ();
}

The only line I'm not sure about is " TWCR &= ~(1<<2);". I think it maybe disabling the i2c interface. I don't know what the Arduino command for that is. Logically it would be Wire.end () but I don't see that command listed with the other i2c commands.

Paul

Wire.end (); // does this command exist?

no,

think you can solve it this way (it won't interfere with Wire as far as I can see)

void wakeSensor () 
{
  int pm = getPinMode(sensorWakePin); // not existing -> see below
  pinMode (sensorWakePin, OUTPUT);
  digitalWrite (sensorWakePin, LOW);
  delay (1);
  digitalWrite (sensorWakePin, HIGH);
  delay (1);
  pinMode (sensorWakePin, pm);
}
int getPinMode(uint8_t pin)
{
  uint8_t bit = digitalPinToBitMask(pin);
  uint8_t port = digitalPinToPort(pin);
  volatile uint8_t *reg, *out;

  if (port == NOT_A_PIN) return -1;

  // JWS: can I let the optimizer do this?
  reg = portModeRegister(port);
  out = portOutputRegister(port);

  if ((~*reg & bit) == bit) // INPUT OR PULLUP
  {
    if ((~*out & bit)  == bit) return INPUT;
    else return INPUT_PULLUP;
  }
  return OUTPUT;
}