1 | #include "pcf8574.h"
|
2 |
|
3 | void pcf8574_init (void)
|
4 | {
|
5 | /*set bus speed*/
|
6 | TWBR = 0x10;
|
7 | }
|
8 |
|
9 | unsigned char pcf8574_send_start (void)
|
10 | {
|
11 | /*writing a one to TWINT clears it, TWSTA=Start, TWEN=TWI-enable*/
|
12 | TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
|
13 | /*wait, until start condition has been sent --> ACK*/
|
14 | while (!(TWCR & (1<<TWINT)));
|
15 | return TWSR;
|
16 | }
|
17 |
|
18 | void pcf8574_send_stop (void)
|
19 | {
|
20 | /*writing a one to TWINT clears it, TWSTO=Stop, TWEN=TWI-enable*/
|
21 | TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN);
|
22 | }
|
23 |
|
24 | unsigned char pcf8574_send_add_rw (unsigned char address, unsigned char rw)
|
25 | {
|
26 | /*address can be 0 .. 8; rw=0 --> write, rw=1 --> read*/
|
27 | unsigned char addr_byte = 0;
|
28 | /*shift address one bit left*/
|
29 | addr_byte = address << 1;
|
30 | /*set RW-Bit, if necessary*/
|
31 | addr_byte |= rw;
|
32 | /*0b0100xxx0 --> address of Expander*/
|
33 | addr_byte |= 0b01000000;
|
34 | /*TWDR contains byte to send*/
|
35 | TWDR = addr_byte;
|
36 | /*send content of TWDR*/
|
37 | TWCR = (1<<TWINT) | (1<<TWEN);
|
38 | /*wait, until address has been sent --> ACK*/
|
39 | while (!(TWCR & (1<<TWINT)));
|
40 | return TWSR;
|
41 | }
|
42 |
|
43 | unsigned char pcf8574_send_byte (unsigned char byte)
|
44 | {
|
45 | /*TWDR contains byte to send*/
|
46 | TWDR = byte;
|
47 | /*send content of TWDR*/
|
48 | TWCR = (1<<TWINT) | (1<<TWEN);
|
49 | /*wait, until byte has been sent --> ACK*/
|
50 | while (!(TWCR & (1<<TWINT)));
|
51 | return TWSR;
|
52 | }
|
53 |
|
54 | unsigned char pcf8574_read_byte (void)
|
55 | {
|
56 | /*send content of TWDR; TWEA = enable ACK*/
|
57 | TWCR = (1<<TWINT) | (1<<TWEA) | (1<<TWEN);
|
58 | /*wait, until byte has been received --> ACK*/
|
59 | while (!(TWCR & (1<<TWINT)));
|
60 | return TWDR;
|
61 | }
|
62 |
|
63 | void pcf8574_set_outputs (unsigned char address, unsigned char byte)
|
64 | {
|
65 | pcf8574_init ();
|
66 | pcf8574_send_start ();
|
67 | pcf8574_send_add_rw (address, 0);
|
68 | pcf8574_send_byte (byte);
|
69 | pcf8574_send_stop ();
|
70 | }
|