-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReadADC_CT.py
51 lines (39 loc) · 1.5 KB
/
ReadADC_CT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import time
import board
import busio
import digitalio
import adafruit_mcp3xxx.mcp3008 as MCP
from adafruit_mcp3xxx.analog_in import AnalogIn
import numpy as np
# Set up MCP3008
spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
cs = digitalio.DigitalInOut(board.D5)
mcp = MCP.MCP3008(spi, cs) # Corrected this line
# Set up the current channel
current_channel = AnalogIn(mcp, MCP.P1)
# Constants
SAMPLES = 100
VCC = 5.0
ADC_MAX = 65535
CALIBRATION_FACTOR = 0.2535 # Use the value we found
def read_current():
samples = [current_channel.value for _ in range(SAMPLES)]
avg_raw = np.mean(samples)
adc_voltage = (avg_raw / ADC_MAX) * VCC
return avg_raw, adc_voltage
# Print header
print("Raw ADC, Sensor Peak Current, Sensor RMS Current, Mains Peak Current, Mains RMS Current")
while True:
raw_adc, adc_voltage = read_current()
# Calculate currents
mains_rms_current = adc_voltage * CALIBRATION_FACTOR
mains_peak_current = mains_rms_current * np.sqrt(2)
# Calculate sensor currents (assuming linear relationship)
sensor_rms_current = adc_voltage
sensor_peak_current = sensor_rms_current * np.sqrt(2)
# Print values in comma-separated format
print(f"{raw_adc:.0f}, {sensor_peak_current:.4f}, {sensor_rms_current:.4f}, {mains_peak_current:.4f}, {mains_rms_current:.4f}")
time.sleep(1)
# Calibration steps if changed the load
# NEW_FACTOR = (AMMETER_READING / CODE_READING) * CURRENT_FACTOR
# NEW_FACTOR = (1.72 / 0.825) * 0.2535 ≈ 0.5284