PIC 12F675 based Solar Battery Charger

This circuit was build to control charging/discharging of a solar powered battery. A 12F675 monitors the battery voltage through an ADC channel and connects/disconnects solar panel and the load to avoid over charging and over discharging the battery.

An LED connected to the micro controller indicates the state of the battery. When the battery is fully charged (>13v) it blinks in long pulses (2s) and the solar panel is disconnected. When the battery is charging i.e. 12.3v to 13v short pulses about 200ms in each 2s. When the voltage drops below 12.3v the load is disconnected from the battery and LED is blinked  two 25ms pulses in each 2s interval.

But there is an issue with this circuit. When the load is connected while the battery is charged to say 12.5v, battery voltage suddenly drops below 12.3v due to current demand from the load and the internal resistance. Open circuit voltage of a battery is not what you get while running. When the load is disconnected, voltage goes back to the original value. This causes the circuit to take false decision and disconnect the load, then voltage restores and the load is connected back… endless loop. This can be avoided if we can detect when the load (say home lighting system) is taking current. A current sense resistor can be used for this. At that time program should use somewhat lower voltage to determine the ‘low battery’ state.

Image

 

1.1

Image

Note that the solar panel is connected through a  normally closed relay pins and the load connected through normally open pins.

 

Program (HiTec-C)

#include <htc.h>
#include <pic.h>

__CONFIG(UNPROTECT & WDTDIS & BORDIS & MCLRDIS & PWRTDIS & WDTDIS & INTIO); 

#define _XTAL_FREQ 4000000

void init()
{
    TRISIO = 0b00000001; 
    CMCON = 0b00000111; // Comparator Off
    ADCON0 = 0b10000001; // Ref = Vdd, Chan = 0, AD = On
    ANSEL = 0b01010001; // FOSC/16
    __delay_us(30); // Acquisition Delay Min 20 uSec
}

int read_adc()
{
    unsigned int n;
    GODONE = 1; // Start conversion
    while(GODONE); // wait for done
    n = (unsigned int)ADRESH << 8 | ADRESL;
    return n;
}

void delay_ms(int n)
{
    while (n-- > 0)
        __delay_ms(1);
}

void FlashLED(int delay, int count)
{
    while (count-- > 0)
    {
        GPIO2 = 1;
        delay_ms(delay);
        GPIO2 = 0;
        delay_ms(delay);
    }
}

void main(void)
{
    init();

    GPIO1 = 0;
    GPIO5 = 0;

    FlashLED(1000, 1);

    while (1)
    {
        unsigned int t;
        int bCharging;
        int bReady;

        t = read_adc();
 
        // Note: adjust following magic numbers according to your setup.
 
        // Battery Level High
        if (t > 900)
        {
            GPIO5 = 1; // stop charging
            bCharging = 0;
        }
        else if (t < 860)
        {
            GPIO5 = 0; // charging
            bCharging = 1;
        }
 
        // Battery Level Low
        if (t < 750)
        {
            bReady = 0; // battery is discharged a lot
            GPIO1 = 0; // disconnect the load
            delay_ms(30000);
        }
        else if (t > 770)
        {
            GPIO1 = 1; // battery ready for working
            bReady = 1;
        }

        if (bCharging == 0) // > 13v
            FlashLED(2000, 1);
        else if (bReady == 1) // > 12.3v 
            FlashLED(200, 1);
        else if (bReady == 0) // < 12.3v
            FlashLED(25, 2);

        delay_ms(2000);
    }
}

My Homemade CNC version 2 with USB Driven PIC16F877A Driver

This is the second version of my CNC machine that is capable of cutting plywood. (see version 1)

DSCF1099

DSCF1590

Skate bearings on L-Iron bars

333

Home made mechanical encoders. I later removed these and made the system open loop.

555

The controller software.

DSCF1589

PSU, Stepper Drivers and PIC

DSCF1588 DSCF1587 DSCF1586

Sketchup Models

1

X-Axis (bed)

2 3

Y-axis with Z-axis motor attached

4

Z-axis and router

Components

* 3A Stepper motors (280 oz-in I guess)
* Cheap TB6560 stepper drivers 24V-3A
* Thread bars and double nuts
* Skate bearings on rails
* 24V 10A SMPS
* CP210x USB-TTL module.
* Homemade Firmware (CCS-C) and driver program (VC++)
* PIC16F877A (more than enough)
* 1/4 inch Trim router + 2mm HSS end mill + V-bit

PIC Program (CCS-C)

core of the code

