I am not having any luck with my ATMEGA32 and the HMC6352 compass. It will ACK it’s way all the way through this program, even the read request, but the compass will never write anything to the data bus. I have also tried reading from a RAM register with the same results. Lot’s of ACKs but never any data on the data bus. If anyone has any ideas I would be very grateful.
Russ
#include <util/delay.h>
#include <stdlib.h>
#include <stdio.h>
#include <avr/io.h>
unsigned char read=0x43,write=0x42;
unsigned char recvd_data;
#define Start() TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(0<<TWSTO) //Send START signal
#define Wait() while (!(TWCR & (1<<TWINT))) //Wait for TW hardware to send data
void address_write(unsigned char address)
{
TWDR=address;
TWCR|=(1<<TWINT)|(1<<TWEN);
while(!(TWCR & (1<<TWINT))); //Wait for TWI hardware to do it’s job
while((TWSR & 0xF8)!=0x18); //Wait for address received and ACKed
}
void data_write(unsigned char data)
{
TWDR=data;
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR & (1<<TWINT))); //Wait for TWI hardware to do it’s job
while((TWSR & 0xF8)!=0x28); //Wait for data received and ACKed
}
void repeat_start(void)
{
TWCR|=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while(!(TWCR & (1<<TWSTA)));
while((TWSR & 0xF8)!=0x10);
}
void address_read(unsigned char address)
{
TWDR=address;
TWCR|=(1<<TWINT)|(1<<TWEN);
while(!(TWCR & (1<<TWINT)));
while((TWSR & 0xF8)!=0x40);
recvd_data=TWDR;
}
void read_data(void)
{
TWCR=(1<<TWINT)|(1<<TWEN);
while(!(TWCR & (1<<TWINT)));
while((TWSR & 0xF8)!=0x58);
recvd_data=TWDR;
}
int main(){
TWBR = 2; //Set bit rate to 100Khz with 2 Mhz clock prescalar = 0
Start(); //Initialize communication with compass
Wait();
address_write(0x42); //address of compass to command 42 hex
data_write(‘G’); // Write to RAM register
data_write(‘t’); //Op Mode register address
data_write(0x52); //10Hz update rate,periodic set/reset on,continous mode
data_write(0x41); //Get compass data
repeat_start();
address_read(0x43);
}//end of main