hello
i want to command an I/O expander PCF8574 with atmega382p but i don't get a result i'm using Microchip studio . this is my code:
/// twi_lib.h /* * twi_lib.h * * Created: 09/01/2022 5:25:27 PM * Author: User */ #ifndef TWI_LIB_H_ #define TWI_LIB_H_ #define SCL_CLOCK 100000L void twi_init(); uint8_t twi_start(char); void twi_write(char); char twi_read_ack(); char twi_read_nack(); void twi_stop(); #endif /* TWI_LIB_H_ */
//// twi_lib.c /* * twi_lib.c * * Created: 09/01/2022 5:22:43 PM * Author: User */ #include <compat/twi.h> #include <util/delay.h> #include "twi_lib.h" void twi_init() { TWSR = 0; TWBR = (((F_CPU/SCL_CLOCK)-16)/2) & 0xff; } uint8_t twi_start(char write_address) { uint8_t twst; // send start condition TWCR = (1<<TWEN)|(1<<TWSTA)|(1<<TWINT); // wait until transmission completed while(!(TWCR & (1<<TWINT))); twst = TWSR; if (twst==0x08) { return 1; } // send device address TWDR = write_address; TWCR = (1<<TWINT) | (1<<TWEN); // wail until transmission completed and ACK/NACK has been received while(!(TWCR & (1<<TWINT))); // check value of TWI Status Register. Mask prescaler bits. twst = TW_STATUS & 0xF8; if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1; return 0; } void twi_write(char data) { //uint8_t twst; // send data to the previously addressed device //TWCR = (1<<TWINT) | (1<<TWEN); TWCR = 1<<TWINT; TWDR = data; TWCR = (1<<TWINT) | (1<<TWEN); // wait until transmission completed while(!(TWCR & (1<<TWINT))); } char twi_read_ack() { TWCR = (1<<TWINT) | (1<<TWEN) ; while(!(TWCR & (1<<TWINT))); return TWDR; } char twi_read_nack() { TWCR = (1<<TWINT) | (1<<TWEN); while(!(TWCR & (1<<TWINT))); return TWDR; } void twi_stop() { /* send stop condition */ TWCR = (1<<TWINT) | (1<<TWSTO) | (1<<TWEN); // wait until stop condition is executed and bus released while(TWCR & (1<<TWSTO)); }
///// main.c /* * carte_I2C_relais.c * * Created: 27/12/2021 5:38:56 PM * Author : User */ #include <avr/io.h> #include <compat/twi.h> //#include<TWI_lib.h> #include <util/delay.h> #include "twi_lib.h" uint32_t CPU_FREQ = 16000000; int main(void) { twi_init(); twi_start(0x20); while (1) { twi_write(0x40); twi_read_ack(); twi_write(0x01); twi_stop(); } }
please check my code. thanks