Advertisement
Guest User

SR/SPI w/ PIC16f819

a guest
Dec 25th, 2013
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.02 KB | None | 0 0
  1. /* Place these things in a config header */
  2. #include <htc.h>
  3. #include "delay.h"
  4. __CONFIG(MCLRE_OFF & CP_OFF & WDTE_OFF & BOREN_OFF & FOSC_INTOSCCLK);
  5.  
  6. /* :) */
  7. #include "delay.c"
  8.  
  9. /* Probably okay macros */
  10. #define SET_BIT(p,n) ((p) |=   (1) << (n))
  11. #define CLR_BIT(p,n) ((p) &= ~((1) << (n)))
  12. #define TOG_BIT(p,n) ((p) ^=   (1) << (n))
  13. #define CHK_BIT(p,n) ((p) &   ((1) << (n)))
  14.  
  15. /* When in a library, use ifdefs to make these default but option pin mappings maybe  */
  16. /* SPI Pins */
  17. #define SPI_SDI     PORTBbits.RB1
  18. #define SPI_SDO     PORTBbits.RB2
  19. #define SPI_CS      PORTBbits.RB3
  20. #define SPI_CLK     PORTBbits.RB4
  21.  
  22. /* SR Pins..figure something out later */
  23. #define SR_LAT     PORTBbits.RB5
  24. #define SR_HSCP    PORTBbits.RB6
  25. #define SR_HTCP    PORTBbits.RB7
  26.  
  27. void spiInit() {
  28.     SET_BIT(TRISB, SPI_SDI);
  29.     CLR_BIT(TRISB, SPI_SDO);
  30.     CLR_BIT(TRISB, SPI_CLK);
  31.     CLR_BIT(TRISB, SPI_CS);
  32.  
  33.     SSPCON = 0;                    // first disable port if it was still running
  34.     SSPSTAT = 0;                   // Reset all status flags (there are some R/W bits)
  35.     SSPCON = (1<<5) | (1<<1);      // enable port, SPI mode Fosc/64
  36. }
  37.  
  38. void srInit() {
  39.     SET_BIT(TRISB, SR_LAT);
  40. }
  41.  
  42. unsigned char spiTxRx(unsigned char byteOut) {
  43.     SSPBUF = byteOut;                 // Write to buffer to start a transmit.
  44.     while((SSPSTAT & (1 << 0)) == 0); // Wait till buffer indicator says a receive has been completed
  45.     return SSPBUF;                    // Read the buffer for the received byte.
  46. }
  47.  
  48. void srTx(char byteIn) {
  49.     for(int i = 0; i < 8; i++) {
  50.         /* Transmit byte, ignoring no return */
  51.         spiTxRx(byteIn);
  52.  
  53.         /* Pulse LATh to transfer shift to storage registers. */
  54.         SR_LAT = 0;
  55.         SR_LAT = 1;
  56.     }
  57. }
  58.  
  59. /* ------------- MAIN PROGRAM -------------------*/
  60. void main() {
  61.     spiInit();
  62.     srInit();
  63.  
  64.     /* Display an LED binary counter as a test */
  65.     SPI_CS = 0;
  66.     for(int i = 0; i < 255; i++) {
  67.         srTx(i);
  68.         DelayMs(100);
  69.     }
  70.     SPI_CS = 1;
  71.  
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement