Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdint.h>
- #include <msp430.h>
- #include "i2c.h"
- volatile uint8_t *i2c_out_buffer;
- volatile uint16_t i2c_out_buffer_size;
- volatile uint8_t *i2c_in_buffer;
- volatile uint16_t i2c_in_buffer_size;
- void i2c_init() {
- P4SEL |= BIT1 | BIT2;
- UCB1CTL1 = UCSWRST;
- UCB1CTL0 = UCMST | UCSYNC | UCMODE_3;
- UCB1CTL1 |= UCSSEL__SMCLK;
- UCB1BR0 = 50; // 400 kHz
- UCB1BR1 = 0;
- UCB1CTL1 &= ~UCSWRST;
- UCB1IE = UCNACKIE | UCTXIE | UCRXIE;
- }
- int i2c_busy() {
- return (UCB1STAT & UCBBUSY);
- }
- void i2c_request(uint8_t addr, uint8_t *send_buffer, uint16_t send_buffer_size, uint8_t *recv_buffer, uint16_t recv_buffer_size, int wait) {
- while (i2c_busy());
- i2c_out_buffer = send_buffer;
- i2c_out_buffer_size = send_buffer_size;
- i2c_in_buffer = recv_buffer;
- i2c_in_buffer_size = recv_buffer_size;
- UCB1I2CSA = addr;
- i2c_nack = 0;
- if (send_buffer_size) {
- UCB1CTL1 |= UCTR;
- } else {
- UCB1CTL1 &= ~UCTR;
- if (i2c_in_buffer_size == 1) {
- UCB1CTL1 |= UCTXNACK;
- }
- }
- UCB1CTL1 |= UCTXSTT;
- if (wait) {
- while (i2c_out_buffer_size || i2c_in_buffer_size);
- }
- }
- void __attribute__((interrupt(USCI_B1_VECTOR))) USCI_B1_ISR() {
- switch (UCB1IV) {
- case 2: // Arbitration lost
- break;
- case 4: // No ACK
- UCB1CTL1 |= UCTXSTP;
- i2c_nack = 1;
- break;
- case 6: // Start received
- break;
- case 8: // Stop received
- break;
- case 12: // Data sent
- if (i2c_out_buffer_size) {
- UCB1TXBUF = *i2c_out_buffer;
- i2c_out_buffer++;
- i2c_out_buffer_size--;
- } else {
- if (i2c_in_buffer_size) {
- UCB1CTL1 &= ~UCTR;
- UCB1CTL1 |= UCTXSTT;
- if (i2c_in_buffer_size == 1) {
- UCB1CTL1 |= UCTXNACK;
- }
- } else {
- UCB1CTL1 |= UCTXSTP;
- }
- }
- break;
- case 10: // Data received
- *i2c_in_buffer = UCB1RXBUF;
- i2c_in_buffer++;
- i2c_in_buffer_size--;
- if (i2c_in_buffer_size == 1) {
- UCB1CTL1 |= UCTXNACK;
- } else if (i2c_in_buffer_size == 0) {
- UCB1CTL1 |= UCTXSTP;
- }
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement