Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Tuesday, November 14, 2017

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.




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 
#include 

__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);
    }
}


Sunday, November 12, 2017

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)

Skate bearings on L-Iron bars




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

The controller software

PSU, Stepper Drivers and PIC






Sketchup Models

X-Axis (bed)

Y-Axis

Y-axis with Z-axis motor attached

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
  • 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



Wednesday, November 8, 2017

Tracing Voronoi Diagrams – The Greedy Approach

Voronoi Diagrams are pretty and useful. I use them for PCB isolation milling. This piece of code (C++/MFC) traces the voronoi diagram of some random points. The algorithm is the most simple, lowest performing greedy method.

void TraceVoronoi(CDC* pDC, std::vector<CPoint>& vPoints, std::vector<COLORREF>& vColors)
{
   for (int x = 0; x < 600; ++x)
   {
      for (int y = 0; y < 400; ++y)
      {
         double dMinDist = 100000000;
         CPoint pt;
         int n = 0;
         for (int i = 0; i < vPoints.size(); ++i)
         {
            CPoint a = vPoints[i];
            double d = (x - a.x) * (x - a.x) + (y - a.y) * (y - a.y);
            //double d = abs(x - a.x) + abs(y - a.y); // Manhattan distance
            //double d = max(abs(x - a.x), abs(y - a.y)); // ?? distance

            if (d < dMinDist)
            {
               pt = a;
               n = i;
               dMinDist = d;
            }
         }
         pDC->SetPixelV(x, y, vColors[n]);
      }
   }

   // Draw Seeds
   for (int i = 0; i < vPoints.size(); ++i)
   {
      CPoint a = vPoints[i];
      pDC->FillSolidRect(a.x - 1, a.y - 1, 3, 3, 0x0);
   }
}

Output1



 Output 2 (B/W)


Output 3 (Manhattan Distance)


Output 4 ( Max(x,y) )


Tuesday, November 7, 2017

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);
}


Monday, November 6, 2017

PIC12F629 න් ටයිමර් ස්විච් එකක්


හැකියාවන්

  • උපකරණයක් දෙන ලද කාලයක් ක්‍රියාත්මක කර තබන්න පුළුවන්.
  • පහල බොත්තම භාවිතා කර තප්පර 1 සිට පැය 18 දක්වා කාලය වෙනස් කර ගන්න පුළුවන්.
  • මගදි කරන්ට් එක ගියොත් ආපහු ආවට පස්සේ ඉතුරුටික වැඩ කරනවා.
  • අවශ්‍ය නම් සාමාන්‍ය ස්විච් එකක් බවට පත් කර ගන්නත් නැවත ටයිමර් ස්විච් එකක් බවට පත් කර ගන්නත් පුළුවන්.

වෙලාව සකසන හැටි

  • පහල බොත්තම ඔබාගෙන ඉන්නකොට කොළ බල්බය පත්තුවෙනවා
  • ආයෙ බොත්තම එබුවාම කොළ බල්බය නිවී නිවී පත්තු වෙන්න පටන් ගන්නවා.
  • පත්තුවෙන වාර ගාන ගැනගෙන යන්න. අවශ්‍ය ගනනේදී 
    • බොත්තම එබුවොත් ගැනපු ගානට සමාන තප්පර ගානකට වැඩ කරන්න ස්විචය මතක තියා ගන්නවා. 
    • බොත්තම දිගටම ඔබාගෙන හිටියොත් ගැනපු ගාන විනාඩි වලින් තමයි මතක තියාගන්නේ.

පාවිච්චි කරන හැටි

  • බොත්තම එබුවොත් වැඩකරන්න පටන්ගන්නවා. සකසපු වෙලාව ගතවුනාම ඉබේම නවතිනවා. 
  • කාලය ඉවරවෙන්න කලින් ආයෙ බොත්තම එබුවොත් වැඩකරන එක නවතිනවා.

පරිපථය


බල සැපයුම: 6v-200mA ට්‍රාන්ස්ෆෝමර් එක > ඍජුකාරක පරිපථය  > 7805