void main()
{
    int8 c;

    Setup();

    output_high(RED_LED);

    output_low(PIN_X_EN); // disable
    output_high(PIN_Y_EN);
    output_high(PIN_Z_EN);

    delay_ms(1000);
    output_low(RED_LED);
    output_low(GREEN_LED);

    while (TRUE)
    {
       output_high(LED_READY); // RX indicator
       c = my_getc();
       output_low(LED_READY); // RX indicator
       if (c == 0xff) // reset comm
       {
          gi_CmdCount = 0;
          gi_NextCmd = 0;
          continue;
       }
       else if (c == 0xfe) // end of transmission 
       {
          while (gi_CmdCount > 0)
          {
              output_high(LED_WORKING);
              DoNext();
              output_low(LED_WORKING);
          } 
      }

      if (gi_CmdCount >= MAX_CMDS)
      {
          SendNack(ERR_MSG_LIMIT);
          gi_CmdCount = 0;
          gi_NextCmd = 0;
          continue;
      }
      set_cmd(gi_CmdCount, c);
      gi_CmdCount++;
   }
}
//------------------------------------------------------------------------------
void ConfigureDevice(int8 iScale, int8 iActive, int8 iMaxActive)
{
   gi_Active = iActive;
   gi_Active *= 100;
   gi_MaxActive = iMaxActive;
   gi_MaxActive *= 100;
   gi_Scale = iScale;

   output_low(PIN_X_EN); // disable
   output_high(PIN_Y_EN);
   output_high(PIN_Z_EN);
}
//------------------------------------------------------------------------------
void UpdateDelay()
{
   if (gi_CurActive > gi_Active)
   {
      if (gi_CurActive > 3000) 
         gi_CurActive -= 1000;
      else if (gi_CurActive > 1000) 
        gi_CurActive -= 200;
      else
        gi_CurActive -= 50;
   }
}
//------------------------------------------------------------------------------
void Move(signed int iDir, int iAxis)
{
   // Y dir: Reversed to match hardware

   switch (iAxis)
   {
   case AXIS_X:
   {
     output_bit(PIN_X_DIR, iDir == FWD ? 0 : 1);
     output_high(PIN_X_CLK);
     output_high(LED_STEPPING);
     UpdateDelay();
     delay_us(gi_CurActive);
     output_low(PIN_X_CLK);
     output_low(LED_STEPPING);
     break;
   }
   case AXIS_Y:
   {
     output_bit(PIN_Y_DIR, iDir == FWD ? 0 : 1);
     output_high(PIN_Y_CLK);
     output_high(LED_STEPPING);
     UpdateDelay();
     delay_us(gi_CurActive);
     output_low(PIN_Y_CLK);
     output_low(LED_STEPPING);

     break;
  }
  case AXIS_Z:
  {
     output_bit(PIN_Z_DIR, iDir == FWD ? 1 : 0);
     output_high(PIN_Z_CLK);
     output_high(LED_STEPPING);
     UpdateDelay();
     delay_us(gi_CurActive);
     output_low(PIN_Z_CLK);
     output_low(LED_STEPPING);

     break;
  }
 }
}
//------------------------------------------------------------------------------
void RunManual()
{
 int16 i;

 output_low(LED_READY); 

 while (input_state(PIN_MANUAL) == 1)
 {
   if (input_state(PIN_Z_UP) == 1)
   {
      delay_ms(1000);
      gi_CurActive = gi_MaxActive;

      for (i = 0; i < 32000; i++)
         Move(FWD, AXIS_Z);
   }
   else if (input_state(PIN_Z_DOWN) == 1)
   {
       delay_ms(1000);
       gi_CurActive = gi_MaxActive;

       for (i = 0; i < 32000; i++)
           Move(BWD, AXIS_Z);
   }

   output_high(LED_BUSY);
   delay_ms(50);
   output_low(LED_BUSY);
   delay_ms(50);
 }

 delay_ms(1000);
}
//------------------------------------------------------------------------------
void DoNext()
{
   int8 cmd;
   sint16 a;
   int8 i;
   signed int m;
   signed int n;
   signed int k;

   cmd = get_cmd(gi_NextCmd);
   gi_NextCmd++;
   gi_CmdCount--;

   if (cmd == MOVE_XYZ)
   {
      if (gi_CmdCount < 2)
      {
         SendNack(ERR_ARGC);
         gi_CmdCount = 0;
         gi_NextCmd = 0;
         return;
      }
      m = get_cmd(gi_NextCmd) - 125; // distance
      gi_NextCmd++;
      gi_CmdCount--;
      n = get_cmd(gi_NextCmd) - 125; // axis
      gi_NextCmd++;
      gi_CmdCount--;
      gi_CurActive = gi_MaxActive;
      k = (m < 0 ? BWD : FWD);
      a = gi_Scale * abs(m);
     output_high(PIN_X_EN); // enable
     output_low(PIN_Y_EN);
     output_low(PIN_Z_EN);

     while (a > 0)
     {
        for (i = 0; i < 16; i++)
           Move(k, n);
        a--;

        /*if (input_state(PIN_MANUAL) == 1)
          {
              delay_ms(1000);
              RunManual();
              gi_CurActive = gi_MaxActive;
           }*/
      }

       output_low(PIN_X_EN); // disable
       output_high(PIN_Y_EN);
       output_high(PIN_Z_EN);

        gi_CurActive = gi_MaxActive;
    }
    else if (cmd == CONFIGURE_DEVICE)
    {
        if (gi_CmdCount < 3)
        {
             SendNack(ERR_ARGC);
             return;
        }
        m = get_cmd(gi_NextCmd); // scale
        gi_NextCmd++;
        gi_CmdCount--;
        k = get_cmd(gi_NextCmd); // active 
        gi_NextCmd++;
        gi_CmdCount--;

        i = get_cmd(gi_NextCmd); // max active 
        gi_NextCmd++;
        gi_CmdCount--;

        ConfigureDevice(m, k, i);
   }
   else
   {
      SendNack(ERR_NO_SUCH_CMD);
      gi_CmdCount = 0;
      gi_NextCmd = 0;
      return;
   }
   if (gi_CmdCount == 0) // All cmds executed 
   {
       gi_NextCmd = 0;
       SendAck();
   }
}

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