/* si2c.c - Software I2C library for esp8266 Copyright (c) 2015 Hristo Gochkov. All rights reserved. This file is part of the esp8266 core for Arduino environment. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "twi.h" #include "pins_arduino.h" #include "wiring_private.h" unsigned char twi_dcount = 18; static unsigned char twi_sda, twi_scl; #define SDA_LOW() (GPES = (1 << twi_sda)) //Enable SDA (becomes output and since GPO is 0 for the pin, it will pull the line low) #define SDA_HIGH() (GPEC = (1 << twi_sda)) //Disable SDA (becomes input and since it has pullup it will go high) #define SDA_READ() ((GPI & (1 << twi_sda)) != 0) #define SCL_LOW() (GPES = (1 << twi_scl)) #define SCL_HIGH() (GPEC = (1 << twi_scl)) #define SCL_READ() ((GPI & (1 << twi_scl)) != 0) #ifndef FCPU80 #define FCPU80 80000000L #endif #if F_CPU == FCPU80 #define TWI_CLOCK_STRETCH 800 #else #define TWI_CLOCK_STRETCH 1600 #endif void twi_setClock(unsigned int freq){ #if F_CPU == FCPU80 if(freq <= 100000) twi_dcount = 19;//about 100KHz else if(freq <= 200000) twi_dcount = 8;//about 200KHz else if(freq <= 300000) twi_dcount = 3;//about 300KHz else if(freq <= 400000) twi_dcount = 1;//about 400KHz else twi_dcount = 1;//about 400KHz #else if(freq <= 100000) twi_dcount = 32;//about 100KHz else if(freq <= 200000) twi_dcount = 14;//about 200KHz else if(freq <= 300000) twi_dcount = 8;//about 300KHz else if(freq <= 400000) twi_dcount = 5;//about 400KHz else if(freq <= 500000) twi_dcount = 3;//about 500KHz else if(freq <= 600000) twi_dcount = 2;//about 600KHz else twi_dcount = 1;//about 700KHz #endif } void twi_init(unsigned char sda, unsigned char scl){ twi_sda = sda; twi_scl = scl; pinMode(twi_sda, INPUT_PULLUP); pinMode(twi_scl, INPUT_PULLUP); twi_setClock(100000); } void twi_stop(void){ pinMode(twi_sda, INPUT); pinMode(twi_scl, INPUT); } static void twi_delay(unsigned char v){ unsigned int i; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-but-set-variable" unsigned int reg; for(i=0;i