SNSへはこちら

AVR32マイコンやってみよう(12) - 各種シリアル通信

[以前やった UART] 以外のシリアル通信のコードを示します。コードを示すだけです。

SPI

#include <avr32/io.h>
#include <stdint.h>

void spi_init(void) {
    // MOSI: GPIO14(#34)
    // MISO: GPIO25(#60)
    // SCK: GPIO15(#35)
    // NPCS0(NSS): GPIO16(#36)
    const int MASK_FOR_PORT0 = (1 << 14) | (1 << 15) | (1 << 16) | (1 << 25);

    AVR32_GPIO.port[0].gperc = MASK_FOR_PORT0;
    AVR32_GPIO.port[0].pmr0c = MASK_FOR_PORT0;
    AVR32_GPIO.port[0].pmr1c = MASK_FOR_PORT0;

    AVR32_PM.pbamask |= 1 << 5;

    AVR32_SPI.CR.spien = 1;
    AVR32_SPI.MR.mstr = 1;
    AVR32_SPI.CSR0.bits = AVR32_SPI_BITS_16_BPT;
    AVR32_SPI.CSR0.ncpha = 1;
    AVR32_SPI.CSR0.scbr = 255;
}

void spi_send(uint16_t dat) {
    while( !AVR32_SPI.SR.tdre );
    AVR32_SPI.TDR.td = dat;
}

I2C

#include <avr32/io.h>
#include <stdint.h>

void twi_init(uint8_t addr) {
    // SCL: GPIO9(#28)
    // SDA: GPIO10(#29)
    AVR32_GPIO.port[0].gperc = (1 << 9) | (1 << 10);
    AVR32_GPIO.port[0].pmr0c = (1 << 9) | (1 << 10);
    AVR32_GPIO.port[0].pmr1c = (1 << 9) | (1 << 10);

    AVR32_PM.pbamask |= 1 << 6;

    AVR32_TWI.MMR.dadr = addr >> 1;
    AVR32_TWI.CWGR.ckdiv = 0x7;
    AVR32_TWI.CWGR.chdiv = 0xF;
    AVR32_TWI.CWGR.cldiv = 0xF;

    AVR32_TWI.CR.svdis = 1; // disable slave mode
    AVR32_TWI.CR.msen = 1; // enable master mode
}

void twi_send(uint8_t *dat, uint8_t len) {
    AVR32_TWI.MMR.mread = 0;
    for(int i = 0; i < len; i++) {
        while( !AVR32_TWI.SR.txrdy );
        AVR32_TWI.THR.txdata = dat[i];
    }
    while( !AVR32_TWI.SR.txcomp );
}