Discrete Fourier Transformation (DFT) based Spectrum Tracer

DFT can be used to convert audio samples from time domain to frequency domain. That is the dancing spectrum in graphic equalizers. This piece of code (C++ with MFC) traces the spectrum of a wave file.

const double PI = 3.14159265;
const int N = 1024; // DFT point count
void TraceSpectrum(CDC* pDC)
{
char* pzFile ="D:\\in.wav";
HMMIO h = mmioOpen((LPTSTR)pzFile, NULL, MMIO_READ | MMIO_ALLOCBUF | MMIO_DENYWRITE); for (int i = 0; i < 50000; ++i)
{
double realInput[N] = { 0 }; for (int j = 0; j < N; ++j)
{
SHORT iLeft;
SHORT iRight;
mmioRead(h, (HPSTR)&iLeft, 2); // 16 bit samples
mmioRead(h, (HPSTR)&iRight, 2); // 16 bit samples realInput[j] = iLeft / 1000.0;
}
TraceDFT(realInput, pDC);
Sleep(10);
} mmioClose(h, 0);
}

void TraceDFT(double* realInput, CDC* pDC) {
double realOutput[N] = { 0 };
double imagOutput[N] = { 0 }; for (int k = 0; k < N / 2; ++k) // Output is symmetric, hence N/2
{
for (int n = 0; n < N; ++n)
{
// Theory: F(k) = sigma(T(n) * (cos(x) - j*sin(x))) Where x = 2PIkn/N double x = 2 * PI * k * n / N;
double re = realInput[n] * cos(x);
double im = realInput[n] * -sin(x);
realOutput[k] += re;
imagOutput[k] += im;
}
}

// To Decibels
double spectrum[N / 2];
for (int i = 0; i < N / 2; ++i)
{
double d = sqrt(realOutput[i] * realOutput[i] + imagOutput[i] * imagOutput[i]);
d = d < 1 ? 0 : 20 * log(d);
spectrum[i] = min(d, 200);
}
// Draw the graph
pDC->FillSolidRect(0, 0, 1000, 500, 0xffffff);
for (int i = 0; i < N / 2; ++i)
pDC->FillSolidRect(20 + i, 200 - spectrum[i], 1, spectrum[i], 0x0);
}

Output

Image

Homemade Timer Switch from PIC 12F629

Image

Features

  • Runs a device for a specified time duration.
  • Using the single push button at the bottom left, the duration can be programmed from 1s to ~18hrs and it is saved in EEPROM.
  • If the power is interrupted while the timer is on, the remainder is continued when the power comes back.
  • Can be converted to a conventional switch by holding down the push button when the timer is powered on. Repeating the same procedure converts the switch back to the previous programmable state.

How to Program

  • Hold down the push button to enter setup mode. The green LED turns on when entered.
  • Short pressing the push button starts a counter and blinks the green LED.
  • Count the number of blinks. Then the next short press takes the count as seconds or a long press takes it as minutes and stores in EEPROM.

How to Use

  • Short pressing the push button turns the switch on for the pre-programmed duration.
  • A short press can preempt a running switch.

Schematic

Image

Power supply: 6v-200mA transformer -> Rectifier Bridge -> Filter caps -> 7805

Plug base drilled for LEDs and push button.

Image

The ugly inside.

Image

Program:  (CCS-C)

#include <12F629.h>
#FUSES NOWDT //No Watch Dog Timer
#FUSES INTRC_IO //Internal RC Osc, no CLKOUT
#FUSES NOCPD //No EE protection
#FUSES NOPROTECT //Code not protected from reading
#FUSES MCLR //Master Clear pin enabled
#FUSES NOPUT //No Power Up Timer
#FUSES NOBROWNOUT //No brownout reset
#use delay(int=4000000)

