Sunday, August 30, 2015

Kula6: Midi IO

I have extended my platform to include midi IO, a button and a potentiometer. Here is the schematic of my platform as it is now:


And this is how the board looks:



The code it is simple, just takes Midi input, buffers it and sends it to the output. The purpose of the code was just to test that the hardware was OK.

#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>


unsigned char data[256];
int readPtr = 0;
int writePtr = 0;
int elements = 0;

#define BAUDRATE 31250
#define UBRR 5

void uart_init(int baudrate)
{
  // calculate division factor for requested baud rate, and set it
unsigned short bauddiv = ((F_CPU+(baudrate*8L))/(baudrate*16L)-1);
UBRRL = bauddiv;
#ifdef UBRRH
UBRRH |= bauddiv>>8;
#endif

    UCSRB = ((1<<RXEN) | (1<<TXEN) | (1<<RXCIE));   // Enable Receiver, Transmitter, Receive Interrupt
    UCSRC = ((1<<URSEL) | (1<<UCSZ1) | (1<<UCSZ0));     // 8N1 data frame
}

void uart_putc(unsigned char c)
{
    // wait until UDR ready
    while(!(UCSRA & (1 << UDRE)));
    UDR = c;    // send character
}

ISR(USART_RXC_vect)
{
    unsigned char c = UDR;

    data[writePtr] = c;
    writePtr++;
    elements++;
    if(writePtr == 256){
        writePtr = 0;
    }
}

int main(void)
{
    //Setup the clock
    cli();            //Disable global interrupts
    uart_init(BAUDRATE);
    sei();            //Enable global interrupts

    while(1){
        if(elements > 0){
            uart_putc(data[readPtr]);
            readPtr++;
            elements--;
            if(readPtr>=256){
                readPtr = 0;
            }
        }
        else {
            _delay_ms(10);
        }
    }
    return 0;
}