Wednesday, April 5, 2017

Note On Note Off

This code uses the PIC12f1822 UART (EUSART) to send a note on and off message.  I tested this and it seems to work OK. 220 ohm resistor on the output pin and 220 ohm resistor to +5 V.

/*
 * File:   T1822MIDIMain.c
 * Author: hmikelson
 *MIDI Test Program
 *
 * Created on April 5, 2017, 10:49 AM
 */

#if defined(__XC)
    #include <xc.h>
#endif

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

__CONFIG(MCLRE_ON & CP_ON & WDTE_OFF & BOREN_OFF & FOSC_INTOSC);

#define _XTAL_FREQ 16000000

void init()
{
    TRISA  = 0b00000000; // all bits output
    OSCCON = 0b01111010;  // set internal osc to 16 MHz
}

char UART_Init(const long int baudrate)
{
    unsigned int x;
    x = (_XTAL_FREQ - baudrate*64)/(baudrate*64);
    if(x>255)
    {
        x = (_XTAL_FREQ - baudrate*16)/(baudrate*16);
        BRGH = 1;
    }
    if(x<256)
    {
        SPBRG = x;
        TXEN = 1;
        SYNC = 0;
        SPEN = 1;
        CREN = 1;
        return 1;
    }
    return 0; //Fail
}

void UART_Write(char data)
{
    while(!TRMT);
    TXREG = data;
}

char UART_TX_Empty()
{
    return TRMT;
}

//Note On
void NoteOn(char ch, char note, char vel)
{
    char chan;
    ch = ch - 1;
    chan = (0b10010000 | ch);
    UART_Write(chan);
    UART_Write(note);
    UART_Write(vel);
}

//Note Off
void NoteOff(char ch, char note, char vel)
{
    char chan;
    ch = ch - 1;
    chan = (0b10000000 | ch);
    UART_Write(chan);
    UART_Write(note);
    UART_Write(vel);
}

void main()
{
    init();
    UART_Init(31250);
    while(1)
    {
        NoteOn(1,64,64);
        __delay_us(1000000);
        NoteOff(1,64,0);
        __delay_us(1000000);
    }
}

No comments:

Post a Comment