from machine import Pin, ADC
import time
# ESP32的ADC引脚(请根据你的硬件连接修改)
adc_pin = 14
adc = ADC(adc_pin)
adc.atten(ADC.ATTN_11DB) # 设置ADC衰减,这取决于你的输入电压范围
adc.width(ADC.WIDTH_12BIT) # 设置ADC的分辨率
# 设置ESP32的GPIO引脚连接到CD74HC4067
s_pins = [Pin(25, Pin.OUT), Pin(33, Pin.OUT), Pin(32, Pin.OUT), Pin(26, Pin.OUT)]
# 初始化通道选择引脚
channels = [
[0, 0, 0, 0], # channel 0
[1, 0, 0, 0], # channel 1
[0, 1, 0, 0], # channel 2
[1, 1, 0, 0], # channel 3
[0, 0, 1, 0], # channel 4
[1, 0, 1, 0], # channel 5
[0, 1, 1, 0], # channel 6
[1, 1, 1, 0], # channel 7
[0, 0, 0, 1], # channel 8
[1, 0, 0, 1], # channel 9
[0, 1, 0, 1], # channel 10
[1, 1, 0, 1], # channel 11
[0, 0, 1, 1], # channel 12
[1, 0, 1, 1], # channel 13
[0, 1, 1, 1], # channel 14
[1, 1, 1, 1] # channel 15
]
# 存储所有通道的数据(改为列表形式,每个元素是一个格式化的字符串)
sensor_data_list = []
# 选择特定的通道
def select_channel(channel_index):
channel_config = channels[channel_index]
for i, pin in enumerate(s_pins):
pin.value(channel_config[i])
# 读取所有通道的数据,并存储
def read_all_channels():
global sensor_data_list
readings = [] # 临时存储本次读取的数据
for i in range(16):
select_channel(i)
time.sleep(0.01) # 短暂延时以确保多路复用器稳定
reading = adc.read()
readings.append(f"C{i}: {reading}") # 添加到临时列表中
time.sleep(0.1) # 稍作延时再进行下一次读取
# 将读取的数据格式化为一个字符串,并添加到全局列表中
formatted_readings = '[' + ', '.join(readings) + ']'
sensor_data_list.append(formatted_readings)
print(formatted_readings) # 打印格式化后的数据
# 定义全局停止标志
stop_flag = False
# 主程序
def main():
global stop_flag # 声明我们要使用全局变量stop_flag
try:
while not stop_flag: # 检查停止标志
read_all_channels() # 读取所有通道的数据
time.sleep(1) # 每次循环后暂停1秒
except KeyboardInterrupt:
# 当按下Ctrl+C时,也会执行这里的代码
stop_program()
# 停止程序的函数
def stop_program():
global stop_flag
stop_flag = True # 设置停止标志为True
print('程序已停止,正在保存数据...')
# 将每次循环读取的数据保存到文件中
with open('sensor_data.txt', 'w') as f:
for data in sensor_data_list:
f.write(data + '\n') # 每个格式化后的数据占一行
print('数据已保存为sensor_data.txt')
# 如果还需要打印数据到控制台,可以调用下面的函数
print_data_from_file('sensor_data.txt')
# 如果需要从文件中读取并打印数据,可以使用以下函数(可选)
def print_data_from_file(filename):
try:
with open(filename, 'r') as f:
for line in f:
print(line.strip()) # strip() 用于移除行尾的换行符
except FileNotFoundError:
print(f"文件 {filename} 未找到!")
# 运行主程序
main()