Senzory 1.0
twi.h
Go to the documentation of this file.
1#ifndef TWI_H
2#define TWI_H
3
4/*
5 * I2C/TWI library for AVR-GCC.
6 * (c) 2018-2025 Tomas Fryza, MIT license
7 *
8 * Developed using PlatformIO and Atmel AVR platform.
9 * Tested on Arduino Uno board and ATmega328P, 16 MHz.
10 */
11
26
27// -- Includes ---------------------------------------------
28 #include <avr/io.h>
29
30
31// -- Defines ----------------------------------------------
35#ifndef F_CPU
36#define F_CPU 16000000
37#endif
38#define F_SCL 100000
39#define TWI_BIT_RATE_REG ((F_CPU/F_SCL - 16) / 2)
40
41
45#define TWI_PORT PORTC
46#define TWI_SDA_PIN 4
47#define TWI_SCL_PIN 5
48
49
53#define TWI_WRITE 0
54#define TWI_READ 1
55#define TWI_ACK 0
56#define TWI_NACK 1
57#define DDR(_x) (*(&_x - 1))
58#define PIN(_x) (*(&_x - 2))
59
60
61// -- Function prototypes ----------------------------------
71void twi_init(void);
72
73
78void twi_start(void);
79
80
92uint8_t twi_write(uint8_t data);
93
94
101uint8_t twi_read(uint8_t ack);
102
103
108void twi_stop(void);
109
110
118uint8_t twi_test_address(uint8_t addr);
119
120
129void twi_readfrom_mem_into(uint8_t addr, uint8_t memaddr, volatile uint8_t *buf, uint8_t nbytes);
130
132
133#endif
uint8_t twi_write(uint8_t data)
Write one byte to the I2C/TWI bus.
Definition twi.c:51
void twi_init(void)
Initialize TWI unit, enable internal pull-ups, and set SCL frequency.
Definition twi.c:20
void twi_readfrom_mem_into(uint8_t addr, uint8_t memaddr, volatile uint8_t *buf, uint8_t nbytes)
Read into buf from the peripheral, starting from the memory address.
Definition twi.c:132
void twi_stop(void)
Generates Stop condition on I2C/TWI bus.
Definition twi.c:99
uint8_t twi_test_address(uint8_t addr)
Test presence of one I2C device on the bus.
Definition twi.c:111
uint8_t twi_read(uint8_t ack)
Read one byte from the I2C/TWI bus and acknowledge it by ACK or NACK.
Definition twi.c:82
void twi_start(void)
Start communication on I2C/TWI bus.
Definition twi.c:37