Analog Stepper Gauge Friday night fun

Took a while to clear off the bench tonight. I got a little happy with the ORDER button last week through weekend. I’ve filled two more parts storage containers and luckily one of my new packages with another parts storage container from Amazon; I couldn’t find any locally, I hope they’re still making them.

The last thing I got to was this “Gauge Stepper Breakout” I got off The Rengineer (The Renaissance Engineer)’s Tindie store. Adam took this very nice stepper motor, put a gauge needle on it (which I believe he 3D printed, or at least it looks like it) and some nice diodes for voltage protection. What’s great about this board is you can drive it right from your microcontroller. I’m sure I don’t need to tell you how weird that is.. I worry about big LEDs.. but here this stepper was happy as a clam being powered by my PIC. I still might consider at least buffering this if I was to place it in a permanent  circuit.

Adam’s provides links to some Arduino libraries but he was saved me a ton of time and just happened to have some PIC sample code! Not before I had about 75% of a ECCP program completed. (I’ll link some of that code if you’re looking for an example of Enhanced PWM output). Once I had Adam’s code I ported it to the TAUTIC 18F26K22 dev board because I already had one on the breadboard. That was mostly changes in the TMR0 (timer 0) code. The only thing of note is check out my IO comments for wiring. You have to cook up 5V/GND to this board then I drove RC3 –> A1 RC2 — A2, RC1 –> B1 and RC0 –> B2. When I had it flipped around the stepper moved in the opposite direction of how I wanted.

A little video of the code in action:

This code is a little sloppy but I just testing this out and it did the trick:


/*
 * File:   main.c
 * Author: Charles M Douvier  Contact at: http://iradan.com
 * Core Driver Code by Adam F. of http://www.therengineer.com/
 *
 * Created on April 4th, 2014
 *
 * Target Device:
 * TAUTIC PIC 18F26K22 Dev Board
 *
 * Project:
 *
 *
 * Version:
 * 1.0
 *
 */

#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4000000 //4Mhz FRC internal osc
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))
#endif

#include 
#include 
#include 
#include 

//config bits
#pragma config FOSC=INTIO67, WDTEN=OFF, PWRTEN=OFF, CP0=OFF, CP1=OFF, BOREN=ON
#pragma config STVREN=ON, LVP=OFF, HFOFST=OFF, IESO=OFF, FCMEN=OFF

//WRT=OFF, FOSC=INTOSC, MCLRE=ON

#define _XTAL_FREQ 4000000 //defined for delay
#define MIN_STEPS_LEFT 23
#define MAX_ACCEL_INDEX 6
#define MAX_STEP 945 /* motor can move 945 steps from stop to stop*/

    int     an8_value, an9_value;          //value for a/d
    char    buf[10];            //buff for iota
    long int    fvar;           //long for format math
    long int    tens;           //left of decm
    long int    decm;           //decimal places
    int     tempi;              //to add leadign zeros..
    int     vtxdata;             //volts int for TX
    int     itxdata;

    unsigned short defaultAccelTable[][2] =
{
  {   1750, 3},
  {   1149, 3},
  {  926,   3},
  {  794,   3},
  {  709,   3},
  {  666,   4},
  {  /*629*/450,   4},
};
unsigned int currentStep;
unsigned char currentState;
unsigned char stateMap[] = {0x09, 0x01, 0x07, 0x06, 0x0E, 0x08};
unsigned char serialBuffer[10];
unsigned char serialByteCount;
 static const unsigned char stateCount = 6;

    volatile unsigned int uart_data;    // use 'volatile' qualifer as this is changed in ISR
/*
 *
 */
void interrupt ISR() {

    if (PIR1bits.RCIF)          // see if interrupt caused by incoming data
    {
        uart_data = RCREG;     // read the incoming data
        PIR1bits.RCIF = 0;      // clear interrupt flag
    }

}