LED සහ push button එක සඳහා plug base එක හිල් කලා


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();
        }
    }
}
//------------------------------------------------------------------------------

අනිත් අය හදපු හැටි

බංගලාදේශයේ පවෙල් මේ විදියට හදලා තිබුනා.



Tuesday, October 31, 2017

Ray Tracer: Hello world

Ray tracing is a complex subject. It needs reasonable amount of mathematics to write even a simple one. But that kind of simple one still generates awesome output. The basic theory is to simulate the travel of light rays from one or more light sources to the eye, subjecting to reflections, refraction and deflections by various objects through its way. To reduce the computational complexity a view is assumed in-front of eye (or camera) and calculates the color of each pixel in the view, based on the amount and hue of the light that may arrive there.


Sphere rendered with ray tracing



A vector class is essential to write a ray tracer.

class vec
{
public:
    vec()                   { x = y = z = 0; }
    vec(double _x, double _y, double _z) { x = _x; y = _y; z = _z; }

    vec operator-(vec& rhs) { return vec(x - rhs.x, y - rhs.y, z - rhs.z); }
    vec operator-()         { return vec(-x, -y, -z); }
    vec operator+(vec& rhs) { return vec(x + rhs.x, y + rhs.y, z + rhs.z); }
    vec operator*(double t) { return vec(x * t, y * t, z * t); }
    double dot(vec& r)      { return x * r.x + y * r.y + z * r.z; }
    vec cross(vec& r)       { return vec(y * r.z - z * r.y, z * r.x - x * r.z, 
                                     x * r.y - y * r.x); }
    double length()         { return sqrt(x * x + y * y + z * z); }
    bool is_equal(vec& r, double eps) { return abs(x - r.x) < eps && abs(y - r.y) < eps 
                                               && abs(z - r.z) < eps; }

    void normalize()
    {
        double d = length();
        x /= d;
        y /= d;
        z /= d;
    }

    static double angle(vec v1, vec v2) { return acos(v1.dot(v2) 
                                                / (v1.length() * v2.length())); }

    double x;
    double y;
    double z;
};

Our first attempt is to trace a sphere illuminated by one omnidirectional light source. For that, this handy function is also required.

bool IntersectLineAndSphere(vec a, vec u, vec S, double r, double& t)
{
    // Line R = a + u*t
    // Sphere center S with radius r. x*x + y*y + z*z = r*r
    // To find the intersection point of ray and the sphere substitute ray on 
    // circle and solve 
    // the quadratic equation for minimum positive t.
    double A = 1;
    double B = 2 * (u.x * (a.x - S.x) + u.y * (a.y - S.y) + u.z * (a.z - S.z));
    double C = (a.x - S.x) * (a.x - S.x) + (a.y - S.y) * (a.y - S.y) 
               + (a.z - S.z) * (a.z - S.z) - r * r;
    double D = B * B - 4 * A * C;
    if (D >= 0)
    {
        double t1 = (-B + sqrt(D)) / 2;
        double t2 = (-B - sqrt(D)) / 2;
        // assuming t1 > 0 && t2 > 0 for this specific setup and as t1 >= t2
        t = t2;
        return true;
    }
    return false;
}

Rays (straight line) are represented in parametric form R = a + ut or x = x0 + dx * t, y = y0 + dy * t, z = z0 + dz * t where t is the parameter that vary along the line. Above function returns the parameter value at the nearest intersection point.

Step 1

Lets forget the light source. Just check where the sphere is.

void Trace(CDC* pDC)
{
    const double PI = 3.14159;
    const double eps = 0.001;

    // Eye or camera
    vec e(0, 0, 0);

    // View port
    vec vp0(-200, -200, 200);
    int vpcx = 400;
    int vpcy = 400;

    // Sphere
    vec S(0, 0, 450);
    double r = 300;

    for (int vpy = vp0.y; vpy < vp0.y + vpcy; ++vpy)
    {
        for (int vpx = vp0.x; vpx < vp0.x + vpcx; ++vpx)
        {
            // For each pixel in view port, the unit vector of ray is
            vec u(vpx - e.x, vpy - e.y, vp0.z - e.z);
            u.normalize();

            int color;
            double t;
            if (IntersectLineAndSphere(e, u, S, r, t))
                color = 100;
            else
                color = 0;

            pDC->SetPixel(vpcx / 2 - vpx, vpcy / 2 - vpy, RGB(color, color, color));
        }
    }
}



