Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pic18 spi driver #29

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions include/spi.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#ifndef ROCKETLIB_SPI_H
#define ROCKETLIB_SPI_H

#include <stdbool.h>
#include <stdint.h>
#include <xc.h>

void spi1_init(void);
uint8_t spi1_exchange(uint8_t data);
void spi1_exchange_buffer(uint8_t *data, uint8_t data_len);

#endif
54 changes: 54 additions & 0 deletions pic18f26k83/spi.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include <stdbool.h>
#include <xc.h>

#include "spi.h"

void spi1_init(void) {
TRISC3 = 0;

SPI1CLKbits.CLKSEL = 0;
SPI1BAUD = 0x22;

SPI1CON0bits.MST = 1; // set mode to master
SPI1CON0bits.BMODE = 1; // sets bit mode to constant width
SPI1CON1bits.CKP = 0; // idle state for clk is low
SPI1CON1bits.SSP = 1; // make cs active low
SPI1CON1bits.SDOP = 0;
SPI1CON1bits.SDIP = 0;

SPI1CON1bits.CKE = 1; // change data on falling edge

SPI1CON2bits.TXR = 0; // no transmit required for transfer
SPI1CON2bits.RXR = 1; // receive data in FIFO
SPI1TWIDTH = 0; // 8 bits
// Enable SPI
PIE2bits.SPI1RXIE = 1; // enable interrupts so we know when device has ACK
SPI1CON0bits.EN = 1; // enable SPI
}

/**/
uint8_t spi1_exchange(uint8_t data) {
INTCON0bits.GIE = 0;
SPI1CON2bits.TXR = 0;
SPI1CON2bits.RXR = 1;
SPI1TCNT = 1;
SPI1TXB = data; /*if we're sending data, send it. if we're recieving, this is 0 (unless you
// initialized bad), but makes sure we output a clock*/
while (!PIR2bits.SPI1RXIF) {
} // wait until receive buffer is not empty?? (basically until theres a clock)
data = SPI1RXB;
INTCON0bits.GIE = 1;
return data; // reading should remove top most byte
}

void spi1_exchange_buffer(uint8_t *data, uint8_t data_len) {
// set data length
SPI1TCNTL = data_len;
SPI1TCNTH = 0;
// uint8_t *block = data;
while (data_len) {
*data = spi1_exchange(*data); // sends pointer, so data gets shoved into array
data++; // increment array
data_len--;
}
}
Loading