void init_io(void) {
    TRISAbits.TRISA0 = 0; // output
    TRISAbits.TRISA1 = 0; // output
    TRISAbits.TRISA2 = 0; // output
    TRISAbits.TRISA3 = 0; // output
    TRISAbits.TRISA4 = 0; // output
    TRISAbits.TRISA5 = 0; // output
    TRISAbits.TRISA6 = 0; // output
    TRISAbits.TRISA7 = 0; // output

    ANSELA = 0x00; // all port A pins are digital I/O

    LATAbits.LATA0 = 0;
    PORTAbits.RA0 = 0;

    TRISBbits.TRISB1 = 0;   //P1C output
    TRISBbits.TRISB2 = 0;  // P1B output
    TRISBbits.TRISB3 = 1;  // AN9    speed control 0-5V
    TRISBbits.TRISB4 = 0;  // P1D output
    TRISBbits.TRISB5 = 1; // RB5 = nc
    TRISBbits.TRISB6 = 0; // RB6 = nc
    TRISBbits.TRISB7 = 0; // RB7 = nc

    ANSELB = 0b00001000;     //RB3, AN9

    TRISCbits.TRISC0 = 0; // output to B2 .. reversed to stoke the right direction
    TRISCbits.TRISC1 = 0; // output to B1
    TRISCbits.TRISC2 = 0; // output to A2
    TRISCbits.TRISC3 = 0; // output to A1
    TRISCbits.TRISC4 = 0; // output
    TRISCbits.TRISC5 = 0; // output
    TRISCbits.TRISC6 = 0; // output
    TRISCbits.TRISC7 = 0; // output
    ANSELC = 0x00; // all port B pins are digital I/O
}

void uart_xmit(unsigned int mydata_byte) {

    while(!TXSTA1bits.TRMT);    // make sure buffer full bit is high before transmitting
    TXREG = mydata_byte;       // transmit data
}

void serial_init(void)
{
    //9600 8N1
    // calculate values of SPBRGL and SPBRGH based on the desired baud rate
    //
    // For 8 bit Async mode with BRGH=0: Desired Baud rate = Fosc/64([SPBRGH:SPBRGL]+1)
    // For 8 bit Async mode with BRGH=1: Desired Baud rate = Fosc/16([SPBRGH:SPBRGL]+1)

    TXSTA1bits.BRGH=1;       // select low speed Baud Rate (see baud rate calcs below)
    TXSTA1bits.TX9=0;        // select 8 data bits
    TXSTA1bits.TXEN = 1;     // enable transmit

    RCSTA1bits.SPEN=1;       // serial port is enabled
    RCSTA1bits.RX9=0;        // select 8 data bits
    RCSTA1bits.CREN=1;       // receive enabled

    SPBRG1=25;  // here is calculated value of SPBRGH and SPBRGL
    SPBRGH1=0;

    PIR1bits.RCIF=0;        // make sure receive interrupt flag is clear
    PIE1bits.RCIE=1;        // enable UART Receive interrupt
    INTCONbits.PEIE = 1;    // Enable peripheral interrupt
    INTCONbits.GIE = 1;     // enable global interrupt

         __delay_ms(50);        // give time for voltage levels on board to settle

    uart_xmit('R');         // transmit some data
}

// All this motor and timer code is from Adam with very minor changes to fit the processor

void t0Delay(unsigned int usec)
{
    unsigned int t0ticks; //16 microsecond timer0 ticks
    unsigned char t0Preload;
    if(usec<16)
    {
        t0ticks=1;
    }
    else
    {
        t0ticks = usec/16;
    }
    t0Preload = 0xFF - t0ticks;
    INTCONbits.TMR0IF=0; //clear the flag
    TMR0 = t0Preload;
    while(INTCONbits.TMR0IF==0)
    {
        ;
    }
}

void zeroMotor()
{
    unsigned int i;
    for (i=0; i < MAX_STEP; i++)
    {
        LATC=stateMap[currentState];
        currentState = (currentState + 5) % stateCount;
        t0Delay(1900);  //2200 in datasheet
    }
    //now the motor is zeroed, reset our state variables.
    currentStep = 0;
    currentState = 0;
    LATC=0; //turn off coils
}

