i2cdev_f405.c 11 KB
Newer Older
Ian McInerney's avatar
Ian McInerney committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
/**
 *    ||          ____  _ __
 * +------+      / __ )(_) /_______________ _____  ___
 * | 0xBC |     / __  / / __/ ___/ ___/ __ `/_  / / _ \
 * +------+    / /_/ / / /_/ /__/ /  / /_/ / / /_/  __/
 *  ||  ||    /_____/_/\__/\___/_/   \__,_/ /___/\___/
 *
 * Crazyflie control firmware
 *
 * Copyright (C) 2011-2012 Bitcraze AB
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * i2cdev.c - Functions to write to I2C devices
 */
#define DEBUG_MODULE "I2CDEV"

#include <stdint.h>
#include <stdbool.h>

#include "i2cdev.h"

#include "nvicconf.h"

#include "FreeRTOS.h"
#include "semphr.h"
#include "task.h"

#include "led.h"
#include "ledseq.h"

#include "debug.h"
#include "cpal_i2c.h"
#include "stm32f40x_i2c_cpal_conf.h"

#define OWN_ADDRESS        0x74
#define I2C_CLOCK_SPEED    400000;

#define I2CDEV_CLK_TS (10 * I2CDEV_LOOPS_PER_US)

#define GPIO_WAIT_FOR_HIGH(gpio, pin, timeoutcycles)\
  {\
    int i = timeoutcycles;\
    while(GPIO_ReadInputDataBit(gpio, pin) == Bit_RESET && i--);\
  }

#define GPIO_WAIT_FOR_LOW(gpio, pin, timeoutcycles) \
  {\
    int i = timeoutcycles;\
    while(GPIO_ReadInputDataBit(gpio, pin) == Bit_SET && i--);\
  }

CPAL_TransferTypeDef  rxTransfer, txTransfer;

xSemaphoreHandle i2cdevDmaEventI2c1;
xSemaphoreHandle i2cdevDmaEventI2c2;
xSemaphoreHandle i2cdevDmaEventI2c3;

/* Private functions */
static bool i2cdevWriteTransfer(I2C_Dev *dev);
static bool i2cdevReadTransfer(I2C_Dev *dev);
static inline void i2cdevRuffLoopDelay(uint32_t us);
static void i2cdevReleaseSemaphoreI2C1(void);
static void i2cdevReleaseSemaphoreI2C3(void);


int i2cdevInit(I2C_Dev *dev)
{
  CPAL_I2C_StructInit(dev);
  dev->CPAL_Mode = CPAL_MODE_MASTER;
  //I2C_DevStructure.wCPAL_Options =  CPAL_OPT_NO_MEM_ADDR;
  dev->CPAL_ProgModel = CPAL_PROGMODEL_DMA;
  dev->CPAL_Direction = CPAL_DIRECTION_TXRX;
  dev->pCPAL_I2C_Struct->I2C_ClockSpeed = I2C_CLOCK_SPEED;
  dev->pCPAL_I2C_Struct->I2C_OwnAddress1 = OWN_ADDRESS;
  dev->pCPAL_TransferRx = &rxTransfer;
  dev->pCPAL_TransferTx = &txTransfer;
  /* Initialize CPAL device with the selected parameters */
  CPAL_I2C_Init(dev);

  vSemaphoreCreateBinary(i2cdevDmaEventI2c1);
  vSemaphoreCreateBinary(i2cdevDmaEventI2c2);
  vSemaphoreCreateBinary(i2cdevDmaEventI2c3);
  
  return true;
}

bool i2cdevReadByte(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                    uint8_t *data)
{
  return i2cdevRead(dev, devAddress, memAddress, 1, data);
}

bool i2cdevReadBit(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                     uint8_t bitNum, uint8_t *data)
{
  uint8_t byte;
  bool status;
  
  status = i2cdevRead(dev, devAddress, memAddress, 1, &byte);
  *data = byte & (1 << bitNum);

  return status;
}

bool i2cdevReadBits(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                    uint8_t bitStart, uint8_t length, uint8_t *data)
{
  bool status;
  uint8_t byte;

  if ((status = i2cdevReadByte(dev, devAddress, memAddress, &byte)) == true)
  {
      uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
      byte &= mask;
      byte >>= (bitStart - length + 1);
      *data = byte;
  }
  return status;
}

bool i2cdevRead(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
               uint16_t len, uint8_t *data)
{
  dev->pCPAL_TransferRx->wNumData = len;
  dev->pCPAL_TransferRx->pbBuffer = data;
  dev->pCPAL_TransferRx->wAddr1 = devAddress << 1;
  dev->pCPAL_TransferRx->wAddr2 = memAddress;

  dev->wCPAL_Options = CPAL_OPT_I2C_NOSTOP_MODE;
  if (memAddress == I2CDEV_NO_MEM_ADDR)
  {
    dev->wCPAL_Options |= CPAL_OPT_NO_MEM_ADDR;
  }
 
  return i2cdevReadTransfer(dev);
}

