import spidev
import time
MG_PIN = 0
#아날로그 값을 입력받을 핀 정의
DC_GAIN = 8.5
#define the DC gain of amplifier
#증폭회로의 전압이득 정의
#***********************Software Related Macros********************************
READ_SAMPLE_TIMES = 10
#define how many samples you are going to take in normal operation
#추출할 샘플의 개수
READ_SAMPLE_INTERVAL = 50
#define the time interval(in milisecond) between each samples in normal operation
#샘플 추출 간격(ms)
#**********************Application Related Macros****************************
ZERO_POINT_X = 2.602
#These values differ from sensor to sensor. User should derermine this value.
#lg400=2.602, the start point_on X_axis of the curve
ZERO_POINT_VOLTAGE = 0.324
#define the output of the sensor in volts when the concentration of CO2 is 400PPM
#CO2가 400ppm일 때의 전압(volt)
MAX_POINT_VOLTAGE = 0.265
#define the output of the sensor in volts when the concentration of CO2 is 10,000PPM
#CO2가 10,000ppm일 때의 전압(volt)
REACTION_VOLTGAE = 0.059
#define the voltage drop of the sensor when move the sensor from air into 1000ppm CO2
#공기에서 1000ppm CO2로 이동할 때 센서의 전압 강하(?)
CO2Curve = [ZERO_POINT_X, ZERO_POINT_VOLTAGE, (REACTION_VOLTGAE / (2.602 - 4))]
#Two points are taken from the curve. With these two points,
#a line is formed which is "approximately equivalent" to the original curve.
#You could use other methods to get more accurate slope
#CO2 Curve format:{ x, y, slope};
#point1: (lg400=2.602, 0.324),
#point2: (lg10000=4, 0.265)
#slope = (y1-y2)(i.e.reaction voltage)/ x1-x2 = (0.324-0.265)/(log400 - log10000)
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000
def analog_read(channel):
r = spi.xfer2([1, (8 + channel) << 4, 0])
adc_out = ((r[1]&3) << 8) + r[2]
return adc_out
def MGGetPercentage(volts):
volts = volts / DC_GAIN # 8.5로 나눔
if volts > ZERO_POINT_VOLTAGE or volts < MAX_POINT_VOLTAGE : # 측정범위를 벗어나면
return -1
else :
return pow(10, (volts - CO2Curve[1]) / CO2Curve[2] + CO2Curve[0]) # volt -> ppm 변환
volts = 0;
while True:
reading = analog_read(0)
voltage = reading * 5 / 1024 #사용전압이 5volt이기 때문에 5
ppm = MGGetPercentage(voltage)
print("Reading = %d\tVoltage=%f\t" % (reading, voltage), end="")
if ppm == -1:
print("Under heating/beyond range(400~10,000)");
else:
print("ppm=%5.2fppm" % ppm);
time.sleep(3)