void moveMotor(unsigned int targetStep)
{
    unsigned int dir;
    unsigned int curDelay;
    unsigned char speedIndex=0;
    unsigned char stepsAtThisSpeed=0;
    unsigned int stepsLeft;
    if(currentStep<targetStep)     {         dir = 1;         stepsLeft = targetStep-currentStep;     }     else     {         dir = -1;         stepsLeft = currentStep - targetStep;     }     while(stepsLeft>0)
    {
        if(stepsLeft<=MIN_STEPS_LEFT)         {             //decellerating             if(stepsAtThisSpeed==0)             {                 if(speedIndex>0)
                    speedIndex--;
                curDelay=defaultAccelTable[speedIndex][0];
                stepsAtThisSpeed=defaultAccelTable[speedIndex][1];
            }
        }
        else
        {

            //accellerating or steady state
            if(stepsAtThisSpeed==0)
            {
                if(speedIndex<MAX_ACCEL_INDEX)                 {                     speedIndex++;                     curDelay=defaultAccelTable[speedIndex][0];                     stepsAtThisSpeed=defaultAccelTable[speedIndex][1];                 }                 //else we're at steady state - do nothing.             }         }         //write step         LATC=stateMap[currentState];         if(dir==1)         {             currentState = (currentState + 1) % stateCount;         }         else         {             currentState = (currentState + 5) % stateCount;         }         t0Delay(curDelay);         if(stepsAtThisSpeed>0)
        {
            stepsAtThisSpeed--;
        }
        stepsLeft--;
        currentStep+=dir;
    }
}

int main(void) {

    init_io();
    serial_init();

    // set up oscillator control register, using internal OSC at 4MHz.
    OSCCONbits.IRCF = 0x05; //set OSCCON IRCF bits to select OSC frequency 4MHz
    OSCCONbits.SCS = 0x02; //set the SCS bits to select internal oscillator block

    ADCON0 = 0b00100101;                            //select AN9 and enable
    ADCON1 = 0b00000000;                  //speed Vref=AVdd, VssRef=AVss
    ADCON2 = 0b00111011;                //ledft justified, 20RAD, FRC

    INTCONbits.TMR0IE = 0;

    TMR0=0;

    T0CONbits.T08BIT = 1;
    T0CONbits.T0CS = 0;
    T0CONbits.PSA = 0;
    T0CONbits.T0PS = 0x04;
    INTCONbits.TMR0IF = 0;

        T0CONbits.TMR0ON = 1;

    __delay_us(5);

    currentStep = 0;
    currentState = 0;

    zeroMotor();         
    __delay_ms(149);        //this could be less messy
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    moveMotor(20);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);
    __delay_ms(149);

    moveMotor(940);
    moveMotor(5);

    while (1) {

        //PORTAbits.RA0 = 1;      //heart beat
        //__delay_ms(50);
        //PORTAbits.RA0 = 0;
        //__delay_ms(50);

        ADCON0 = 0b00100101;    //select AN9 and enable
        __delay_us(5);
        GO = 1;
        while (GO) continue;    //wait for conversion
        an9_value = ADRESH;     //AN9 value

        fvar = an9_value;
        fvar = fvar * 10749;    //calibration.. change to meet your needs
        fvar = fvar / 256;
        tens = fvar / 100;
        //tens = tens % 10;
        decm = fvar % 100;
        vtxdata = fvar / 20;
        uart_xmit(vtxdata);    // -->RS232

        moveMotor(vtxdata);
        //moveMotor(5); //from sample code
    }
    return (EXIT_SUCCESS);
}

Some ECCP ( Enchanced PWM ) code written for the PIC 18F26K22 code I wrote following the screen shot of the output:

Deadband on Enhance PWM mode output on PIC
Deadband on Enhance PWM mode output on PIC

void pwm_init(){

//    CCPR1L = 0x120;
    CCPR1Lbits.CCPR1L = 0xFE;
    PR2 = 0xFE;
    CCPTMRS0bits.C1TSEL = 0;     //CCP TMR2 Selection
    CCP1CONbits.P1M = 0x02;     //half bridge
    CCP1CONbits.DC1B = 0x00;
    PWM1CONbits.P1RSEN = 0;
    PWM1CONbits.P1DC = 0x1F;    //dead band delay
    ECCP1ASbits.CCP1AS = 0x00;
    ECCP1ASbits.CCP1ASE = 0;    //Auto-shutdown off
    CCP1CONbits.CCP1M = 0x0C;
    PSTR1CONbits.STR1A = 1;
    PSTR1CONbits.STR1B = 1;

    T2CONbits.T2CKPS = 1;
    T2CONbits.TMR2ON = 1;

}