#define PUSH_BTN    PIN_A0
#define SETUP_LED   PIN_A1
#define RUN_LED     PIN_A2
#define RELAY       PIN_A4
#define SPEAKER     PIN_A5
#define DEBOUNCE_DELAY   30 // ms
#define SHORT_PRESS      1
#define LONG_PRESS       2
#define RELEASE_TIME_OUT 3 // took too long to release
int16 gi_TimerDuration = 0; // The switch is kept on this amount of seconds
int16 gi_Remaining = 0; // Number of seconds remaining to switch off
//------------------------------------------------------------------------------
void PerSecond() // This gets called per second
{
    if (gi_Remaining > 0)
    {
        gi_Remaining--;

        // In each ~32 seconds, save remainder to continue automatically after a power outage
        if ((gi_Remaining & 0x1f) == 0) 
        {
             write_eeprom(2, gi_Remaining & 0xff);
             write_eeprom(3, gi_Remaining >> 8);
        }

        // Toggle Running indicator at last 10s
        //if (gi_Remaining < 10)
        // output_bit(RUN_LED, gi_Remaining & 0x1);
    }
    else if (gi_Remaining == 0)
    {
        output_low(RELAY);
        output_low(RUN_LED);
    }
}
//------------------------------------------------------------------------------
int16 time = 0; // driven by timer0
#INT_TIMER0 
void isr_timer0_overflow()
{
    time++;
    if (time < 3840)
       return;

    time = 0;
    PerSecond();
}
//------------------------------------------------------------------------------
void WaitForButtonPushDown()
{
    while (true)
    {
        int n;
        int i;

        while (input_state(PUSH_BTN) == 0)
            continue;

        // Some times this is sensitive to power glitches.
        // Read consecutive 5 HIGHs to verify.
        n = 0;
        for (i = 0; i < 5; ++i)
        {
             n += input_state(PUSH_BTN);
             delay_us(200);
        }

        if (n == 5) // OK. we are satisfied
            break;
    }

    delay_ms(DEBOUNCE_DELAY);
}
//------------------------------------------------------------------------------
int WaitForButtonReleaseOrTimeout()
{
    int16 t;

    // Wait till release or time out
    t = 0;
    while (input_state(PUSH_BTN) == 1)
    {
         output_high(SPEAKER);
         delay_us(300);
         output_low(SPEAKER);
         delay_us(300);

         if (t == 500) // 1500 // ~1s time out
             return RELEASE_TIME_OUT;

         t++;
    }
    delay_ms(DEBOUNCE_DELAY);

    if (t < 300) // less than half a second
        return SHORT_PRESS;
    else
        return LONG_PRESS;
}
//------------------------------------------------------------------------------
int WaitForButtonPress()
{
    WaitForButtonPushDown();
    return WaitForButtonReleaseOrTimeout();
}
//------------------------------------------------------------------------------
void DoTheJob()
{
    if (gi_TimerDuration == 0) // holiday
        return;

    // Start new service cycle
    gi_Remaining = gi_TimerDuration;
    output_high(RELAY);
    output_high(RUN_LED);
}
//------------------------------------------------------------------------------
void StopTheJob()
{
    if (gi_Remaining == 0) // already stoped
        return;

    gi_Remaining = 0;
    output_low(RELAY);
    output_low(RUN_LED);

    write_eeprom(2, 0);
    write_eeprom(3, 0);
}
//------------------------------------------------------------------------------
void RunSetup()
{
    int16 seconds;
    int16 t;
    int a;

    // Enter the setup mode
    output_high(SETUP_LED);

    // If we entered here in case of a timeout, Wait until button release 
    while (input_state(PUSH_BTN) == 1)
        continue;
    delay_ms(DEBOUNCE_DELAY);

    // Wait for a short press to start reading the duration input from user
    a = WaitForButtonPress();
    if (a == LONG_PRESS || a == RELEASE_TIME_OUT)
    {
        // Exit setup mode
        output_low(SETUP_LED);

        // Wait until release in case of a timeout
        while (input_state(PUSH_BTN) == 1)
            continue;
        delay_ms(DEBOUNCE_DELAY);

        return;
    }

    // Short press.
    // Read user input in seconds (i.e. time till next push down)
    seconds = 0;
    t = 0;
    while (input_state(PUSH_BTN) == 0)
    {
        delay_ms(7);// 10
        t++;
        output_bit(SETUP_LED, t > 90 ? 1 : 0);

        if (t == 100) // 1s
        {
            t = 0;
            seconds++;
        }
    }
    delay_ms(DEBOUNCE_DELAY);

    output_high(SETUP_LED); // as this LED is used above for 1Hz blink

    // Wait for a press to complete reading the duration input from user
    a = WaitForButtonReleaseOrTimeout();
    if (a == LONG_PRESS || a == RELEASE_TIME_OUT) // input in minutes
        gi_TimerDuration = seconds * 60; // Read minutes in seconds
    else if (a == SHORT_PRESS) // input is in seconds
        gi_TimerDuration = seconds;

    write_eeprom(0, gi_TimerDuration & 0xff);
    write_eeprom(1, gi_TimerDuration >> 8); 

    // Exit setup mode.
    output_low(SETUP_LED);
    // Wait until release
    while (input_state(PUSH_BTN) == 1)
        continue;
    delay_ms(DEBOUNCE_DELAY);
}
//------------------------------------------------------------------------------
void main()
{
    int switch_mode; // Regular or Timer

    setup_timer_0(RTCC_INTERNAL | RTCC_DIV_1);

    output_high(RUN_LED);
    output_high(SETUP_LED);
    delay_ms(100);

    output_low(RELAY);
    output_low(RUN_LED);
    output_low(SETUP_LED);
    delay_ms(1000); // env stabilization

    // EEPROM
    // Byte [0,1] -> gi_TimerDuration
    // Byte [2,3] -> gi_Remaining
    // Byte [4] -> switch_mode. 1=Regular Switch, else=Timer Switch 

    switch_mode = read_eeprom(4);

    // This is to switch between Regular and Timer modes. Hold down the button
    // when micro is powered on.
    if (input_state(PUSH_BTN) == 1)
    {
        // Wait until release
        while (input_state(PUSH_BTN) == 1)
        {
             output_high(SPEAKER);
             delay_us(300);
             output_low(SPEAKER);
             delay_us(300);
        }
        delay_ms(DEBOUNCE_DELAY);

        // user wants to toggle the switch mode
        if (switch_mode == 0)
            switch_mode = 1;
        else
            switch_mode = 0;

        write_eeprom(4, switch_mode); 
    }

    if (switch_mode == 1)
    {
        // Regular switch

        output_high(RELAY);
        output_high(RUN_LED);

        while (TRUE)
            continue;
    }

    // Starting Timer mode.

    // Read saved configurations
    gi_TimerDuration = read_eeprom(1);
    gi_TimerDuration = gi_TimerDuration << 8 | read_eeprom(0);
    gi_Remaining = read_eeprom(3); 
    gi_Remaining = gi_Remaining << 8 | read_eeprom(2);

    // Continuity after power outage.
    // Note: we save this in each 32s. so there can be a error of 32s.
    if (gi_Remaining >= 32) // not going to continue remainders of less than 32s
    {
        // little compensation (error / 2) may be preferred.
        gi_Remaining -= 16;
        output_high(RELAY);
    }
    else
        gi_Remaining = 0;

    enable_interrupts(GLOBAL);
    enable_interrupts(INT_TIMER0);

    while (TRUE)
    {
        int a;
        a = WaitForButtonPress();
        if (a == SHORT_PRESS)
        {
            if (gi_Remaining > 0)
                StopTheJob();
            else
                DoTheJob();
        }
        else if (a == LONG_PRESS || a == RELEASE_TIME_OUT)
        {
            RunSetup();
        }
    }
}
//------------------------------------------------------------------------------

