I try to make a tiny26 and a mega162 to communicate using the spi protocol. For the mega I use the hardware spi controller and for the tiny I ported the assembly code from the datasheet for using USI as SPI slave. When master wants the communication to be initiated, pulls the SS line low which triggers an interrupt to the slave, and in the ISR the spi_comm routine is called.
The init and comm routines for master are the following:
void spi_init_ms(void) { DDRB |=0xb0; //SCK,MOSI,~SS as outputs cbi(DDRB,6); //MISO as input sbi(PORTB,6); //MISO pull-up enabled SPCR = ((1<<SPE)+(1<<MSTR)+(1<<SPR1)); //SCK freq = fosc/64 }; unsigned char spi_comm(char tosl) { unsigned char fromsl; cbi(PORTB,4); //pull ~SS low _delay_loop_2(200); //wait SPDR = tosl; while(!(SPSR&(1<<SPIF))); //wait for end of transmition fromsl = SPDR; sbi(PORTB,4); return fromsl; };
and for tha slave:
void spi_init_sl(void) { DDRB = 0x02; PORTB= 0x45; USICR = (1<<USIWM0)+(1<<USICS1); //3-wire , shift reg clock ext., pos.edge GIMSK = 0x40; MCUCR = (1<<ISC01); //ext interrupt on falling edge }; unsigned char spi_comm(unsigned char tomst) { unsigned char frommst; USIDR = tomst; USISR = (1<<USIOIF); while(!(USISR&(1<<USIOIF))); //wait for 4bit counter overflow frommst = USIDR; return(frommst); };
The problem is that when i initiate the transmition from the master with the slave configured to send always a 0x3c byte, the data i receive in the master look like 0x00 0xf0 0x3c 0x3c 0x27 0x9e 0x1e 0x3c (real received data).
Anybody has any clue for what the prob is? I have spent quite a long time trying different settings and this is the best i could make (much better than receiving only 0xff).
P.S. I am new in c. I used to write code in assembly.