//.. now dump something smaller than 127 into CCPR1Lbits.CCPR1L
//to set the pulse width

PIC 18F26K22 PWM+A/D with MOSFET, the start of an eScooter?

I’m considering building an electric scooter; considering it probably putting it lightly.. I have almost everything I need for it.  Interested? Why type so much when you can just watch my proof of concept!

If you’re following along and want to use the same hardware (warning totally untested… ):
Controller found on the TAUTC Tindie Store
Search on eBay for “24VDC scooter motor” ..
..and pick up a MOSFET that’ll pull off a couple 20 amps and saturates at or below 5VDC.
…what am I talking about? Try google or read this.

To the important stuff, the code:


/* 
 * File:   main.c
 * Author: Charles M Douvier
 * Contact at: http://iradan.com
 *
 * Created on March 27, 2014, 4:12 PM
 *
 * Target Device:
 * 18F26K22 on TAUTIC Dev Board
 *
 * Project:
 * Electric Scooter
 *.. a real hack job, comment, delete garbage, etc.
 *
 * Version:
 * 0.1
 *
 */
#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4000000 //4Mhz FRC internal osc
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))
#endif

#include 
#include 
#include 
#include 

//config bits
#pragma config FOSC=INTIO67, WDTEN=OFF, PWRTEN=OFF, CP0=OFF, CP1=OFF, BOREN=ON
#pragma config STVREN=ON, LVP=OFF, HFOFST=OFF, IESO=OFF, FCMEN=OFF

//WRT=OFF, FOSC=INTOSC, MCLRE=ON

#define _XTAL_FREQ 4000000 //defined for delay

//clean up on isle 2.. 

    int     an9_value;          //value for a/d
    char    buf[10];            //buff for iota
    long int    fvar;           //long for format math
    long int    tens;           //left of decm
    long int    decm;           //decimal places
    int     tempi;              //to add leadign zeros..
    int     vtxdata;             //volts int for TX
    int     itxdata;

    volatile unsigned int uart_data;    // use 'volatile' qualifer as this is changed in ISR
/*
 * 
 */
void interrupt ISR() {

    if (PIR1bits.RCIF)          // see if interrupt caused by incoming data
    {
        uart_data = RCREG;     // read the incoming data
        PIR1bits.RCIF = 0;      // clear interrupt flag
    }

}

void init_io(void) {
    TRISAbits.TRISA0 = 0; // output
    TRISAbits.TRISA1 = 0; // output
    TRISAbits.TRISA2 = 0; // output
    TRISAbits.TRISA3 = 0; // output
    TRISAbits.TRISA4 = 0; // output
    TRISAbits.TRISA5 = 0; // output
    TRISAbits.TRISA6 = 0; // output
    TRISAbits.TRISA7 = 0; // output

    ANSELA = 0x00; // all port A pins are digital I/O

    TRISBbits.TRISB3 = 1; // AN9
    TRISBbits.TRISB4 = 0; // RB4 = nc
    TRISBbits.TRISB5 = 1; // RB5 = nc
    TRISBbits.TRISB6 = 0; // RB6 = nc
    TRISBbits.TRISB7 = 0; // RB7 = nc

    ANSELB = 0b00001000;     //RB3, AN9

    TRISCbits.TRISC0 = 0; // output
    TRISCbits.TRISC1 = 0; // output
    TRISCbits.TRISC2 = 0; // output
    TRISCbits.TRISC3 = 0; // output
    TRISCbits.TRISC4 = 0; // output
    TRISCbits.TRISC5 = 0; // output
    TRISCbits.TRISC6 = 1; // input
    TRISCbits.TRISC7 = 1; // input
    ANSELC = 0x00; // all port C pins are digital I/O
}

void pwm_init(){

//         PSTR1CONbits.STR1A
//hackhackhackhack... TODO

//    CCPR1L = 0x120;
    CCPR1Lbits.CCPR1L = 0xFE;
    PR2 = 0xFE;
    CCPTMRS0bits.C1TSEL = 0;     //CCP TMR2 Selection
    CCP1CONbits.P1M = 0x00;
    CCP1CONbits.DC1B = 0x00;
    PWM1CONbits.P1RSEN = 0;
    T2CONbits.T2CKPS = 1;  //1:2 Prescale
    T2CONbits.TMR2ON = 1;  //timer 2 go

    CCP1CON = 0x0C;       //PWM (CCP)1 ON

}

