You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

i2c_wrapper.c 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. Copyright 2016 Kai Ryu <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <avr/interrupt.h>
  15. #include <avr/wdt.h>
  16. #include <util/delay.h>
  17. #include "i2cmaster.h"
  18. #include "i2c_wrapper.h"
  19. #include "debug.h"
  20. #define wdt_intr_enable(value) \
  21. __asm__ __volatile__ ( \
  22. "in __tmp_reg__,__SREG__" "\n\t" \
  23. "cli" "\n\t" \
  24. "wdr" "\n\t" \
  25. "sts %0,%1" "\n\t" \
  26. "out __SREG__,__tmp_reg__" "\n\t" \
  27. "sts %0,%2" "\n\t" \
  28. : /* no outputs */ \
  29. : "M" (_SFR_MEM_ADDR(_WD_CONTROL_REG)), \
  30. "r" (_BV(_WD_CHANGE_BIT) | _BV(WDE)), \
  31. "r" ((uint8_t) ((value & 0x08 ? _WD_PS3_MASK : 0x00) | \
  32. _BV(WDIE) | (value & 0x07)) ) \
  33. : "r0" \
  34. )
  35. #define SCL_CLOCK 400000L
  36. #define SCL_DURATION (1000000L/SCL_CLOCK)/2
  37. static uint8_t i2c_wdt_enabled = 0;
  38. extern uint8_t i2c_force_stop;
  39. static void wdt_init(void);
  40. void i2c_wrapper_init(void)
  41. {
  42. /* init i2c */
  43. i2c_init();
  44. /* init watch dog */
  45. wdt_init();
  46. }
  47. void i2c_wrapper_task(void)
  48. {
  49. /* reset watch dog counter */
  50. wdt_reset();
  51. }
  52. void wdt_init(void)
  53. {
  54. cli();
  55. wdt_reset();
  56. wdt_intr_enable(WDTO_2S);
  57. sei();
  58. }
  59. ISR(WDT_vect)
  60. {
  61. xprintf("i2c timeout\n");
  62. /* let slave to release SDA */
  63. TWCR = 0;
  64. DDRD |= (1<<PD0);
  65. DDRD &= ~(1<<PD1);
  66. if (!(PIND & (1<<PD1))) {
  67. for (uint8_t i = 0; i < 9; i++) {
  68. PORTD &= ~(1<<PD0);
  69. _delay_us(SCL_DURATION);
  70. PORTD |= (1<<PD0);
  71. _delay_us(SCL_DURATION);
  72. }
  73. }
  74. /* send stop condition */
  75. TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
  76. /* escape from loop */
  77. i2c_force_stop = 1;
  78. }