#!/usr/bin/perl

# Script to quickly calculate the specs for a capacitive power supply with
# a bridge rectifier. 
#
# BUILDING SUCH A DEVICE IS VERY DANGEROUS (NO ISOLATION FROM MAINS POTENTIAL).
# USE AT YOUR OWN RISK.

# Constants
$pi = 3.14159265;

# Default values
$net_min = 220;      $net_max = 250;
$freq = 50;          $freq_tol = 0.01;
$zd_size = 6.8;      $zd_tol = 0.05;
$cap_size = 4.7e-07; $cap_tol = 0.2;
$res_size = 470;     $res_tol = 0.1;

# User input
print "AC voltage minimum and maximum (default: $net_min $net_max): ";
while (<>) { $_ =~ m/([\d\.]+)\s+([\d\.]+)/ and ($net_min, $net_max) = ($1,$2); last; }

print "Net frequency and tolerance (default: $freq $freq_tol): ";
while (<>) { $_ =~ m/([\d\.]+)\s+([\d\.]+)/ and ($freq, $freq_tol) = ($1,$2); last; }

print "Z-Diode size and tolerance (default: $zd_size $zd_tol): ";
while (<>) { $_ =~ m/([\d\.]+)\s+([\d\.]+)/ and ($zd_size, $zd_tol) = ($1,$2); last; }

print "Capacitor size and tolerance (default: $cap_size $cap_tol): ";
while (<>) { $_ =~ m/([\d\.e\-]+)\s+([\d\.]+)/ and ($cap_size, $cap_tol) = ($1,$2); last; }

print "Resistor size and tolerance (default $res_size $res_tol): ";
while (<>) { $_ =~ m/([\d\.]+)\s+([\d\.]+)/ and ($res_size, $res_tol) = ($1,$2); last; }

# Calculation
$V_min = ( (sqrt(2) * $net_min) - ($zd_size + $zd_tol * $zd_size) ) / sqrt(2);
$R_min = 1 / ((1 / (2 * $pi * ($freq - $freq * $freq_tol) * ($cap_size - $cap_size * $cap_tol))) + ($res_size + $res_size *  $res_tol));

$V_max = ( (sqrt(2) * $net_max) - ($zd_size - $zd_tol * $zd_size)) / sqrt(2);
$R_max = 1  / ((1 / (2 * $pi * ($freq + $freq * $freq_tol) * ($cap_size + $cap_size * $cap_tol))) + ($res_size - $res_size * $res_tol));

# Output
print "\nMinimum current: ".($V_min * $R_min * 1000)." mA\nMaximum current: ".($V_max * $R_max * 1000)." mA\n";

# WINDOWS quirk
while (<>) {last;}