void uart_xmit(unsigned int mydata_byte) {

    while(!TXSTA1bits.TRMT);    // make sure buffer full bit is high before transmitting
    TXREG = mydata_byte;       // transmit data
}

void serial_init(void)
{
    //9600 8N1
    // calculate values of SPBRGL and SPBRGH based on the desired baud rate
    //
    // For 8 bit Async mode with BRGH=0: Desired Baud rate = Fosc/64([SPBRGH:SPBRGL]+1)
    // For 8 bit Async mode with BRGH=1: Desired Baud rate = Fosc/16([SPBRGH:SPBRGL]+1)

    TXSTA1bits.BRGH=1;       // select low speed Baud Rate (see baud rate calcs below)
    TXSTA1bits.TX9=0;        // select 8 data bits
    TXSTA1bits.TXEN = 1;     // enable transmit

    RCSTA1bits.SPEN=1;       // serial port is enabled
    RCSTA1bits.RX9=0;        // select 8 data bits
    RCSTA1bits.CREN=1;       // receive enabled

    SPBRG1=25;  // here is calculated value of SPBRGH and SPBRGL
    SPBRGH1=0;

    PIR1bits.RCIF=0;        // make sure receive interrupt flag is clear
    PIE1bits.RCIE=1;        // enable UART Receive interrupt
    INTCONbits.PEIE = 1;    // Enable peripheral interrupt
    INTCONbits.GIE = 1;     // enable global interrupt

         __delay_ms(50);        // give time for voltage levels on board to settle

    uart_xmit('R');         // transmit some data "restart" notification
}

int main(void) {

    init_io();
    serial_init();
    LATCbits.LATC2 = 0;
    pwm_init();

    // set up oscillator control register, using internal OSC at 4MHz.
    OSCCONbits.IRCF = 0x05; //set OSCCON IRCF bits to select OSC frequency 4MHz
    OSCCONbits.SCS = 0x02; //set the SCS bits to select internal oscillator block

    ADCON0 = 0b00100101;                            //select AN9 and enable
    ADCON1 = 0b00000000;                  //speed Vref=AVdd, VssRef=AVss
    ADCON2 = 0b00111011;                //ledft justified, 20RAD, FRC
    __delay_us(5);

//loop

    while (1) {

        PORTAbits.RA0 = 1; //blinky i'm alive.
        __delay_ms(140);
        PORTAbits.RA0 = 0;
        __delay_ms(140);

            GO = 1;
    while (GO) continue;              //wait for conversion
    an9_value = ADRESH;               //AN9 value

        fvar = an9_value; //this is hacked off another project but works
        fvar = fvar * 10749;        //calibration
        fvar = fvar / 256;
        tens = fvar / 100;
        //tens = tens % 10;
        decm = fvar % 100;
        vtxdata = fvar / 43; //because I'm lazy... I'll change this later.
        uart_xmit(vtxdata);
        CCPR1Lbits.CCPR1L = vtxdata;

    }
    return (EXIT_SUCCESS);
}

A tiny Si4707 WX Radio Project Update

I pulled out the weather radio project today to see what I could get done in a few hours. I was pretty close on finishing off the hardware but I fell a little short right at the end. I found I had forgotten to buy something to convert the regulated 5V to 3.3V for the radio (and PIC since they’re tied together on I2C). I ran into a few issues I totally spaced:1.  The Si4707 requires a reset after power up .. it ignores I2C if you don’t.

2. Pull-ups.. duh, not only on I2C which I had, but don’t forget the Si4707 reset (oops).

I ended up buying a couple random Digikey parts at the ham radio convention and guess what? 10@ MCP1802T-3002I/OT (300mA 3.0V LDO) ..they are SOT23-5 and I had JUST gotten 10 break-out boards in the mail so I ended up having a 5V3.3V converter (close enough anyways, as the PIC and Si4707 work down to 2.7V).. soldered it up but I didn’t have time to pop it in. I used the Weller but I think I’m going to solder another one with the new hot air gun I got this week. I ordered one of those cheap 858D rework stations; I don’t plan on using it too much so hopefully it’ll do the trick. I also got a bunch of SMD protoboards.. so I get to practice reflow this week.