bool i2cdevRead16(I2C_Dev *dev, uint8_t devAddress, uint16_t memAddress,
               uint16_t len, uint8_t *data)
{
  dev->pCPAL_TransferRx->wNumData = len;
  dev->pCPAL_TransferRx->pbBuffer = data;
  dev->pCPAL_TransferRx->wAddr1 = devAddress << 1;
  dev->pCPAL_TransferRx->wAddr2 = memAddress;
  dev->wCPAL_Options = CPAL_OPT_I2C_NOSTOP_MODE | CPAL_OPT_16BIT_REG;

  return i2cdevReadTransfer(dev);
}

static bool i2cdevReadTransfer(I2C_Dev *dev)
{
  bool status;

  dev->CPAL_Mode = CPAL_MODE_MASTER;
  /* Force the CPAL state to ready (in case a read operation has been initiated) */
  dev->CPAL_State = CPAL_STATE_READY;
  /* Start writing data in master mode */
  status = CPAL_I2C_Read(dev);

  if (status == CPAL_PASS)
  {
    if (dev == I2C1_DEV)
    {
      xSemaphoreTake(i2cdevDmaEventI2c1, M2T(30));
    }
    else if (dev == I2C3_DEV)
    {
      xSemaphoreTake(i2cdevDmaEventI2c3, M2T(30));
    }

    //TODO: Remove spin loop below. It does not work without it at the moment
    while(dev->CPAL_State != CPAL_STATE_READY && dev->CPAL_State != CPAL_STATE_ERROR);
    status = (dev->CPAL_State == CPAL_STATE_READY) || (dev->CPAL_State != CPAL_STATE_ERROR);
  }

  return status;
}

bool i2cdevWriteByte(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                    uint8_t data)
{
  return i2cdevWrite(dev, devAddress, memAddress, 1, &data);
}

bool i2cdevWriteBit(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                    uint8_t bitNum, uint8_t data)
{
    uint8_t byte;
    i2cdevReadByte(dev, devAddress, memAddress, &byte);
    byte = (data != 0) ? (byte | (1 << bitNum)) : (byte & ~(1 << bitNum));
    return i2cdevWriteByte(dev, devAddress, memAddress, byte);
}

bool i2cdevWriteBits(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                     uint8_t bitStart, uint8_t length, uint8_t data)
{
  bool status;
  uint8_t byte;

  if ((status = i2cdevReadByte(dev, devAddress, memAddress, &byte)) == true)
  {
      uint8_t mask = ((1 << length) - 1) << (bitStart - length + 1);
      data <<= (bitStart - length + 1); // shift data into correct position
      data &= mask; // zero all non-important bits in data
      byte &= ~(mask); // zero all important bits in existing byte
      byte |= data; // combine data with existing byte
      status = i2cdevWriteByte(dev, devAddress, memAddress, byte);
  }

  return status;
}

bool i2cdevWrite(I2C_Dev *dev, uint8_t devAddress, uint8_t memAddress,
                uint16_t len, uint8_t *data)
{
  dev->pCPAL_TransferTx->wNumData = len;
  dev->pCPAL_TransferTx->pbBuffer = data;
  dev->pCPAL_TransferTx->wAddr1 = devAddress << 1;
  dev->pCPAL_TransferTx->wAddr2 = memAddress;
  
  if (memAddress != I2CDEV_NO_MEM_ADDR)
  {
    dev->wCPAL_Options &= !CPAL_OPT_NO_MEM_ADDR;
  }
  else
  {
    dev->wCPAL_Options |= CPAL_OPT_NO_MEM_ADDR;
  }

  return i2cdevWriteTransfer(dev);
}

bool i2cdevWrite16(I2C_Dev *dev, uint8_t devAddress, uint16_t memAddress,
                   uint16_t len, uint8_t *data)
{
  dev->pCPAL_TransferTx->wNumData = len;
  dev->pCPAL_TransferTx->pbBuffer = data;
  dev->pCPAL_TransferTx->wAddr1 = devAddress << 1;
  dev->pCPAL_TransferTx->wAddr2 = memAddress;
  dev->wCPAL_Options = CPAL_OPT_I2C_NOSTOP_MODE | CPAL_OPT_16BIT_REG;

  return i2cdevWriteTransfer(dev);
}

static bool i2cdevWriteTransfer(I2C_Dev *dev)
{
  bool status;

  dev->CPAL_Mode = CPAL_MODE_MASTER;
  /* Force the CPAL state to ready (in case a read operation has been initiated) */
  dev->CPAL_State = CPAL_STATE_READY;
  /* Start writing data in master mode */
  status = CPAL_I2C_Write(dev);

  if (status == CPAL_PASS)
  {
    if (dev == I2C1_DEV)
    {
      xSemaphoreTake(i2cdevDmaEventI2c1, M2T(30));
    }
    else if (dev == I2C3_DEV)
    {
      xSemaphoreTake(i2cdevDmaEventI2c3, M2T(30));
    }

    //TODO: Remove spin loop below. It does not work without it at the moment
    while(dev->CPAL_State != CPAL_STATE_READY && dev->CPAL_State != CPAL_STATE_ERROR);
    status = (dev->CPAL_State == CPAL_STATE_READY) || (dev->CPAL_State != CPAL_STATE_ERROR);
  }

  return status;
}