Troubleshooting

  1. EEPROM of the microcontroller should be cleared when it is first programmed.
  2. MCLR pin should be kept grounded. If this is not done LEDs will flash rapidly.
  3. Verify your circuit using a simple program. Check LEDs are blinking, switch is working, buzzer is working.
  4. If it still does not work, hold the switch down while power is on. This toggles the behaviour of the switch from programmable to non-programmable and vice versa.

How Others Did

Pavel from Bangladesh has made his own version with some extended features.

539815_10152055538180902_1323642183_n 1511030_10152055538110902_1340965153_n

Homemade CNC v1

This is the first version of my homemade CNC machine (see version 2). It does not have enough power to cut anything but has a reasonable precision in drawing.

Image

It does not have any bearings (other than those inside steppers actually), lead screws run each axis and bear the weight at the same time, reasonably noisy and slow. Each axis (X,Y) is driven by two steppers working synchronously.

Image

Z axis is the head moving mechanism of an old CD ROM drive.

Image

In the above picture Y axis steppers are visible at the top. X axis steppers are in the box at the right hand side. Stepper drivers are based on L298 H-bridges and stays at the same box. This was the first time to work with power electronics. Mani chips left their life.

The base is made of MDF. The working area is about 8″ x 8″. Z axis travels about 1″.

Image

Motor couplers are cheap flexible tubes clamped with hose clips.

Image

Image

This machine is driven by a laptop -> USB to serial TTL converter -> PIC micro -> L298 drivers powered by an ATX PC PSU. As there are no opensource or free CAM softwares that support my configuration, I happened to write my own.

Image

The software accepts images, detect edges, generates tool paths and communicates with the PIC.

If you are trying to make your own homemade CNC, create the mechanical implementation your self and buy some stepper drivers. Do not try to build stepper drivers unless you are a skilled electronics guy. Power electronics is a separate subject that can generate lot of headache. Even a cheap poor quality TB6560 based stepper driver easily defeats most of the H-Bridges. Though steppers are supposed to rotate in steps, they do not. In the natural frequency they just vibrate not rotate (happened to me at 200Hz or 5 ms steps). This is a very sad situation. You have to accelerate the stepper rapidly across this area or start at a larger frequency and lose some steps!

Electromagnetic interference generated by steppers and router is non trivial, that can reset a PIC and stop your work unfinished at the middle. Do not forget the filter capacitors at the power supply and PIC MCLR pin. Do not use the USB power to drive signaling circuit. If your laptop is not intelligent enough to shut down the ports at the correct time then you are very likely to have a laptop with 2/3 ports burnt at the end. So use a separate power supply for the signaling circuit.