Tomorrow I should be able to finish up the radio and then it’s all software.

Si4707 WX Radio Build - 11MAR14

The photo isn’t the most exciting workbench shot but you can see that 858D in the back corner. The WX radio is the black box right up close to the left.

An evening of measuring inductance

I was inspired by Alan Wolke’s ( @W2AEW ) video on measuring capacitors and inductors with an oscilloscope. I tried it out and it works pretty reasonably; yeah why wouldn’t it? Anyhow, if you can do it on an oscilloscope it can be done by a microcontroller right?  I have been trying to keep myself from buying this $220 eBay LCR meter on eBay.. it looks nice enough (model: MCH2811C). I needed to make this a project or I was going to pull the trigger on some Chinese garbage!

I went with simple and cheap, I don’t know how well it’ll work out yet but I bread-boarded a proof of concept design. It tested okay after some modification. The first road bump was I had found the PIC output pins had unacceptable rise time compared to 74HC14. The first change was using the PIC output to drive the 74HC14 HEX inverter to get the quick rise time needed.  I’m throwing a fast edge at the tank circuit that includes an “unknown” inductor and then I do my measurement, just as Alan used his homebrew TDR circuit. I went really low tech on my measurement circuit, I may change this. I used an LM339 comparator and a trimmer as a voltage divider. The first couple waves in the tank “ring” trigger the comparator and I measure the frequency by figuring out the time between the positive pulses by timer. Pretty simple no? It works fine as it turns out. I will have to get a better capacitor and ensure I measure it very accurately to do my math in the PIC and get a reasonable result.

Instead of the usual photos I made another YouTube video. It wasn’t a great one, one take, no editing.. it’s gets my point across (kind of).

My project proof of concept for the PIC L-meter. With the addition of a known inductor and a rotary switch and a little more code you can turn this into a PIC LC-meter in no time.

 

Project Update: Spunk The Annoying Robot

The last robot I built was a Roomba Sumo Robot (Talos) for a small competition with co-workers. While collecting parts for this little eBay robot platform I got for somewhere in the neighborhood of 15$USD, I grabbed my Pololu motor controller and remember that I wrote that whole Sumo robot in ASM; that was a lot of code between two PICs.

The little robot I’m building now has very few specifications. It’s goal in life is to follow you around, but not too close. It should back away when needed and basically run around, pausing for a while in its search for someone to follow around. My wife named it Spunk because she’s certain to be the one it annoys most.

I’ve built the project as seen in the photo and written all primary code.. ordered a lot of battery management parts to see what I like the best. Determined I can’t get the robot to “find” people with the sensors I have, so I ordered more… so this little guy is half-done. I’ll shelve him until more parts arrive. I really only grabbed it down as it was 4 projects deep in the to-do list because I haven’t kept up with pre-ordering parts, or worse.. ordered the wrong things. I’m still on the hunt for a better display for the WX radio, ordered items for my RS-485 project, etc. etc..

The heart of Spunk is a PIC 18F14K22 on a TAUTIC 20 pin development board. Maybe Jayson ( @TAUTIC ) needs to pay me for all this advertising? 😉 jk.. I just bought a couple of the boards because they fit my type of prototyping perfectly. This was my last one… time to make an order over at @tindie for some more.

Spunk getting probed.
Spunk getting probed.

For now, no code. I’ll post the old ASM code for the Pololu motor controller and the C code as well once it get it properly commented and make sure it at least mostly works. Once I do some real roving tests I’ll throw it on YouTube (and maybe the first tests of Talos as well)… TBC for now.

Checkout: @tymkrs MIDI In Me + PIC18F14K22

I don’t want anyone thinking they’re going to see a bunch of music related items on the blog because I’m really no good at such things. My brother on the other hand is very talented and we recently decided he needed some more MIDI toys. A lot of his music is already created with the help of MIDI.

MIDI is “Musical Instrument Digital Interface“; a standard that defines hardware and protocol. If you want more information on it such as specifications Google is your friend.

