I'm trying to set up a technique for serial communications using the pic16f887 and the Hitachi H48C 3-Axis Accelerometer. I'm new to bit banging and I know I need to find out how to do it to send data to the h48c. I'm finding loads of example codes in basic stamp but I'm trying to convert it to c and its not easy, for me anyway Wondering if someone would take a look at what I have so far for the bit banging part and see if it looks completely messed up or not
unsigned char data;
unsigned char i;
int main(void)
{
PORTD=0;
TRISD0=0;//RD1 OUTPUT
TRISD1=0;//CLOCK AS OUTPUT
RD2=1;//CHIP SELECT HIGH
data=0x1b; //00011011
data=data<<3;// SHIFTS OUT THE 000/11011
// send bits 7..0
for(i = 0; i < 5; i++)// READS BITS 0 TO 5
{
RD2=0;//CHIP SELECT LOW
// LOOK AT THE LEFTMOST BIT
// SET DATA HIGH IF BIT IS 1, LOW IF 0
if (data & 0x80)
RD0=1;//(DATA HIGH)
else
RD0=0;//(DATA LOW)
// pulse clock to indicate that bit value should be read
RD1=0;//(CLOCK LOW)
RD1=1;//(CLOCK HIGH)
// SHIFT BIT LEFT SO NEXT BIT WITH BE MSB
data=data <<= 1;
}
Basically it's correct but you have the bit order wrong. By repeating the loop 5 times while clocking out the MSB you are sending bits 7,6,5,4 and 3 which is probably not what you wanted. If the bits have to be sent with b5 first, change the mask 0x80 to 0x40. If they should be sent LSB first, use 0x01 and shift the other direction. There is one error, the shift instruction should be data = data << 1; with no '=' in it.