Operácie

I2C.c

Z SensorWiki

Verzia z 12:57, 1. február 2013, ktorú vytvoril StudentDVPS (diskusia | príspevky)
(rozdiel) ← Staršia verzia | Aktuálna úprava (rozdiel) | Novšia verzia → (rozdiel)

<source lang="c"> /*

* I2C.c
*
* Created: 15.01.2013 19:05:05
*  Author: Tomáš Statečný
*/ 
  1. include <inttypes.h>
  2. include <compat/twi.h>
  1. include "I2C.h"
  2. include "lcd.h"

//Zadefinovanie CPU fekvencie v Hz pokial nie je dana

  1. ifndef F_CPU
  2. define F_CPU 16000000UL
  3. endif

//Zadefinovanie I2C frekvencie v Hz

  1. define SCL_CLOCK 100000L

//Inicializacia I2C void i2c_init(void) {

 TWSR = 0;                         //No prescaler
 TWBR = ((F_CPU/SCL_CLOCK)-16)/2;  //must be > 10 for stable operation

}

//Zadefinovanie vstupov a vystupov

  1. define SDA_I (DDRC &= ~(1<<4)) //Nastavenie 4bit DDRC na citanie (SDA)
  2. define SCL_O (DDRC |= (1<<5)) //Nastavenie 5bit DDRC na zapis (SCL)
  3. define SDA_O (DDRC |= (1<<4)) //Nastavenie 4bit DDRC na zapis (SDA)

//Nastavovanie pinov

  1. define SETBIT_SCL (PORTC |= (1<<5)) //Zapis log.1 na pin 5 PORTC (SCL)
  2. define CLEARBIT_SCL (PORTC &= ~(1<<5)) //Zapis log.0 na pin 5 PORTC (SCL)
  1. define SETBIT_SDA (PORTC |= (1<<4)) //Zapis log.1 na pin 4 PORTC (SDA)
  2. define CLEARBIT_SDA (PORTC &= ~(1<<4)) //Zapis log.0 na pin 4 PORTC (SDA)
  3. define CHECKBIT_SDA (PORTC & (1<<4)) //Zistenie stavu na pin 4 PORTC (SDA)

//Funkcia na meranie teploty alebo vlhkosti pre snimac SHT11 unsigned Measure(char CMD){ char i; char j = 0x80; unsigned hodnot = 0;

SDA_O; SETBIT_SDA; _delay_us(5); SCL_O; CLEARBIT_SCL; _delay_ms(100);

//Reset merania for(i=0; i<10; i++){

SDA_O; SETBIT_SDA; _delay_us(5); SCL_pulse(); }

//Incializacia prenosu SDA_O; CLEARBIT_SDA; _delay_us(5);

SCL_O; SETBIT_SCL; _delay_ms(5); SCL_O; CLEARBIT_SCL; _delay_ms(5);


SDA_O; CLEARBIT_SDA; _delay_us(5); SCL_pulse();

SDA_O; SETBIT_SDA; _delay_us(5);

SCL_O; SETBIT_SCL; _delay_ms(5); SCL_O; CLEARBIT_SCL; _delay_ms(5);

_delay_ms(20);

//Adresa prikazu for(i=0; i<8; i++){

SDA_O; if(!(j & CMD)) CLEARBIT_SDA;

else SETBIT_SDA;

_delay_us(5); SCL_pulse();

j >>= 1; }

//Overie ACK bitu SDA_I; SCL_pulse();

if(CHECKBIT_SDA) return 0;

SCL_O; CLEARBIT_SCL; _delay_ms(100);

SDA_I; while(!CHECKBIT_SDA);

//Pockaj, dokial sa neprenesu data SDA_I; while(CHECKBIT_SDA);

//Vycitanie prveho Byte for(i=0; i<8; i++){ hodnot <<= 1;

SDA_I; if(CHECKBIT_SDA){ hodnot |= 1; _delay_us(5); SCL_pulse(); } }

//Odoslanie ACK bitu SDA_O; CLEARBIT_SDA; _delay_us(5); SCL_pulse();

//Vycitanie druheho Byte for(i=0; i<8; i++){ hodnot <<= 1;

SDA_I; if(CHECKBIT_SDA){ hodnot |= 1; _delay_us(5); SCL_pulse(); } }

return hodnot; //Vrati hodnotu bez kontrolneho suctu }

//Zadefinovanie jednej periody SCL int SCL_pulse(){

SCL_O; CLEARBIT_SCL; _delay_ms(5); SCL_O; SETBIT_SCL; _delay_ms(5); return 0; }