My brother had some information on the specification but not really anything that helped me much. I did a lot of reading on the specifications on the MIDI Manufacturers Association webpage and then countless other sites describing the protocol in length. It even looks like there is a tutorial on the Arduino site, although I didn’t look at it because I don’t use them. Again, I’m not going to go into the protocol anymore than I discussed the specification. I’ll let you do that leg work. However, the *really* short version is there are a couple key commands followed (usually) by some extra bytes (generally 1 or 2). All the data is transmitted like normal 8N1 serial data at 31.25kbaud. Lucky for me 31.5k has a nice PIC SPBRG division value for low error rate (at 4MHz).

Hardware Interface: I decided I wasn’t going to build the 5mA loop interface and I remembered the Toymakers ( @tymkrs ) had a nice little interface board already built. One trip on over to their Tinde Store and I had it a few days later.

It’s a small kit, it came well packed, and it fit the bill just fine. I have nothing but praise this little kit with only one tiny little nit-picky mention. I wish they included a URL of the location of the instructions for building the kit. They had a couple resistors and I needed to know what was R1, R2, etc.. it was easy to find, a return trip to Tindie linked instructions, a construction video! and a lot of information on their website. So I know I’m picky.. If they wanted to make a 9.7 a 10.. that’d be it 😉

The Toymakers Midi In Me Kit.
The Toymakers Midi In Me Kit.

After everything was plugged in, code was loaded on the PIC, a MIDI device plugged in.. etc.. I checked out the MIDI kit to see response and how noisy it might be… no complaints here.. it looked good…

MIDI In signal edge TEK0000

The Firmware: It’s just “sample” code. I haven’t written any real output yet because my brother is in charge of the “analog” bits which really means he is going to figure out what he wants in block diagrams and I will have to figure out how to make it happen in circuit. Right now I’m reading the MIDI signal in on UART by interrupt… and checking for my command signal. (I’m using a Control Change because of my MIDI device… you will most likely want to change this). The control change value is 0xB1 in my case, then… my device (Knob #1) which is 0x11 … and finally it gives me a value (knob position 0x00 to 0x7F). I’m taking that position value and transmitting it out the UART to my PC…

 

The output dropped onto my PC. Note: RealTerm allows me to enter in 31250 baud.. 8N1
The output dropped onto my PC. Note: RealTerm allows me to enter in 31250 baud.. 8N1
MIDI on the LA
MIDI on the LA

 

I used the TAUTIC 20 pin dev board (any groaning of “AGAIN??”??) … but a change-up! 🙂 I used a PIC 18F14K22 … because I felt like getting crazy 😉 and the 18 series is optimized for C so I will probably go back to the 18F series … I think the last time I used one was my ESR meter?  A few changes switching to the 18 series.. but nothing huge. Just getting used to slightly different registers.  Last warnings about the code; It’s simple… it’s just checking to see if your interface it working… (or if you’re sending MIDI and you don’t have a scope or LA). It has a lot of clutter because I was using it for some other non-MIDI related testing but it’s easy to spot and delete if you need to copy it as a starting point for whatever you’re working on. (Do share!)

/* 
 * File:   main.c
 * Author: Charles M Douvier
 * Contact at: http://iradan.com
 *
 * Created on February 8, 2014, 11:39 AM
 *
 * Target Device:
 * 18F14K22 on Tautic 20 pin dev board
 *
 * Project: MIDI Slave
 *
 *
 * Version:
 * 0.1  Configuration, 31.25Kbaud TX&RX
 * 0.2  Grab MIDI byte from 31.25K MIDI and turn around and TX the value of the
 *      MIDI command. <CMD: Control Change><Device><Value>
 *      <B1><11><value> //my example
 *
 */
#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4000000 //4Mhz FRC internal osc
#define __delay_us(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000000.0)))
#define __delay_ms(x) _delay((unsigned long)((x)*(_XTAL_FREQ/4000.0)))
#endif

#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//config bits
#pragma config FOSC=IRC, WDTEN=OFF, PWRTEN=OFF, MCLRE=ON, CP0=OFF, CP1=OFF, BOREN=ON
#pragma config STVREN=ON, LVP=OFF, HFOFST=OFF, IESO=OFF, FCMEN=OFF

#define _XTAL_FREQ 4000000 //defined for delay

/*
 * Variables
 */

    long int    decm;           //long temp
    int     tempi;              //temp
    int     i, ilevel;                  //temp
    int     itxdata;            //int RS232 tx data
    char    buf[10];            //buff for iota
    volatile unsigned int uart_data;    // use 'volatile' qualifer as this is changed in ISR

/*
 *  Functions
 */

    void interrupt ISR() {

    if (PIR1bits.RCIF)          // see if interrupt caused by incoming data
    {
        uart_data = RCREG;     // read the incoming data
        PIR1bits.RCIF = 0;      // clear interrupt flag
                                //
    }

}

void uart_xmit(unsigned int mydata_byte) {

    while(!TXSTAbits.TRMT);    // make sure buffer full bit is high before transmitting
    TXREG = mydata_byte;       // transmit data
}

void serial_init(void)
{

    // calculate values of SPBRGL and SPBRGH based on the desired baud rate
    //
    // For 8 bit Async mode with BRGH=0: Desired Baud rate = Fosc/64([SPBRGH:SPBRGL]+1)
    // For 8 bit Async mode with BRGH=1: Desired Baud rate = Fosc/16([SPBRGH:SPBRGL]+1)

    TXSTAbits.BRGH=1;       // select low speed Baud Rate (see baud rate calcs below)
    TXSTAbits.TX9=0;        // select 8 data bits
    TXSTAbits.TXEN = 1;     // enable transmit

    RCSTAbits.SPEN=1;       // serial port is enabled
    RCSTAbits.RX9=0;        // select 8 data bits
    RCSTAbits.CREN=1;       // receive enabled

    //BRGH=1        31.25KHz
    //SPBRG=7

    SPBRG=7;               //

    PIR1bits.RCIF=0;        // make sure receive interrupt flag is clear
    PIE1bits.RCIE=1;        // enable UART Receive interrupt
    INTCONbits.PEIE = 1;    // Enable peripheral interrupt
    INTCONbits.GIE = 1;     // enable global interrupt

         __delay_ms(50);        // give time for voltage levels on board to settle

    //  uart_xmit('S');         // transmit a character example

}

void init_io(void) {
    TRISAbits.TRISA0 = 0; // output
    TRISAbits.TRISA1 = 0; // output
    TRISAbits.TRISA2 = 0; // output
    TRISAbits.TRISA4 = 0; // output
    TRISAbits.TRISA5 = 0; // output

    ANSEL = 0x00;         // no A/D
    ANSELH = 0x00;

    TRISBbits.TRISB4 = 0; // RB4 = nc
    TRISBbits.TRISB5 = 1; // RB5 = nc
    TRISBbits.TRISB6 = 0; // RB6 = nc
    TRISBbits.TRISB7 = 0; // RB7 = nc

    TRISCbits.TRISC0 = 0; // output
    TRISCbits.TRISC1 = 0; // output
    TRISCbits.TRISC2 = 0; // output
    TRISCbits.TRISC3 = 0; // output
    TRISCbits.TRISC4 = 0; // output
    TRISCbits.TRISC5 = 0; // output
    TRISCbits.TRISC6 = 1; // input
    TRISCbits.TRISC7 = 1; // input

}

void set_cmd11(void)
{
    //set an AD output
                while(uart_data==0x11)
            {
                i++; //wait for next char
            }
            ilevel = uart_data;         //finally the value
            uart_xmit(ilevel);
}

void check0xb1(void)
{
    if (uart_data == 0xB1)
    {
            while(uart_data==0xB1)
            {
                i++; //wait for next char
            }
            if ( uart_data == 0x11)     //and the knob 1 is "device 11"... 
               set_cmd11();
    }
}

int main(void) {

    init_io();

    // set up oscillator control register, using internal OSC at 4MHz.
    OSCCONbits.IRCF = 0x05; //set OSCCON IRCF bits to select OSC frequency 4MHz
    OSCCONbits.SCS = 0x02; //set the SCS bits to select internal oscillator block

    serial_init();

    decm=30;            //testing

    ltoa(buf,decm,10);  //long conversion to buffer
    tempi=strlen(buf);  //uh, adding leading zeros..
    uart_xmit('+');
    uart_xmit(itxdata);
    uart_xmit('.');
    LATAbits.LATA0=0;

    while (1) {

        i++;

        while (uart_data)
        {
            check0xb1();    //my midi device is sending a Control Change 0xB1
            uart_data=0;
        }

    }
    return (EXIT_SUCCESS);
}