static inline void i2cdevRuffLoopDelay(uint32_t us)
{
  volatile uint32_t delay;

  for(delay = I2CDEV_LOOPS_PER_US * us; delay > 0; delay--);
}

void i2cdevUnlockBus(GPIO_TypeDef* portSCL, GPIO_TypeDef* portSDA, uint16_t pinSCL, uint16_t pinSDA)
{
  GPIO_SetBits(portSDA, pinSDA);
  /* Check SDA line to determine if slave is asserting bus and clock out if so */
  while(GPIO_ReadInputDataBit(portSDA, pinSDA) == Bit_RESET)
  {
    /* Set clock high */
    GPIO_SetBits(portSCL, pinSCL);
    /* Wait for any clock stretching to finish. */
    GPIO_WAIT_FOR_HIGH(portSCL, pinSCL, 10 * I2CDEV_LOOPS_PER_MS);
    i2cdevRuffLoopDelay(I2CDEV_CLK_TS);

    /* Generate a clock cycle */
    GPIO_ResetBits(portSCL, pinSCL);
    i2cdevRuffLoopDelay(I2CDEV_CLK_TS);
    GPIO_SetBits(portSCL, pinSCL);
    i2cdevRuffLoopDelay(I2CDEV_CLK_TS);
  }

  /* Generate a start then stop condition */
  GPIO_SetBits(portSCL, pinSCL);
  i2cdevRuffLoopDelay(I2CDEV_CLK_TS);
  GPIO_ResetBits(portSDA, pinSDA);
  i2cdevRuffLoopDelay(I2CDEV_CLK_TS);
  GPIO_ResetBits(portSDA, pinSDA);
  i2cdevRuffLoopDelay(I2CDEV_CLK_TS);

  /* Set data and clock high and wait for any clock stretching to finish. */
  GPIO_SetBits(portSDA, pinSDA);
  GPIO_SetBits(portSCL, pinSCL);
  GPIO_WAIT_FOR_HIGH(portSCL, pinSCL, 10 * I2CDEV_LOOPS_PER_MS);
  /* Wait for data to be high */
  GPIO_WAIT_FOR_HIGH(portSDA, pinSDA, 10 * I2CDEV_LOOPS_PER_MS);
}

static void i2cdevReleaseSemaphoreI2C1(void)
{
  portBASE_TYPE  xHigherPriorityTaskWoken = pdFALSE;

  xSemaphoreGiveFromISR(i2cdevDmaEventI2c1, &xHigherPriorityTaskWoken);

  if(xHigherPriorityTaskWoken)
  {
   vPortYieldFromISR();
  }
}

static void i2cdevReleaseSemaphoreI2C3(void)
{
  portBASE_TYPE  xHigherPriorityTaskWoken = pdFALSE;

  xSemaphoreGiveFromISR(i2cdevDmaEventI2c3, &xHigherPriorityTaskWoken);

  if(xHigherPriorityTaskWoken)
  {
   vPortYieldFromISR();
  }
}

/**
  * @brief  User callback that manages the I2C device errors.
  * @note   Make sure that the define USE_SINGLE_ERROR_CALLBACK is uncommented in
  *         the cpal_conf.h file, otherwise this callback will not be functional.
  * @param  pDevInitStruct.
  * @param  DeviceError.
  * @retval None
  */
void CPAL_I2C_ERR_UserCallback(CPAL_DevTypeDef pDevInstance, uint32_t DeviceError)
{
  DEBUG_PRINT("Error callback nr: %i\n", (int)DeviceError);
}

/**
  * @brief  Manages the End of Tx transfer event.
  * @param  pDevInitStruct
  * @retval None
  */
void CPAL_I2C_TXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct)
{
  if (pDevInitStruct == I2C1_DEV)
  {
    i2cdevReleaseSemaphoreI2C1();
  }
  else if (pDevInitStruct == I2C3_DEV)
  {
    i2cdevReleaseSemaphoreI2C3();
  }
}

/**
  * @brief  Manages the End of Rx transfer event.
  * @param  pDevInitStruct
  * @retval None
  */
void CPAL_I2C_RXTC_UserCallback(CPAL_InitTypeDef* pDevInitStruct)
{
  if (pDevInitStruct == I2C1_DEV)
  {
    i2cdevReleaseSemaphoreI2C1();
  }
  else if (pDevInitStruct == I2C3_DEV)
  {
    i2cdevReleaseSemaphoreI2C3();
  }
}