Step 2

Easily decorate the background with a checkerboard pattern.


void Trace(CDC* pDC)
{
    ...

    for (int vpy = vp0.y; vpy < vp0.y + vpcy; ++vpy)
    {
        for (int vpx = vp0.x; vpx < vp0.x + vpcx; ++vpx)
        {
            ...

            double t;
            if (IntersectLineAndSphere(e, u, S, r, t))
            {
                 int color = 100;
                 pDC->SetPixel(vpcx / 2 - vpx, vpcy / 2 - vpy
                               , RGB(color, color, color));
            }
            else // no intersection
            {
==>              bool dark = (int)(vpx - vp0.x) / 8 % 2 != (int)(vpy - vp0.y) / 8 % 2;
==>              pDC->SetPixel(vpcx / 2 - vpx, vpcy / 2 - vpy
                               , dark ? 0x0 : 0x202020); // grid
            }
        }
    }
}


Step 3

The sphere is illuminated by the ambient light only. i.e. each point on sphere has a constant brightness value. That light is emitted radially. So amount of light coming from the points at boundary is less than that near the center.

void Trace(CDC* pDC)
{
    ...

    for (int vpy = vp0.y; vpy < vp0.y + vpcy; ++vpy)
    {
        for (int vpx = vp0.x; vpx < vp0.x + vpcx; ++vpx)
        {
            ...

            double t;
            if (IntersectLineAndSphere(e, u, S, r, t))
            {
                 vec vi = e + u * t; // intersection point
                 vec vn = (S - vi) * (1 / r); // surface normal
                 vn.normalize();

==>              double c = (PI / 2 - abs(vec::angle(vn, u))) / (PI / 2) * 256;
==>              int color = min(c / 3, 255);
                 pDC->SetPixel(vpcx / 2 - vpx, vpcy / 2 - vpy, RGB(color, color, color));
            }
            else // no intersection
            {
                 ...
            }
        }
    }
}

Step 4

Lights ON. Check whether the light hits the point that we are interested on. Calculate the amount of light that is reflected towards the selected pixel in the view port. Ambient light turned off to see the reflected light only. Various magic numbers are required to tune the light.

void Trace(CDC* pDC)
{
    ...
    // Omnidirectional Light
    vec L(-400, 400, -600);
    for (int vpy = vp0.y; vpy < vp0.y + vpcy; ++vpy)
    {
        for (int vpx = vp0.x; vpx < vp0.x + vpcx; ++vpx)
        {
             // For each pixel in view port, the unit vector of ray is
             vec u(vpx - e.x, vpy - e.y, vp0.z - e.z);
             u.normalize();
             double t = 0;
             if (IntersectLineAndSphere(e, u, S, r, t))
             {
                  vec vi = e + u * t; // intersection point
                  vec vn = (S - vi) * (1 / r); // surface normal
                  vn.normalize();
                  int color = 0;
                  // Check if light hits this point.

                  // Unit vector of light
                  vec uL = vi - L;
                  uL.normalize();
                  if (IntersectLineAndSphere(L, uL, S, r, t))
                  {
                      vec vL1 = L + uL * t; // nearest point to the light
                      if (vL1.is_equal(vi, eps)) // light hits here
                      {
                          // reflected light
                          vec vr = vn * uL.dot(vn) * 2 - uL;
                          double c = (PI - abs(vec::angle(u, vr))) / PI * 256;
                          c = c * c / 256 + c * c * c / 256 / 500;
                          color += min(c / 1.5, 255);
                       }
                   }
                   pDC->SetPixel(vpcx / 2 - vpx, vpcy / 2 - vpy, RGB(color, color, color));
              }
              else // no intersection
              {
                   ...
              }
         }
     }
}

Step 5

Ambient + Reflection