PIC Micro Controller C Input / Output Routine

RS232 to SPI converter in CCS C

by David Knott

#include <16C84.h>

#pragma use delay (clock=4000000) // 4 Mhz clock.  Used by RS232 and delay
functions

#pragma case   // Makes the compiler case sensitive.  Case insensitivity is
the default!

#pragma use fast_io(A)  // The default I/O attribute is standard_io.  This
setting
#pragma use fast_io(B)  // has the compiler generate instructions to change
the

// data direction register during I/O operations.
    // fast_io does not generate these extra instructions.

#pragma use RS232 (baud=9600, xmit=PIN_B0, rcv=PIN_B1)


// This structure is overlayed on to an I/O port to gain access to the LCD
pins.
// The bits are allocated from low order up.

struct {
      int unused:2;  // The 232 serial port PB[0:1]

      int mosi:1;  // Output PB2

      int miso:1;  // Input PB3

      int sclk:1;  // Output PB4

      int cs:1;   // Output PB5

} SPIPort;

#pragma byte SPIPort=0x06 // Place the entire structure over PORTB (address
6)


BYTE
SPIPutch (BYTE byOutData)
{
      int nIndex;
      BYTE byInData = 0;


     // Data is presented on rising edge of SCLK, and captured on falling
edge of SCLK.



     // Tell the device we are initiating communications.
      SPIPort.cs = 0;

      for (nIndex = 0; nIndex < 8; ++nIndex) {

    // Update pin status to reflect bit in data to be sent.
     SPIPort.mosi = (byOutData & 0x80 ? 1 : 0);

    // Increment to next bit to be sent.
     byOutData = byOutData << 1;


    // Clock a rising edge on SCLK.  MOSI presents on the rising edge of
SCLK.
     SPIPort.sclk = 1;

    // TODO: Add delay to wait for slave device to present data?


     delay_cycles (20);

     byInData = byInData << 1;

    // Read what the slave device has presented on our MISO pin.
     if (SPIPort.miso)
    byInData |= 0x01;

    // We read what the slave device had asserted on MISO.

     SPIPort.sclk = 0;



      }
      SPIPort.cs = 1;
      return byInData;

}

void
FlashLED (BYTE byOnTime)
{

      output_low (PIN_A0);
      DELAY_MS (byOnTime);
      output_high (PIN_A0);
}



void
main (void)
{

      char chInChar;
      BYTE test = 0xff;
      BYTE byReturn;

      SPIPort.cs = 1;

      set_tris_b (0x0a);

     // PORTA is an output.
      set_tris_a (0x00);
      chInChar = 0;



     // Make sure sclk is low before we assert the Chip Select.
      SPIPort.sclk = 0;

     //   printf ("Ready for input...\r\n");

     if (

      while (1) {
     chInChar = GETCHAR ();
//             chInChar++;
     byReturn = SPIPutch (chInChar);

     printf ("0x%x\r\n",byReturn);
      }


}


Questions:

Comments: