Advertisement
manitou

i2c.c maple I2C slave

Apr 9th, 2012
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 24.30 KB | None | 0 0
  1. /******************************************************************************
  2.  * The MIT License
  3.  *
  4.  * Copyright (c) 2010 Perry Hung.
  5.  *
  6.  * Permission is hereby granted, free of charge, to any person
  7.  * obtaining a copy of this software and associated documentation
  8.  * files (the "Software"), to deal in the Software without
  9.  * restriction, including without limitation the rights to use, copy,
  10.  * modify, merge, publish, distribute, sublicense, and/or sell copies
  11.  * of the Software, and to permit persons to whom the Software is
  12.  * furnished to do so, subject to the following conditions:
  13.  *
  14.  * The above copyright notice and this permission notice shall be
  15.  * included in all copies or substantial portions of the Software.
  16.  *
  17.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  18.  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  19.  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  20.  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  21.  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  22.  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  23.  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24.  * SOFTWARE.
  25.  *****************************************************************************/
  26.  
  27. /**
  28.  * @file i2c.c
  29.  * @brief Inter-Integrated Circuit (I2C) support.
  30.  *
  31.  * Currently, only master mode is supported.
  32.  */
  33.  
  34. #include "libmaple.h"
  35. #include "rcc.h"
  36. #include "gpio.h"
  37. #include "nvic.h"
  38. #include "i2c.h"
  39. #include "string.h"
  40. #include "systick.h"
  41.  
  42. static i2c_dev i2c_dev1 = {
  43.     .regs         = I2C1_BASE,
  44.     .gpio_port    = &gpiob,
  45.     .sda_pin      = 7,
  46.     .scl_pin      = 6,
  47.     .clk_id       = RCC_I2C1,
  48.     .ev_nvic_line = NVIC_I2C1_EV,
  49.     .er_nvic_line = NVIC_I2C1_ER,
  50.     .state        = I2C_STATE_DISABLED
  51. };
  52. /** I2C1 device */
  53. i2c_dev* const I2C1 = &i2c_dev1;
  54.  
  55. static i2c_dev i2c_dev2 = {
  56.     .regs         = I2C2_BASE,
  57.     .gpio_port    = &gpiob,
  58.     .sda_pin      = 11,
  59.     .scl_pin      = 10,
  60.     .clk_id       = RCC_I2C2,
  61.     .ev_nvic_line = NVIC_I2C2_EV,
  62.     .er_nvic_line = NVIC_I2C2_ER,
  63.     .state        = I2C_STATE_DISABLED
  64. };
  65. /** I2C2 device */
  66. i2c_dev* const I2C2 = &i2c_dev2;
  67.  
  68. static inline int32 wait_for_state_change(i2c_dev *dev,
  69.                                           i2c_state state,
  70.                                           uint32 timeout);
  71.  
  72. /**
  73.  * @brief Fill data register with slave address
  74.  * @param dev I2C device
  75.  * @param addr Slave address
  76.  * @param rw Read/write bit
  77.  */
  78. static inline void i2c_send_slave_addr(i2c_dev *dev, uint32 addr, uint32 rw) {
  79.     dev->regs->DR = (addr << 1) | rw;
  80. }
  81.  
  82. // thd stuff
  83. static uint8 i2c_slave_mode;  // needs to be in device table TODO
  84. static void i2c_slave_irq_handler(i2c_dev *dev);
  85. static void (*i2c_onSlaveTransmit)(void);
  86. static void (*i2c_onSlaveReceive)(int);
  87.  
  88. /*
  89.  * Simple debugging trail. Define I2C_DEBUG to turn on.
  90.  */
  91. #define I2C_DEBUG
  92. #ifdef I2C_DEBUG
  93.  
  94. struct crumb {
  95.     uint32 event;
  96.     uint32 arg0;
  97.     uint32 arg1;
  98. };
  99.  
  100. #define NR_CRUMBS       128
  101. struct crumb crumbs[NR_CRUMBS];
  102. uint32 cur_crumb = 0;
  103.  
  104. static inline void i2c_drop_crumb(uint32 event, uint32 arg0, uint32 arg1) {
  105.     if (cur_crumb < NR_CRUMBS) {
  106.         struct crumb *crumb = &crumbs[cur_crumb++];
  107.         crumb->event = event;
  108.         crumb->arg0 = arg0;
  109.         crumb->arg1 = arg1;
  110.     }
  111. }
  112. #define I2C_CRUMB(event, arg0, arg1) i2c_drop_crumb(event, arg0, arg1)
  113.  
  114. #else
  115. #define I2C_CRUMB(event, arg0, arg1)
  116. #endif
  117.  
  118.  
  119. enum {
  120.     IRQ_ENTRY           = 1,
  121.     TXE_ONLY            = 2,
  122.     TXE_BTF             = 3,
  123.     STOP_SENT           = 4,
  124.     TEST                = 5,
  125.     RX_ADDR_START       = 6,
  126.     RX_ADDR_STOP        = 7,
  127.     RXNE_ONLY           = 8,
  128.     RXNE_SENDING        = 9,
  129.     RXNE_START_SENT     = 10,
  130.     RXNE_STOP_SENT      = 11,
  131.     RXNE_DONE           = 12,
  132.     ERROR_ENTRY         = 13,
  133. };
  134.  
  135. /**
  136.  * @brief IRQ handler for I2C master. Handles transmission/reception.
  137.  * @param dev I2C device
  138.  */
  139. static void i2c_irq_handler(i2c_dev *dev) {
  140.     i2c_msg *msg = dev->msg;
  141.  
  142.     uint8 read = msg->flags & I2C_MSG_READ;
  143.  
  144.     uint32 sr1 = dev->regs->SR1;
  145.     uint32 sr2 = dev->regs->SR2;
  146.     I2C_CRUMB(IRQ_ENTRY, sr1, sr2);
  147.  
  148.     /*
  149.      * Reset timeout counter
  150.      */
  151.     dev->timestamp = systick_uptime();
  152.  
  153.     /*
  154.      * EV5: Start condition sent
  155.      */
  156.     if (sr1 & I2C_SR1_SB) {
  157.         msg->xferred = 0;
  158.         i2c_enable_irq(dev, I2C_IRQ_BUFFER);
  159.  
  160.         /*
  161.          * Master receiver
  162.          */
  163.         if (read) {
  164.             i2c_enable_ack(dev);
  165.         }
  166.  
  167.         i2c_send_slave_addr(dev, msg->addr, read);
  168.         sr1 = sr2 = 0;
  169.     }
  170.  
  171.     /*
  172.      * EV6: Slave address sent
  173.      */
  174.     if (sr1 & I2C_SR1_ADDR) {
  175.         /*
  176.          * Special case event EV6_1 for master receiver.
  177.          * Generate NACK and restart/stop condition after ADDR
  178.          * is cleared.
  179.          */
  180.         if (read) {
  181.             if (msg->length == 1) {
  182.                 i2c_disable_ack(dev);
  183.                 if (dev->msgs_left > 1) {
  184.                     i2c_start_condition(dev);
  185.                     I2C_CRUMB(RX_ADDR_START, 0, 0);
  186.                 } else {
  187.                     i2c_stop_condition(dev);
  188.                     I2C_CRUMB(RX_ADDR_STOP, 0, 0);
  189.                 }
  190.             }
  191.         } else {
  192.             /*
  193.              * Master transmitter: write first byte to fill shift
  194.              * register.  We should get another TXE interrupt
  195.              * immediately to fill DR again.
  196.              */
  197.             if (msg->length != 1) {
  198.                 i2c_write(dev, msg->data[msg->xferred++]);
  199.             }
  200.         }
  201.         sr1 = sr2 = 0;
  202.     }
  203.  
  204.     /*
  205.      * EV8: Master transmitter
  206.      * Transmit buffer empty, but we haven't finished transmitting the last
  207.      * byte written.
  208.      */
  209.     if ((sr1 & I2C_SR1_TXE) && !(sr1 & I2C_SR1_BTF)) {
  210.         I2C_CRUMB(TXE_ONLY, 0, 0);
  211.         if (dev->msgs_left) {
  212.             i2c_write(dev, msg->data[msg->xferred++]);
  213.             if (msg->xferred == msg->length) {
  214.                 /*
  215.                  * End of this message. Turn off TXE/RXNE and wait for
  216.                  * BTF to send repeated start or stop condition.
  217.                  */
  218.                 i2c_disable_irq(dev, I2C_IRQ_BUFFER);
  219.                 dev->msgs_left--;
  220.             }
  221.         } else {
  222.             /*
  223.              * This should be impossible...
  224.              */
  225.             throb();
  226.         }
  227.         sr1 = sr2 = 0;
  228.     }
  229.  
  230.     /*
  231.      * EV8_2: Master transmitter
  232.      * Last byte sent, program repeated start/stop
  233.      */
  234.     if ((sr1 & I2C_SR1_TXE) && (sr1 & I2C_SR1_BTF)) {
  235.         I2C_CRUMB(TXE_BTF, 0, 0);
  236.         if (dev->msgs_left) {
  237.             I2C_CRUMB(TEST, 0, 0);
  238.             /*
  239.              * Repeated start insanity: We can't disable ITEVTEN or else SB
  240.              * won't interrupt, but if we don't disable ITEVTEN, BTF will
  241.              * continually interrupt us. What the fuck ST?
  242.              */
  243.             i2c_start_condition(dev);
  244.             while (!(dev->regs->SR1 & I2C_SR1_SB))
  245.                 ;
  246.             dev->msg++;
  247.         } else {
  248.             i2c_stop_condition(dev);
  249.  
  250.             /*
  251.              * Turn off event interrupts to keep BTF from firing until
  252.              * the end of the stop condition. Why on earth they didn't
  253.              * have a start/stop condition request clear BTF is beyond
  254.              * me.
  255.              */
  256.             i2c_disable_irq(dev, I2C_IRQ_EVENT);
  257.             I2C_CRUMB(STOP_SENT, 0, 0);
  258.             dev->state = I2C_STATE_XFER_DONE;
  259.         }
  260.         sr1 = sr2 = 0;
  261.     }
  262.  
  263.     /*
  264.      * EV7: Master Receiver
  265.      */
  266.     if (sr1 & I2C_SR1_RXNE) {
  267.         I2C_CRUMB(RXNE_ONLY, 0, 0);
  268.         msg->data[msg->xferred++] = dev->regs->DR;
  269.  
  270.         /*
  271.          * EV7_1: Second to last byte in the reception? Set NACK and generate
  272.          * stop/restart condition in time for the last byte. We'll get one more
  273.          * RXNE interrupt before shutting things down.
  274.          */
  275.         if (msg->xferred == (msg->length - 1)) {
  276.             i2c_disable_ack(dev);
  277.             if (dev->msgs_left > 2) {
  278.                 i2c_start_condition(dev);
  279.                 I2C_CRUMB(RXNE_START_SENT, 0, 0);
  280.             } else {
  281.                 i2c_stop_condition(dev);
  282.                 I2C_CRUMB(RXNE_STOP_SENT, 0, 0);
  283.             }
  284.         } else if (msg->xferred == msg->length) {
  285.             dev->msgs_left--;
  286.             if (dev->msgs_left == 0) {
  287.                 /*
  288.                  * We're done.
  289.                  */
  290.                 I2C_CRUMB(RXNE_DONE, 0, 0);
  291.                 dev->state = I2C_STATE_XFER_DONE;
  292.             } else {
  293.                 dev->msg++;
  294.             }
  295.         }
  296.     }
  297. }
  298.  
  299. void __irq_i2c1_ev(void) {
  300.    if (i2c_slave_mode) i2c_slave_irq_handler(&i2c_dev1);
  301.     else i2c_irq_handler(&i2c_dev1);
  302. }
  303.  
  304. void __irq_i2c2_ev(void) {
  305.    if (i2c_slave_mode) i2c_slave_irq_handler(&i2c_dev2);
  306.     else i2c_irq_handler(&i2c_dev2);
  307. }
  308.  
  309. /**
  310.  * @brief Interrupt handler for I2C error conditions
  311.  * @param dev I2C device
  312.  * @sideeffect Aborts any pending I2C transactions
  313.  */
  314. static void i2c_irq_error_handler(i2c_dev *dev) {
  315.     I2C_CRUMB(ERROR_ENTRY, dev->regs->SR1, dev->regs->SR2);
  316.  
  317.     dev->error_flags = dev->regs->SR2 & (I2C_SR1_BERR |
  318.                                          I2C_SR1_ARLO |
  319.                                          I2C_SR1_AF |
  320.                                          I2C_SR1_OVR);
  321.     if (i2c_slave_mode && (dev->regs->SR1 & I2C_SR1_AF)){
  322.         //  EV3-2: slave transmit stop NACK   thd
  323.         dev->regs->SR1 = 0;
  324.         dev->regs->SR2 = 0;
  325.         i2c_enable_ack(dev);            // write to CR1 to proceed 
  326.         return;
  327.     }
  328.     /* Clear flags */
  329.     dev->regs->SR1 = 0;
  330.     dev->regs->SR2 = 0;
  331.     i2c_stop_condition(dev);
  332.  
  333.  
  334.     i2c_disable_irq(dev, I2C_IRQ_BUFFER | I2C_IRQ_EVENT | I2C_IRQ_ERROR);
  335.     dev->state = I2C_STATE_ERROR;
  336. }
  337.  
  338. void __irq_i2c1_er(void) {
  339.     i2c_irq_error_handler(&i2c_dev1);
  340. }
  341.  
  342. void __irq_i2c2_er(void) {
  343.     i2c_irq_error_handler(&i2c_dev2);
  344. }
  345.  
  346. /**
  347.  * @brief Reset an I2C bus.
  348.  *
  349.  * Reset is accomplished by clocking out pulses until any hung slaves
  350.  * release SDA and SCL, then generating a START condition, then a STOP
  351.  * condition.
  352.  *
  353.  * @param dev I2C device
  354.  */
  355. void i2c_bus_reset(const i2c_dev *dev) {
  356.     /* Release both lines */
  357.     gpio_write_bit(dev->gpio_port, dev->scl_pin, 1);
  358.     gpio_write_bit(dev->gpio_port, dev->sda_pin, 1);
  359.     gpio_set_mode(dev->gpio_port, dev->scl_pin, GPIO_OUTPUT_OD);
  360.     gpio_set_mode(dev->gpio_port, dev->sda_pin, GPIO_OUTPUT_OD);
  361.  
  362.     /*
  363.      * Make sure the bus is free by clocking it until any slaves release the
  364.      * bus.
  365.      */
  366.     while (!gpio_read_bit(dev->gpio_port, dev->sda_pin)) {
  367.         /* Wait for any clock stretching to finish */
  368.         while (!gpio_read_bit(dev->gpio_port, dev->scl_pin))
  369.             ;
  370.         delay_us(10);
  371.  
  372.         /* Pull low */
  373.         gpio_write_bit(dev->gpio_port, dev->scl_pin, 0);
  374.         delay_us(10);
  375.  
  376.         /* Release high again */
  377.         gpio_write_bit(dev->gpio_port, dev->scl_pin, 1);
  378.         delay_us(10);
  379.     }
  380.  
  381.     /* Generate start then stop condition */
  382.     gpio_write_bit(dev->gpio_port, dev->sda_pin, 0);
  383.     delay_us(10);
  384.     gpio_write_bit(dev->gpio_port, dev->scl_pin, 0);
  385.     delay_us(10);
  386.     gpio_write_bit(dev->gpio_port, dev->scl_pin, 1);
  387.     delay_us(10);
  388.     gpio_write_bit(dev->gpio_port, dev->sda_pin, 1);
  389. }
  390.  
  391. /**
  392.  * @brief Initialize an I2C device and reset its registers to their
  393.  *        default values.
  394.  * @param dev Device to initialize.
  395.  */
  396. void i2c_init(i2c_dev *dev) {
  397.     rcc_reset_dev(dev->clk_id);
  398.     rcc_clk_enable(dev->clk_id);
  399. }
  400.  
  401. /**
  402.  * @brief Initialize an I2C device as bus master
  403.  * @param dev Device to enable
  404.  * @param flags Bitwise or of the following I2C options:
  405.  *              I2C_FAST_MODE: 400 khz operation,
  406.  *              I2C_DUTY_16_9: 16/9 Tlow/Thigh duty cycle (only applicable for
  407.  *                             fast mode),
  408.  *              I2C_BUS_RESET: Reset the bus and clock out any hung slaves on
  409.  *                             initialization,
  410.  *              I2C_10BIT_ADDRESSING: Enable 10-bit addressing,
  411.  *              I2C_REMAP: Remap I2C1 to SCL/PB8 SDA/PB9.
  412.  */
  413. void i2c_master_enable(i2c_dev *dev, uint32 flags) {
  414. #define I2C_CLK                (STM32_PCLK1/1000000)
  415.     uint32 ccr   = 0;
  416.     uint32 trise = 0;
  417.  
  418.     /* PE must be disabled to configure the device */
  419.     ASSERT(!(dev->regs->CR1 & I2C_CR1_PE));
  420.     i2c_slave_mode = 0;   // thd
  421.  
  422.     if ((dev == I2C1) && (flags & I2C_REMAP)) {
  423.         afio_remap(AFIO_REMAP_I2C1);
  424.         I2C1->sda_pin = 9;
  425.         I2C1->scl_pin = 8;
  426.     }
  427.  
  428.     /* Reset the bus. Clock out any hung slaves. */
  429.     if (flags & I2C_BUS_RESET) {
  430.         i2c_bus_reset(dev);
  431.     }
  432.  
  433.     /* Turn on clock and set GPIO modes */
  434.     i2c_init(dev);
  435.     gpio_set_mode(dev->gpio_port, dev->sda_pin, GPIO_AF_OUTPUT_OD);
  436.     gpio_set_mode(dev->gpio_port, dev->scl_pin, GPIO_AF_OUTPUT_OD);
  437.  
  438.     /* I2C1 and I2C2 are fed from APB1, clocked at 36MHz */
  439.     i2c_set_input_clk(dev, I2C_CLK);
  440.  
  441.     if (flags & I2C_FAST_MODE) {
  442.         ccr |= I2C_CCR_FS;
  443.  
  444.         if (flags & I2C_DUTY_16_9) {
  445.             /* Tlow/Thigh = 16/9 */
  446.             ccr |= I2C_CCR_DUTY;
  447.             ccr |= STM32_PCLK1/(400000 * 25);
  448.         } else {
  449.             /* Tlow/Thigh = 2 */
  450.             ccr |= STM32_PCLK1/(400000 * 3);
  451.         }
  452.  
  453.         trise = (300 * (I2C_CLK)/1000) + 1;
  454.     } else {
  455.         /* Tlow/Thigh = 1 */
  456.         ccr = STM32_PCLK1/(100000 * 2);
  457.         trise = I2C_CLK + 1;
  458.     }
  459.  
  460.     /* Set minimum required value if CCR < 1*/
  461.     if ((ccr & I2C_CCR_CCR) == 0) {
  462.         ccr |= 0x1;
  463.     }
  464.  
  465.     i2c_set_clk_control(dev, ccr);
  466.     i2c_set_trise(dev, trise);
  467.  
  468.     /* Enable event and buffer interrupts */
  469.     nvic_irq_enable(dev->ev_nvic_line);
  470.     nvic_irq_enable(dev->er_nvic_line);
  471.     i2c_enable_irq(dev, I2C_IRQ_EVENT | I2C_IRQ_BUFFER | I2C_IRQ_ERROR);
  472.  
  473.     /*
  474.      * Important STM32 Errata:
  475.      *
  476.      * See STM32F10xx8 and STM32F10xxB Errata sheet (Doc ID 14574 Rev 8),
  477.      * Section 2.11.1, 2.11.2.
  478.      *
  479.      * 2.11.1:
  480.      * When the EV7, EV7_1, EV6_1, EV6_3, EV2, EV8, and EV3 events are not
  481.      * managed before the current byte is being transferred, problems may be
  482.      * encountered such as receiving an extra byte, reading the same data twice
  483.      * or missing data.
  484.      *
  485.      * 2.11.2:
  486.      * In Master Receiver mode, when closing the communication using
  487.      * method 2, the content of the last read data can be corrupted.
  488.      *
  489.      * If the user software is not able to read the data N-1 before the STOP
  490.      * condition is generated on the bus, the content of the shift register
  491.      * (data N) will be corrupted. (data N is shifted 1-bit to the left).
  492.      *
  493.      * ----------------------------------------------------------------------
  494.      *
  495.      * In order to ensure that events are not missed, the i2c interrupt must
  496.      * not be preempted. We set the i2c interrupt priority to be the highest
  497.      * interrupt in the system (priority level 0). All other interrupts have
  498.      * been initialized to priority level 16. See nvic_init().
  499.      */
  500.     nvic_irq_set_priority(dev->ev_nvic_line, 0);
  501.     nvic_irq_set_priority(dev->er_nvic_line, 0);
  502.  
  503.     /* Make it go! */
  504.     i2c_peripheral_enable(dev);
  505.  
  506.     dev->state = I2C_STATE_IDLE;
  507. }
  508.  
  509.  
  510. /**
  511.  * @brief Process an i2c transaction.
  512.  *
  513.  * Transactions are composed of one or more i2c_msg's, and may be read
  514.  * or write tranfers.  Multiple i2c_msg's will generate a repeated
  515.  * start in between messages.
  516.  *
  517.  * @param dev I2C device
  518.  * @param msgs Messages to send/receive
  519.  * @param num Number of messages to send/receive
  520.  * @param timeout Bus idle timeout in milliseconds before aborting the
  521.  *                transfer.  0 denotes no timeout.
  522.  * @return 0 on success,
  523.  *         I2C_ERROR_PROTOCOL if there was a protocol error,
  524.  *         I2C_ERROR_TIMEOUT if the transfer timed out.
  525.  */
  526. int32 i2c_master_xfer(i2c_dev *dev,
  527.                       i2c_msg *msgs,
  528.                       uint16 num,
  529.                       uint32 timeout) {
  530.     int32 rc;
  531.  
  532.     ASSERT(dev->state == I2C_STATE_IDLE);
  533.  
  534.     dev->msg = msgs;
  535.     dev->msgs_left = num;
  536.     dev->timestamp = systick_uptime();
  537.     dev->state = I2C_STATE_BUSY;
  538.  
  539.     i2c_enable_irq(dev, I2C_IRQ_EVENT);
  540.     i2c_start_condition(dev);
  541.  
  542.     rc = wait_for_state_change(dev, I2C_STATE_XFER_DONE, timeout);
  543.     if (rc < 0) {
  544.         goto out;
  545.     }
  546.  
  547.     dev->state = I2C_STATE_IDLE;
  548. out:
  549.     return rc;
  550. }
  551.  
  552.  
  553. /**
  554.  * @brief Wait for an I2C event, or time out in case of error.
  555.  * @param dev I2C device
  556.  * @param state I2C_state state to wait for
  557.  * @param timeout Timeout, in milliseconds
  558.  * @return 0 if target state is reached, a negative value on error.
  559.  */
  560. static inline int32 wait_for_state_change(i2c_dev *dev,
  561.                                           i2c_state state,
  562.                                           uint32 timeout) {
  563.     i2c_state tmp;
  564.  
  565.     while (1) {
  566.         tmp = dev->state;
  567.  
  568.         if (tmp == I2C_STATE_ERROR) {
  569.             return I2C_STATE_ERROR;
  570.         }
  571.  
  572.         if (tmp == state) {
  573.             return 0;
  574.         }
  575.  
  576.         if (timeout) {
  577.             if (systick_uptime() > (dev->timestamp + timeout)) {
  578.                 /* TODO: overflow? */
  579.                 /* TODO: racy? */
  580.                 return I2C_ERROR_TIMEOUT;
  581.             }
  582.         }
  583.     }
  584. }
  585.  
  586. //-------------------------------------------------------------------------
  587. // thd slave stuff
  588. //  use master error IRQ handler
  589. #define I2C_BUFFER_LENGTH 32
  590. static uint8 slave_request;   // version 0   deprecated
  591. //  these need to be per device  TODO
  592. static uint32 inbytes = 0;
  593. static uint8 slave_inbuf[I2C_BUFFER_LENGTH];
  594. static uint8 slave_outbuf[I2C_BUFFER_LENGTH];
  595. static uint8 user_inbuf[I2C_BUFFER_LENGTH];
  596. static int user_index, user_end;
  597. static uint32 outbytes = 0;
  598. static uint8 slave_out = 0xc6;
  599.  
  600. uint32 i2c_slave_available(i2c_dev *dev){
  601.     return user_end-user_index;
  602. }
  603.  
  604. // version 0  deprecated
  605. uint32 i2c_slave_request(i2c_dev *dev){
  606.     uint32 ret = slave_request;  // per device
  607.     if (slave_request) slave_request = 0;   //  clear
  608.     return ret;
  609. }
  610.  
  611. uint8 i2c_slave_read(i2c_dev *dev){
  612.     uint8 data =255;
  613.     if (user_end-user_index) data = user_inbuf[user_index++];
  614.     return data;
  615. }
  616.  
  617. // from callback function
  618. void i2c_slave_write(i2c_dev *dev, uint8* data,int count){
  619.     int i;
  620.     outbytes = count;
  621.     if (count < 0) outbytes=0;
  622.     if (count > I2C_BUFFER_LENGTH) outbytes = I2C_BUFFER_LENGTH;
  623.     for(i=0;i<outbytes;i++) slave_outbuf[i] = data[i];
  624. }
  625.  
  626. void i2c_attachSlaveRxEvent(i2c_dev *dev, void (*function)(int)) {
  627.     i2c_onSlaveReceive = function;
  628. }
  629.  
  630. void i2c_attachSlaveTxEvent(i2c_dev *dev, void (*function)(void)) {
  631.     i2c_onSlaveTransmit = function;
  632. }
  633.  
  634. /**
  635.  * @brief Initialize an I2C device as slave
  636.  * @param dev Device to enable
  637.  * @parame i2c_slaveid  7-bit slave id
  638.  * @param flags Bitwise or of the following I2C options:
  639.  *              I2C_FAST_MODE: 400 khz operation,
  640.  *              I2C_DUTY_16_9: 16/9 Tlow/Thigh duty cycle (only applicable for
  641.  *                             fast mode),
  642.  *              I2C_10BIT_ADDRESSING: Enable 10-bit addressing,
  643.  *              I2C_REMAP: Remap I2C1 to SCL/PB8 SDA/PB9.
  644.  */
  645. void i2c_slave_enable(i2c_dev *dev, uint8 i2c_slaveid, uint32 flags){
  646.  
  647.     uint32 ccr   = 0;
  648.     uint32 trise = 0;
  649.  
  650.     /* PE must be disabled to configure the device */
  651.     ASSERT(!(dev->regs->CR1 & I2C_CR1_PE));
  652.     i2c_slave_mode = 1;   // thd  per device
  653.     slave_request =0;
  654.  
  655.     if ((dev == I2C1) && (flags & I2C_REMAP)) {
  656.         afio_remap(AFIO_REMAP_I2C1);
  657.         I2C1->sda_pin = 9;
  658.         I2C1->scl_pin = 8;
  659.     }
  660.  
  661.  
  662.  
  663.     /* Turn on clock and set GPIO modes */
  664.     i2c_init(dev);
  665.     gpio_set_mode(dev->gpio_port, dev->sda_pin, GPIO_AF_OUTPUT_OD);
  666.     gpio_set_mode(dev->gpio_port, dev->scl_pin, GPIO_AF_OUTPUT_OD);
  667.  
  668.     /* I2C1 and I2C2 are fed from APB1, clocked at 36MHz */
  669.     i2c_set_input_clk(dev, I2C_CLK);
  670.  
  671.     if (flags & I2C_FAST_MODE) {
  672.         ccr |= I2C_CCR_FS;
  673.  
  674.         if (flags & I2C_DUTY_16_9) {
  675.             /* Tlow/Thigh = 16/9 */
  676.             ccr |= I2C_CCR_DUTY;
  677.             ccr |= STM32_PCLK1/(400000 * 25);
  678.         } else {
  679.             /* Tlow/Thigh = 2 */
  680.             ccr |= STM32_PCLK1/(400000 * 3);
  681.         }
  682.  
  683.         trise = (300 * (I2C_CLK)/1000) + 1;
  684.     } else {
  685.         /* Tlow/Thigh = 1 */
  686.         ccr = STM32_PCLK1/(100000 * 2);
  687.         trise = I2C_CLK + 1;
  688.     }
  689.  
  690.     /* Set minimum required value if CCR < 1*/
  691.     if ((ccr & I2C_CCR_CCR) == 0) {
  692.         ccr |= 0x1;
  693.     }
  694.  
  695.     i2c_set_clk_control(dev, ccr);
  696.     i2c_set_trise(dev, trise);
  697.  
  698.     /* Enable event and buffer interrupts */
  699.     nvic_irq_enable(dev->ev_nvic_line);
  700.     nvic_irq_enable(dev->er_nvic_line);
  701.     i2c_enable_irq(dev, I2C_IRQ_EVENT | I2C_IRQ_BUFFER | I2C_IRQ_ERROR );
  702.  
  703.     /*
  704.      * Important STM32 Errata:
  705.      *
  706.      * See STM32F10xx8 and STM32F10xxB Errata sheet (Doc ID 14574 Rev 8),
  707.      * Section 2.11.1, 2.11.2.
  708.      *
  709.      * 2.11.1:
  710.      * When the EV7, EV7_1, EV6_1, EV6_3, EV2, EV8, and EV3 events are not
  711.      * managed before the current byte is being transferred, problems may be
  712.      * encountered such as receiving an extra byte, reading the same data twice
  713.      * or missing data.
  714.      *
  715.      * 2.11.2:
  716.      * In Master Receiver mode, when closing the communication using
  717.      * method 2, the content of the last read data can be corrupted.
  718.      *
  719.      * If the user software is not able to read the data N-1 before the STOP
  720.      * condition is generated on the bus, the content of the shift register
  721.      * (data N) will be corrupted. (data N is shifted 1-bit to the left).
  722.      *
  723.      * ----------------------------------------------------------------------
  724.      *
  725.      * In order to ensure that events are not missed, the i2c interrupt must
  726.      * not be preempted. We set the i2c interrupt priority to be the highest
  727.      * interrupt in the system (priority level 0). All other interrupts have
  728.      * been initialized to priority level 16. See nvic_init().
  729.      */
  730.     nvic_irq_set_priority(dev->ev_nvic_line, 0);
  731.     nvic_irq_set_priority(dev->er_nvic_line, 0);
  732.    
  733.     // set slave address
  734.     dev->regs->OAR1 = (i2c_slaveid<<1);
  735.    
  736.     /* Make it go! */
  737.     i2c_peripheral_enable(dev);
  738.     i2c_enable_ack(dev);  // must come after enable
  739.  
  740.     dev->state = I2C_STATE_IDLE;
  741.     I2C_CRUMB(0x99,1,2);
  742. }
  743. /**
  744.  * @brief IRQ handler for I2C slave
  745.  * @param dev I2C device
  746.  */
  747. static void i2c_slave_irq_handler(i2c_dev *dev) {
  748.    
  749.     uint32 sr1 = dev->regs->SR1;            // reading SR1 and 2 allows to proceed
  750.     uint32 sr2 = dev->regs->SR2;
  751.     I2C_CRUMB(IRQ_ENTRY, sr1, sr2);
  752.  
  753.     /*
  754.      * Reset timeout counter
  755.      */
  756.     dev->timestamp = systick_uptime();
  757.  
  758.     /*
  759.      * EV1: Slave address recvd
  760.      */
  761.     if (sr1 & I2C_SR1_ADDR) {
  762.         I2C_CRUMB(RX_ADDR_START, 0, 0);
  763.         if (sr1 & I2C_SR1_TXE) {        //start and send to master
  764.             outbytes = 0;
  765.             // CALLBACK for stuff to send to master
  766.             i2c_onSlaveTransmit();
  767.             if (0 == outbytes) {   // send something
  768.                 outbytes = 1;
  769.                 slave_outbuf[0] = 0x11;
  770.             }
  771.         } else inbytes=0;
  772.        sr1 = sr2 = 0;
  773.     }
  774.  
  775.     /*
  776.      * EV2: slave Receiver data in
  777.      */
  778.     if (sr1 & I2C_SR1_RXNE) {
  779.         I2C_CRUMB(RXNE_ONLY, 0, 0);
  780.         slave_inbuf[inbytes] = dev->regs->DR;
  781.         if (inbytes < I2C_BUFFER_LENGTH-1) inbytes++;
  782.         // TODO should we do NACK if buffer full ?
  783.     }
  784.  
  785.     /*
  786.      * EV4: slave Receiver stop
  787.      */
  788.     if (sr1 & I2C_SR1_STOPF) {
  789.         int i;
  790.         I2C_CRUMB(STOP_SENT, 0, 0);
  791.         // have all the bytes, do CALLBACK  
  792.         for(i=0;i<inbytes;i++) user_inbuf[i] = slave_inbuf[i];
  793.         user_end = inbytes;
  794.         user_index=0;
  795.         i2c_onSlaveReceive(inbytes);
  796.         inbytes=0;
  797.         i2c_enable_ack(dev);            // write to CR1 to proceed
  798.     }
  799.  
  800.    /*
  801.      * EV3: slave transmit  unsure about EV3-1   two TXE events
  802.      */
  803.     if (sr1 & I2C_SR1_TXE) {
  804.         I2C_CRUMB(TXE_ONLY, 0, 0);
  805.         if (outbytes) {
  806.             if (1 == outbytes) { // last byte
  807.                 i2c_disable_ack(dev);  //  NACK
  808.             } else i2c_enable_ack(dev);
  809.             i2c_write(dev,slave_outbuf[--outbytes]);
  810.         } else {
  811.                 i2c_stop_condition(dev); //  stop after final byte
  812.                 I2C_CRUMB(STOP_SENT,0,0);
  813.         }
  814.         sr1 = sr2 = 0;
  815.     }
  816.  
  817.     /*
  818.      * EV3-2: slave transmit stop NACK  error inerrupt will handle this !
  819.      */
  820.  
  821. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement