// // qsmrecv.c FD3S ECU Syncronized Serial and Asyncronus Gateway // for PIC18F252 // 2002(c) Kashi. // #include char spibp, sendstat; struct sSPI_buf { char CmdSeg; int addr; char data; char dummy; char lock; } SPIbuf_in, SPIbuf_out, UARTbuf_in, UARTbuf_out; void interrupt ssp_in() { char i; // Insert your code here // check SPI int if(SSPIF){ SSPIF = 0; // clear int flag *((char *)&SPIbuf_in + spibp) = SSPBUF; // receive data SSPBUF = *((char *)&SPIbuf_out + spibp); // trans data if( ++spibp == 5 ){ spibp = 0; if( !UARTbuf_in.lock && (sendstat == 1)){ // UART data ready for(i=0;i<4;i++) // set send data *((char *)&SPIbuf_out + i) = *((char *)&UARTbuf_in + i); sendstat = 2; // sending } else if( sendstat == 2){ sendstat = 3; // sending done } else if( !UARTbuf_out.lock && (sendstat == 3)){ for(i=0;i<4;i++) // pull read data *((char *)&UARTbuf_out + i) = *((char *)&SPIbuf_in + i); sendstat = 4; // answer ready, clear transaction SPIbuf_out.CmdSeg = 0xff; // idle, nop command } else if( sendstat == 0){ if( (*((char *)&SPIbuf_in + 0) == 0xff) && (*((char *)&SPIbuf_in + 1) == 'F') ) RA0 = 0; else RA0 = 1; } } } } void main() { char c, bp; PORTA = 0xff; PORTB = 0x00; PORTC = 0xff; TRISA = 0xfe; TRISB = 0xfe; TRISC = 0x9f; ADCON1 = 0x06; SSPSTAT = 0x00; SSPCON1 = 0x34; TXSTA = 0x24; RCSTA = 0x90; SPBRG = 64; // 38,400bps @40.00MHz PEIE = 1; // peripheral interrupt enable GIE = 1; // grobal interrupt enable restart: RA0 = 1; // LED off spibp = 0; UARTbuf_in.lock = 1; UARTbuf_out.lock = 1; SPIbuf_in.lock = 1; SPIbuf_out.lock = 1; SPIbuf_out.CmdSeg = 0xff; // idle, nop command SSPIE = 0; // SSP interrupt disable SSPBUF = 0xff; while(1){ // wait last char on frame if(SSPIF){ SSPIF = 0; if( SSPBUF == 'S' ) break; SSPBUF = 0xff; } } CREN = 0; CREN = 1; // clear error c = RCREG; // dummy read SSPIE = 1; // SSP interrupt enable RA0 = 0; // LED on reread: sendstat = 0; UARTbuf_in.lock = 1; for( bp = 0; bp < 4; bp++){ while(!RCIF); // wait receive char c = RCREG; if( bp == 0 && c == 0xff){ while(!TRMT); // wait transmitter TXREG = 0x00; // responce null char goto reread; } *((char *)&UARTbuf_in + bp) = c; } UARTbuf_in.lock = 0; // data ready UARTbuf_out.lock = 0; // output buffer ready sendstat = 1; // sending request while(sendstat != 4){ // polling request done if(RCIF){ // receive UART, break? if( RCREG == 0xff ){ TXREG = 0x00; // responce null char goto restart; } } } UARTbuf_out.lock = 1; for( bp = 0; bp < 4; bp++){ while(!TRMT); // wait transmitter TXREG = *((char *)&UARTbuf_out + bp); } goto reread; }