The voltage of the electrical system (e.g., 120V, 240V).
Copper
Aluminum
Select the material of the wire.
60°C (e.g., TW)
75°C (e.g., THW, THWN)
90°C (e.g., THHN, XHHW)
The maximum operating temperature of the wire insulation.
Recommended maximum voltage drop (typically 3-5%).
Results
Required Ampacity (Amps):N/A
Voltage Drop (Volts):N/A
Voltage Drop (%):N/A
Wire Size: N/A
The primary calculation involves determining the necessary wire ampacity considering the load, then calculating the actual voltage drop based on wire length, material resistivity, and selected gauge. The NEC (National Electrical Code) tables are used to find the smallest conductor with sufficient ampacity and acceptable voltage drop.
Conductor Properties (Based on NEC Standards)
AWG Gauge vs. Ampacity and Resistance
Common Wire Gauges and Properties (Copper, 75°C)
AWG Gauge
Diameter (mm)
Area (mm²)
Ampacity (Amps)
Resistance (Ω/km)
What is Wire Sizing?
Wire sizing, often referred to as determining the correct conductor gauge, is a fundamental aspect of electrical engineering and DIY electrical work. It involves selecting the appropriate size (diameter or cross-sectional area) of electrical wire for a specific application to safely and efficiently carry electrical current. Proper wire sizing is crucial for preventing overheating, minimizing energy loss due to voltage drop, and ensuring the longevity and reliability of electrical systems. Failing to size wires correctly can lead to numerous problems, ranging from inefficient operation to severe safety hazards like electrical fires.
Anyone involved in electrical installations, from certified electricians to homeowners undertaking renovation projects, should understand the principles of wire sizing. This includes those designing new electrical systems, upgrading existing ones, or troubleshooting electrical issues. It's a critical consideration for circuits powering appliances, lighting, motors, and any other electrical load. A common misconception is that any sufficiently thick wire will do, but this overlooks the nuanced relationship between wire gauge, current capacity, distance, and acceptable voltage drop, all of which are addressed by a professional wire sizing calculator.
Wire Sizing Formula and Mathematical Explanation
The process of determining the correct wire size for a wire sizing calculator involves several steps and considerations, primarily governed by electrical codes like the National Electrical Code (NEC) in the US. The core principles revolve around ampacity (the maximum current a conductor can carry continuously under specific conditions) and voltage drop (the reduction in voltage along the length of the conductor due to its resistance).
Key Formulas:
1. Ampacity Calculation: The initial step is to determine the required ampacity of the wire. This is usually based on the load current, with adjustments for ambient temperature, conduit fill, and other factors as specified by code. For basic calculations, we start with the expected load current.
2. Voltage Drop Calculation: Voltage drop is calculated using Ohm's Law, adapted for AC circuits considering wire resistance and reactance. The simplified formula for voltage drop (VD) in volts is:
VD = (2 * K * I * L) / CM (for single-phase, two-wire circuits)
Where:
VD = Voltage Drop (in Volts)
2 = Factor for two-way current flow (in a loop)
K = Resistance constant for the conductor material (Ohm-circular mil per foot)
I = Current (in Amps)
L = Length of the wire (one-way, in feet)
CM = Circular Mils (cross-sectional area of the wire)
For three-phase circuits, the '2' factor is replaced by '√3' (approximately 1.732).
3. Percentage Voltage Drop: This is calculated as:
VD% = (VD / System Voltage) * 100
4. Selecting the Wire Gauge: The chosen wire gauge must satisfy two main criteria:
Its ampacity (from NEC tables) must be greater than or equal to the required ampacity calculated in step 1.
The resulting percentage voltage drop (calculated in step 3) must be less than or equal to the allowable voltage drop (typically 3%).
A wire sizing calculator automates these calculations, referencing NEC tables for K values, CM values, and ampacities based on the selected material, temperature rating, and gauge.
Variable Table:
Variable Name
Meaning
Unit
Typical Range/Values
Current Load (I)
Maximum current the circuit will draw.
Amps (A)
1 – 1000+ (depends on application)
Wire Length (L)
One-way distance from power source to load.
Feet (ft)
1 – 1000+ (depends on installation)
System Voltage (V)
Nominal voltage of the electrical system.
Volts (V)
12, 24, 120, 208, 240, 277, 480, 600
Conductor Material
Material of the wire conductor.
N/A
Copper, Aluminum
Insulation Temp Rating
Max operating temperature of wire insulation.
Degrees Celsius (°C)
60, 75, 90
Allowable Voltage Drop (%)
Maximum acceptable voltage loss.
Percent (%)
1 – 5 (NEC recommends ≤3% for branch circuits)
K Value (Copper)
Resistivity constant for copper.
Ohm-CM/ft
~12.9 (at 75°C)
K Value (Aluminum)
Resistivity constant for aluminum.
Ohm-CM/ft
~21.2 (at 75°C)
Circular Mils (CM)
Cross-sectional area of the wire.
CM
Varies by AWG gauge (e.g., 16510 for 6 AWG)
Ampacity
Max current a conductor can carry.
Amps (A)
Varies by gauge and temp rating (NEC tables)
Practical Examples (Real-World Use Cases)
Understanding the practical application of a wire sizing calculator is key. Here are two common scenarios:
Example 1: Residential Kitchen Appliance Circuit
Scenario: A homeowner wants to install a new circuit for a microwave oven in their kitchen. The microwave is rated at 15 Amps and will be located approximately 50 feet from the breaker panel. The system voltage is 120V. The homeowner desires to maintain a voltage drop of no more than 3% to ensure the appliance operates efficiently.
Inputs for Calculator:
Current Load: 15 A
Wire Length: 50 ft
System Voltage: 120 V
Conductor Material: Copper
Insulation Temp Rating: 90°C (for THHN/THWN)
Allowable Voltage Drop: 3%
Calculator Output:
Required Ampacity: 15 A
Calculated Voltage Drop: ~2.7 V
Calculated Voltage Drop (%): ~2.25%
Recommended Wire Size: 12 AWG
Interpretation: A 12 AWG copper wire is recommended. This gauge has an ampacity of 25A (at 75°C) or 30A (at 90°C) per NEC tables, well above the 15A load. The calculated voltage drop of approximately 2.25% is below the 3% allowable limit, ensuring efficient operation of the microwave.
Example 2: Workshop Power Feed
Scenario: An electrician needs to run power to a detached workshop 120 feet away from the main house's electrical panel. The workshop will house several tools, requiring a total continuous load of 30 Amps at 240V. To minimize power loss over the long run, a maximum voltage drop of 3% is specified.
Inputs for Calculator:
Current Load: 30 A
Wire Length: 120 ft
System Voltage: 240 V
Conductor Material: Copper
Insulation Temp Rating: 90°C (for THHN/THWN)
Allowable Voltage Drop: 3%
Calculator Output:
Required Ampacity: 30 A
Calculated Voltage Drop: ~3.46 V
Calculated Voltage Drop (%): ~1.44%
Recommended Wire Size: 10 AWG
Interpretation: A 10 AWG copper wire is sufficient. It meets the ampacity requirement (typically 35A at 75°C or 40A at 90°C) and the voltage drop calculation shows a loss of about 1.44%, which is well within the 3% limit. If the calculation had suggested a smaller gauge which failed the ampacity test, the wire sizing calculator would point towards the next larger size needed for safety.
How to Use This Wire Sizing Calculator
Using this wire sizing calculator is straightforward. Follow these steps to get accurate results:
Enter Current Load: Input the maximum continuous amperage the circuit will draw. If unsure, use the rating of the largest appliance or the circuit breaker size.
Input Wire Length: Provide the one-way distance from the power source (e.g., breaker panel) to the electrical device or outlet.
Specify System Voltage: Enter the nominal voltage of your electrical system (e.g., 120V for standard outlets, 240V for larger appliances).
Select Conductor Material: Choose whether the wire is made of Copper or Aluminum. Copper is more conductive and typically requires a smaller gauge for the same ampacity.
Choose Insulation Temperature Rating: Select the temperature rating associated with the wire's insulation type (e.g., 60°C, 75°C, 90°C). Higher ratings allow for higher ampacity in certain conditions but are often subject to the 60°C or 75°C column depending on the termination points per NEC rules.
Set Allowable Voltage Drop: Input the maximum acceptable percentage of voltage loss along the wire. 3% is a common recommendation for branch circuits to ensure efficient equipment operation.
Click "Calculate": The calculator will process your inputs and display the recommended wire gauge.
Interpreting Results:
Recommended Wire Size: This is the primary output, indicating the smallest AWG (American Wire Gauge) size that meets both ampacity and voltage drop requirements.
Required Ampacity: The minimum current-carrying capacity the wire must possess.
Calculated Voltage Drop (Volts & %): These show the actual voltage loss the selected wire would experience under the specified load and length. Ensure the percentage is below your set allowable limit.
Decision-Making Guidance: If the calculated wire size is larger than what you initially expected, it's usually due to a long wire run (causing high voltage drop) or a high current load. Always default to the larger wire size if results are borderline or if local codes have stricter requirements. Consulting with a qualified electrician is recommended for complex installations or if you are uncertain about any aspect of electrical work.
Key Factors That Affect Wire Sizing Results
Several critical factors influence the outcome of a wire sizing calculator and the ultimate choice of conductor size. Understanding these allows for more informed decisions and safer installations:
Current Load (Amperage): This is the most direct factor. Higher current demands necessitate larger wires to prevent overheating. The NEC defines ampacities for different wire sizes, and codes often require sizing based on 125% of the continuous load.
Wire Length (Distance): Longer runs increase the wire's total resistance, leading to greater voltage drop. This is often the limiting factor for circuits running significant distances, forcing the use of a larger gauge than ampacity alone would require. This is a key aspect that any good wire sizing calculator must account for.
System Voltage: While voltage itself doesn't directly determine wire size based on resistance, it dictates the percentage voltage drop. A lower system voltage (e.g., 120V) is more sensitive to voltage drop than a higher one (e.g., 240V) for the same absolute voltage loss.
Conductor Material (Copper vs. Aluminum): Aluminum has higher resistance than copper (meaning K value is higher), so for the same ampacity and length, aluminum wire needs to be a larger gauge than copper wire. Aluminum wiring also requires specific termination techniques due to its tendency to oxidize and creep.
Insulation Temperature Rating & Ambient Conditions: The type of insulation (e.g., THHN, XHHW) determines the maximum allowable operating temperature. Higher temperature ratings (like 90°C) generally permit higher ampacities, but NEC rules often limit the effective ampacity to that of the 60°C or 75°C column based on the temperature rating of connected equipment terminals. Ambient temperature also affects ampacity; wires in hot environments carry less current safely.
Conduit Fill & Number of Conductors: When multiple current-carrying conductors are bundled in a conduit or raceway, they generate more heat. The NEC mandates "derating factors" that reduce the allowable ampacity for each conductor as the number of current-carrying conductors increases. A comprehensive wire sizing calculator might incorporate these derating factors.
Circuit Type (e.g., motor loads): Motors have specific requirements due to their high starting current (inrush). NEC provides tables and rules for sizing conductors and overload protection for motor circuits, which differ from standard continuous loads.
Local Electrical Codes and Amendments: While the NEC provides a baseline, local jurisdictions may have amendments or additional requirements that override or supplement the code. Always verify local regulations.
Frequently Asked Questions (FAQ)
Q1: What is the difference between AWG and MCM?
AWG (American Wire Gauge) is used for smaller wires, while MCM (Thousand Circular Mils) is used for larger conductors, typically above 400 kcmil. MCM represents the area in thousands of circular mils.
Q2: Can I use aluminum wire instead of copper?
Yes, but aluminum wire needs to be sized larger than copper for the same ampacity due to its lower conductivity. It also requires specific connectors and installation techniques to ensure safety and prevent fire hazards. This is why a wire sizing calculator is essential.
Q3: What is the NEC, and why is it important for wire sizing?
The NEC (National Electrical Code) is a standard for safe electrical design and installation. It provides tables and rules for determining wire ampacity, voltage drop limits, and other safety factors. Following the NEC is crucial for preventing electrical hazards.
Q4: My calculator suggests 10 AWG, but the breaker is 20A. Is that okay?
Yes. The wire's ampacity must be equal to or greater than the breaker rating (or 125% of the continuous load). 10 AWG copper typically has an ampacity of 30A (at 75°C) or 35A (at 90°C), which safely exceeds a 20A breaker. The calculation ensures the wire won't overheat if the breaker functions correctly.
Q5: Does the voltage drop calculation change for three-phase power?
Yes. The formula for voltage drop in a three-phase system uses a factor of √3 (approximately 1.732) instead of 2, reflecting the nature of three-phase power distribution.
Q6: How do I account for derating if I run wires in a conduit with other circuits?
You need to consult NEC tables (like Table 310.15(C)(1)) for derating factors based on the number of current-carrying conductors in the conduit and the ambient temperature. A simple wire sizing calculator may not include this; you would manually adjust the required ampacity downwards before using the calculator or select a larger wire size.
Q7: What is the NEC's recommendation for allowable voltage drop?
The NEC recommends that the total voltage drop for feeders and branch circuits combined should not exceed 5%. For branch circuits alone, it recommends a maximum of 3% for power, 1-1.5% for lighting, and a combined total not exceeding 5%.
Q8: Can I use a smaller wire if the voltage drop is acceptable but the ampacity is borderline?
No. You must satisfy BOTH ampacity and voltage drop requirements. Always choose the wire size that meets the higher of the two demands. If a wire meets the voltage drop requirement but not the ampacity, you must select a larger gauge wire.
Related Tools and Internal Resources
Voltage Drop Calculator – Specifically calculates voltage drop for various scenarios, useful for verifying results or analyzing existing installations.
Amperage Calculator – Helps determine the current draw (amperage) for various electrical devices based on their wattage and voltage.
Electrical Safety Guide – Provides essential tips and best practices for working safely with electricity.
Circuit Breaker Calculator – Assists in selecting the appropriate circuit breaker size for different loads.
NEC Code Reference – Quick access to key tables and definitions from the National Electrical Code for wire sizing.
Power Factor Calculator – Understand how power factor affects electrical systems and sizing, especially for inductive loads.
// NEC Ampacity Tables Data (simplified for common cases)
// Based on copper conductors, 75°C column unless otherwise noted
// Source: NEC Table 310.16 (values are approximate and subject to specific conditions)
var conductorData = {
"copper": {
"60": { // Temp Rating 60C
"14": {"ampacity": 15, "cm": 4110, "resistance_ohm_km": 3.28},
"12": {"ampacity": 20, "cm": 6530, "resistance_ohm_km": 2.06},
"10": {"ampacity": 30, "cm": 10380, "resistance_ohm_km": 1.30},
"8": {"ampacity": 40, "cm": 16510, "resistance_ohm_km": 0.81},
"6": {"ampacity": 55, "cm": 26240, "resistance_ohm_km": 0.51},
"4": {"ampacity": 70, "cm": 41740, "resistance_ohm_km": 0.32},
"3": {"ampacity": 80, "cm": 52620, "resistance_ohm_km": 0.25},
"2": {"ampacity": 95, "cm": 66360, "resistance_ohm_km": 0.20},
"1": {"ampacity": 115, "cm": 83690, "resistance_ohm_km": 0.16},
"1/0": {"ampacity": 130, "cm": 105600, "resistance_ohm_km": 0.13},
"2/0": {"ampacity": 150, "cm": 133100, "resistance_ohm_km": 0.10},
"3/0": {"ampacity": 175, "cm": 167800, "resistance_ohm_km": 0.08},
"4/0": {"ampacity": 200, "cm": 211600, "resistance_ohm_km": 0.06}
},
"75": { // Temp Rating 75C
"14": {"ampacity": 15, "cm": 4110, "resistance_ohm_km": 3.28}, // Often limited by terminal rating to 60C for 14/12
"12": {"ampacity": 20, "cm": 6530, "resistance_ohm_km": 2.06}, // Often limited by terminal rating to 60C for 14/12
"10": {"ampacity": 30, "cm": 10380, "resistance_ohm_km": 1.30},
"8": {"ampacity": 40, "cm": 16510, "resistance_ohm_km": 0.81},
"6": {"ampacity": 55, "cm": 26240, "resistance_ohm_km": 0.51},
"4": {"ampacity": 70, "cm": 41740, "resistance_ohm_km": 0.32},
"3": {"ampacity": 80, "cm": 52620, "resistance_ohm_km": 0.25},
"2": {"ampacity": 95, "cm": 66360, "resistance_ohm_km": 0.20},
"1": {"ampacity": 115, "cm": 83690, "resistance_ohm_km": 0.16},
"1/0": {"ampacity": 130, "cm": 105600, "resistance_ohm_km": 0.13},
"2/0": {"ampacity": 150, "cm": 133100, "resistance_ohm_km": 0.10},
"3/0": {"ampacity": 175, "cm": 167800, "resistance_ohm_km": 0.08},
"4/0": {"ampacity": 200, "cm": 211600, "resistance_ohm_km": 0.06}
},
"90": { // Temp Rating 90C
"14": {"ampacity": 20, "cm": 4110, "resistance_ohm_km": 3.28}, // Note: Terminal limitations often apply
"12": {"ampacity": 25, "cm": 6530, "resistance_ohm_km": 2.06}, // Note: Terminal limitations often apply
"10": {"ampacity": 35, "cm": 10380, "resistance_ohm_km": 1.30},
"8": {"ampacity": 50, "cm": 16510, "resistance_ohm_km": 0.81},
"6": {"ampacity": 65, "cm": 26240, "resistance_ohm_km": 0.51},
"4": {"ampacity": 85, "cm": 41740, "resistance_ohm_km": 0.32},
"3": {"ampacity": 95, "cm": 52620, "resistance_ohm_km": 0.25},
"2": {"ampacity": 115, "cm": 66360, "resistance_ohm_km": 0.20},
"1": {"ampacity": 135, "cm": 83690, "resistance_ohm_km": 0.16},
"1/0": {"ampacity": 155, "cm": 105600, "resistance_ohm_km": 0.13},
"2/0": {"ampacity": 180, "cm": 133100, "resistance_ohm_km": 0.10},
"3/0": {"ampacity": 210, "cm": 167800, "resistance_ohm_km": 0.08},
"4/0": {"ampacity": 240, "cm": 211600, "resistance_ohm_km": 0.06}
}
},
"aluminum": {
"60": {
"8": {"ampacity": 30, "cm": 16510, "resistance_ohm_km": 1.3},
"6": {"ampacity": 40, "cm": 26240, "resistance_ohm_km": 0.82},
"4": {"ampacity": 55, "cm": 41740, "resistance_ohm_km": 0.52},
"3": {"ampacity": 60, "cm": 52620, "resistance_ohm_km": 0.41},
"2": {"ampacity": 75, "cm": 66360, "resistance_ohm_km": 0.33},
"1": {"ampacity": 90, "cm": 83690, "resistance_ohm_km": 0.26},
"1/0": {"ampacity": 105, "cm": 105600, "resistance_ohm_km": 0.21},
"2/0": {"ampacity": 125, "cm": 133100, "resistance_ohm_km": 0.16},
"3/0": {"ampacity": 145, "cm": 167800, "resistance_ohm_km": 0.13},
"4/0": {"ampacity": 170, "cm": 211600, "resistance_ohm_km": 0.10}
},
"75": {
"8": {"ampacity": 35, "cm": 16510, "resistance_ohm_km": 1.3},
"6": {"ampacity": 50, "cm": 26240, "resistance_ohm_km": 0.82},
"4": {"ampacity": 65, "cm": 41740, "resistance_ohm_km": 0.52},
"3": {"ampacity": 75, "cm": 52620, "resistance_ohm_km": 0.41},
"2": {"ampacity": 85, "cm": 66360, "resistance_ohm_km": 0.33},
"1": {"ampacity": 100, "cm": 83690, "resistance_ohm_km": 0.26},
"1/0": {"ampacity": 120, "cm": 105600, "resistance_ohm_km": 0.21},
"2/0": {"ampacity": 140, "cm": 133100, "resistance_ohm_km": 0.16},
"3/0": {"ampacity": 165, "cm": 167800, "resistance_ohm_km": 0.13},
"4/0": {"ampacity": 190, "cm": 211600, "resistance_ohm_km": 0.10}
},
"90": {
"8": {"ampacity": 40, "cm": 16510, "resistance_ohm_km": 1.3},
"6": {"ampacity": 55, "cm": 26240, "resistance_ohm_km": 0.82},
"4": {"ampacity": 75, "cm": 41740, "resistance_ohm_km": 0.52},
"3": {"ampacity": 85, "cm": 52620, "resistance_ohm_km": 0.41},
"2": {"ampacity": 100, "cm": 66360, "resistance_ohm_km": 0.33},
"1": {"ampacity": 115, "cm": 83690, "resistance_ohm_km": 0.26},
"1/0": {"ampacity": 135, "cm": 105600, "resistance_ohm_km": 0.21},
"2/0": {"ampacity": 155, "cm": 133100, "resistance_ohm_km": 0.16},
"3/0": {"ampacity": 180, "cm": 167800, "resistance_ohm_km": 0.13},
"4/0": {"ampacity": 210, "cm": 211600, "resistance_ohm_km": 0.10}
}
}
};
var availableGauges = ["14", "12", "10", "8", "6", "4", "3", "2", "1", "1/0", "2/0", "3/0", "4/0"];
var K_VALUES = {
"copper": 12.9, // Ohm-CM/ft at 75°C for copper
"aluminum": 21.2 // Ohm-CM/ft at 75°C for aluminum
};
var chartInstance = null;
var chartDataPoints = {};
function isValidNumber(value, min = -Infinity, max = Infinity) {
return !isNaN(parseFloat(value)) && isFinite(value) && value >= min && value Ohm/m -> Ohm/ft
// Calculate Voltage Drop for this gauge
// VD = (2 * K * I * L) / CM — For single phase
// K is in Ohm-CM/ft. Resistance is in Ohm/ft.
// Formula needs consistent units. Let's use Ohm/ft and CM directly.
// VD = 2 * (Resistance per foot * CM) * I * L / CM — Incorrect dimensional analysis
// Correct derivation:
// Total Resistance (R_total) = Resistance per foot * L
// VD = I * R_total = I * (Resistance per foot * L)
// Let's use the K value directly as it incorporates CM:
// VD = (2 * K * I * L) / CM is correct IF K is in Ohm-CM/ft.
// Let's find K based on R_ohm_ft and CM: K = R_ohm_ft * CM
var K_calculated = resistance_ohm_ft * cm; // Effective K for this gauge and material
var voltageDropVolts = (2 * K_calculated * requiredAmpacity * wireLength) / cm;
// Ensure voltage drop is not negative or NaN (due to potential data issues)
if (isNaN(voltageDropVolts) || voltageDropVolts < 0) voltageDropVolts = 0;
var voltageDropPercent = (voltageDropVolts / voltage) * 100;
if (isNaN(voltageDropPercent) || voltageDropPercent = requiredAmpacity;
// Check if gauge meets voltage drop requirement
var meetsVoltageDrop = voltageDropPercent <= allowableVoltageDropPercent;
return {
gauge: gauge,
ampacity: ampacity,
cm: cm,
resistance_ohm_km: resistance_ohm_km, // Store for chart/table
voltageDropVolts: voltageDropVolts,
voltageDropPercent: voltageDropPercent,
meetsAmpacity: meetsAmpacity,
meetsVoltageDrop: meetsVoltageDrop
};
}).filter(function(item) { return item !== null; }); // Remove null entries
// Filter to find the smallest gauge that meets BOTH criteria
var bestGauge = null;
for (var i = 0; i = 0; i–) {
var gaugeStr = availableGauges[i];
var wireInfo = availableWireData.find(function(w) { return w.gauge === gaugeStr; });
if (wireInfo && wireInfo.meetsAmpacity) {
highestAmpacityGauge = wireInfo;
break;
}
}
// Find smallest gauge overall
if (availableWireData.length > 0) {
smallestGauge = availableWireData[availableWireData.length -1]; // Assumes availableGauges is sorted smallest to largest AWG
}
if (highestAmpacityGauge) {
document.getElementById("primaryResult").textContent = "Wire Size: Larger than " + highestAmpacityGauge.gauge + " AWG Needed";
document.getElementById("calculatedVoltageDrop").textContent = highestAmpacityGauge.voltageDropVolts.toFixed(2) + " V";
document.getElementById("calculatedVoltageDropPercent").textContent = highestAmpacityGauge.voltageDropPercent.toFixed(2) + " %";
document.getElementById("primaryResult").style.backgroundColor = "#dc3545"; // Red for error/warning
} else if (smallestGauge) {
document.getElementById("primaryResult").textContent = "Wire Size: Smallest Gauge (" + smallestGauge.gauge + " AWG) Insufficient";
document.getElementById("calculatedVoltageDrop").textContent = smallestGauge.voltageDropVolts.toFixed(2) + " V";
document.getElementById("calculatedVoltageDropPercent").textContent = smallestGauge.voltageDropPercent.toFixed(2) + " %";
document.getElementById("primaryResult").style.backgroundColor = "#dc3545"; // Red for error/warning
}
else {
document.getElementById("primaryResult").textContent = "Wire Size: Calculation Error";
}
}
// Reset primary result color if a valid size was found
if (bestGauge) {
document.getElementById("primaryResult").style.backgroundColor = "var(–primary-color)";
}
updateChartAndTable();
}
function updateChartAndTable() {
var material = document.getElementById("material").value;
var tempRating = document.getElementById("tempRating").value;
var dataForMaterial = conductorData[material];
if (!dataForMaterial) return;
var dataForTemp = dataForMaterial[tempRating] || dataForMaterial["75″]; // Fallback to 75C
chartDataPoints = {};
var tableHtml = ";
// Populate table and collect data for chart
availableGauges.forEach(function(gauge) {
var gaugeData = dataForTemp[gauge];
if (!gaugeData) return;
var ampacity = gaugeData.ampacity;
var resistance_ohm_km = gaugeData.resistance_ohm_km;
// Add data for chart
chartDataPoints[gauge] = { ampacity: ampacity, resistance: resistance_ohm_km };
// Add row to table
tableHtml += '
';
tableHtml += '
' + gauge + ' AWG
';
// Placeholder for diameter and area – these require a separate lookup or calculation
tableHtml += '
N/A
'; // Diameter
tableHtml += '
N/A
'; // Area
tableHtml += '
' + ampacity + ' A
';
tableHtml += '
' + resistance_ohm_km.toFixed(3) + ' Ω/km
';
tableHtml += '
';
});
document.getElementById("wireTableBody").innerHTML = tableHtml;
renderChart();
}
function renderChart() {
var ctx = document.getElementById('wireSizingChart').getContext('2d');
// Destroy previous chart instance if it exists
if (chartInstance) {
chartInstance.destroy();
}
var labels = Object.keys(chartDataPoints).sort(function(a, b) {
// Custom sort for AWG (handle 1/0, 2/0 etc.)
var order = availableGauges;
return order.indexOf(a) – order.indexOf(b);
});
var ampacities = labels.map(function(label) { return chartDataPoints[label].ampacity; });
var resistances = labels.map(function(label) { return chartDataPoints[label].resistance; });
// Scale resistance data for better visualization alongside ampacity
// Find max ampacity and max resistance to determine relative scaling
var maxAmpacity = Math.max(…ampacities);
var maxResistance = Math.max(…resistances);
var resistanceScaleFactor = maxAmpacity / maxResistance * 0.5; // Aim for resistance bars to be roughly half the height of ampacity bars if scales were equal
var scaledResistances = resistances.map(function(r) {
// return r * resistanceScaleFactor; // Simple scaling, might not be ideal visually
// Alternative: Use a secondary y-axis if the charting library supported it easily with canvas
// For simplicity with native canvas, we'll just plot the raw values and accept the scale difference, or maybe normalize.
// Let's try normalizing resistance to a 0-100 range relative to max resistance
return (r / maxResistance) * 100; // Normalize to 0-100
});
var resistanceMaxNormalized = 100; // Since we normalized to 100
chartInstance = new Chart(ctx, {
type: 'bar', // Changed to bar for better comparison
data: {
labels: labels,
datasets: [{
label: 'Ampacity (Amps)',
data: ampacities,
backgroundColor: 'rgba(0, 74, 153, 0.6)', // Primary color
borderColor: 'rgba(0, 74, 153, 1)',
borderWidth: 1,
yAxisID: 'y-ampacity' // Assign to primary y-axis
}, {
label: 'Resistance (Ω/km)',
data: scaledResistances, // Use scaled/normalized data
backgroundColor: 'rgba(255, 165, 0, 0.6)', // Orange for resistance
borderColor: 'rgba(255, 165, 0, 1)',
borderWidth: 1,
yAxisID: 'y-resistance' // Assign to secondary y-axis
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
title: { display: true, text: 'AWG Gauge' }
},
y-ampacity: { // Primary Y-axis for Ampacity
type: 'linear',
position: 'left',
title: { display: true, text: 'Ampacity (Amps)' },
beginAtZero: true,
ticks: {
// callback: function(value) { if (value % 5 === 0) return value; } // Optional: format ticks
}
},
y-resistance: { // Secondary Y-axis for Resistance
type: 'linear',
position: 'right',
title: { display: true, text: 'Normalized Resistance (%)' },
beginAtZero: true,
ticks: {
// callback: function(value) { return value + '%'; } // Display as percentage
},
grid: {
drawOnChartArea: false, // Only draw grid lines for the primary axis
},
min: 0,
max: 100 // Since we normalized resistance to 0-100
}
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
var label = context.dataset.label || ";
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
// Adjust display based on which dataset is hovered
if (context.dataset.label === 'Resistance (Ω/km)') {
// Find original resistance value for tooltip
var originalResistance = resistances[context.dataIndex];
label += originalResistance.toFixed(3) + ' Ω/km';
} else {
label += context.parsed.y + (context.dataset.label.includes('Ampacity') ? ' Amps' : ");
}
}
return label;
}
}
}
}
}
});
}
// Helper function to handle AWG sorting in the chart
function sortAwg(a, b) {
var order = ["14", "12", "10", "8", "6", "4", "3", "2", "1", "1/0", "2/0", "3/0", "4/0"];
return order.indexOf(a) – order.indexOf(b);
}
function resetCalculator() {
document.getElementById("currentAmps").value = "";
document.getElementById("wireLength").value = "";
document.getElementById("voltage").value = "120";
document.getElementById("material").value = "copper";
document.getElementById("tempRating").value = "75";
document.getElementById("allowableVoltageDrop").value = "3";
document.getElementById("requiredAmpacity").textContent = "N/A";
document.getElementById("calculatedVoltageDrop").textContent = "N/A";
document.getElementById("calculatedVoltageDropPercent").textContent = "N/A";
document.getElementById("primaryResult").textContent = "Wire Size: N/A";
document.getElementById("primaryResult").style.backgroundColor = "var(–primary-color)"; // Reset color
// Clear errors
var errorElements = document.querySelectorAll(".error-message");
errorElements.forEach(function(el) {
el.style.display = 'none';
el.textContent = ";
});
var inputElements = document.querySelectorAll(".loan-calc-container input, .loan-calc-container select");
inputElements.forEach(function(el) {
el.classList.remove('validation-error');
});
updateChartAndTable(); // Reset table/chart too
}
function copyResults() {
var currentAmps = document.getElementById("currentAmps").value;
var wireLength = document.getElementById("wireLength").value;
var voltage = document.getElementById("voltage").value;
var material = document.getElementById("material").value;
var tempRating = document.getElementById("tempRating").value;
var allowableVoltageDropPercent = document.getElementById("allowableVoltageDrop").value;
var requiredAmpacity = document.getElementById("requiredAmpacity").textContent;
var calculatedVoltageDrop = document.getElementById("calculatedVoltageDrop").textContent;
var calculatedVoltageDropPercent = document.getElementById("calculatedVoltageDropPercent").textContent;
var primaryResult = document.getElementById("primaryResult").textContent;
var summary = "— Wire Sizing Calculation Summary —\n";
summary += "Current Load: " + (currentAmps || "N/A") + " A\n";
summary += "Wire Length: " + (wireLength || "N/A") + " ft\n";
summary += "System Voltage: " + (voltage || "N/A") + " V\n";
summary += "Material: " + material.charAt(0).toUpperCase() + material.slice(1) + "\n";
summary += "Temp Rating: " + tempRating + "°C\n";
summary += "Allowable Voltage Drop: " + (allowableVoltageDropPercent || "N/A") + " %\n\n";
summary += "— Results —\n";
summary += "Required Ampacity: " + requiredAmpacity + "\n";
summary += "Calculated Voltage Drop: " + calculatedVoltageDrop + "\n";
summary += "Calculated Voltage Drop (%): " + calculatedVoltageDropPercent + "\n";
summary += primaryResult + "\n";
// Use a temporary textarea to copy text
var textArea = document.createElement("textarea");
textArea.value = summary;
textArea.style.position = "fixed";
textArea.style.left = "-9999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'Results copied to clipboard!' : 'Failed to copy results.';
// Optional: Show a temporary message to the user
alert(msg);
} catch (err) {
alert('Failed to copy results. Please copy manually.');
}
document.body.removeChild(textArea);
}
// Initialize calculation and chart on load
document.addEventListener('DOMContentLoaded', function() {
// Set default values and trigger initial calculation/chart rendering
document.getElementById("voltage").value = "120";
document.getElementById("allowableVoltageDrop").value = "3";
updateChartAndTable(); // Renders table and chart initially
// calculateWireSize(); // Optionally run calculation on load if inputs have defaults
});