max9814_mic_async_driver

A MicroPython library to control MAX9814 microphone

1.0.0 yangcong-bit Updated At: 2026-11-11
Install Package
Local Install
mpremote mip install https://upypi.net/pkgs/max9814_mic_async_driver/1.0.0
Remote Install
mip.install("https://upypi.net/pkgs/max9814_mic_async_driver/1.0.0")
Version Selection
README

A MicroPython library to control MAX9814 microphone — MicroPython 异步驱动

实验性异步版本:尚未完成实物验收。

同步来源:同步版本。维护者说明同步版本已验证;本次未逐包复测同步来源,适用硬件和固件范围以原有记录为准。

异步版本:本包 Python 源码及示例已通过 MicroPython 1.23 / 1.29 编译检查;软件回归只覆盖选定路径,不代表本包全部 API、实际器件及并发行为已验证。

仓库验证说明 · 两轮软件检查 · 受限清单 · 安装与初始化迁移

目录

简介

max9814_mic_async_driver 是当前仓库中独立发布的 MicroPython 异步包。设备/功能名称和 API 均来自包内运行时文件;它不是对同步 API 的无依据重命名。源包:sensors/max9814_mic_driver。

主要功能

  • 可解析的公开类:MAX9814Mic, MAX9814MicAsync, SyncAdapterMixin。
  • 可解析的公开调用入口:51 个(详见 API 矩阵)。
  • 异步等级:cooperative_nonblocking;依据:等待阶段使用协程让出;底层总线调用仍同步。

硬件要求

项目 从代码取得的事实
通信/IO Pin(, ADC(
示例 GPIO 6
供电、地址与电平 仅按模块实物标签、数据手册及代码常量配置;。

软件环境

项目 值
运行时 MicroPython + uasyncio
包版本 1.0.0
作者 leeqingshui
依赖 无声明的第三方依赖

文件结构

├── code/__pycache__/main.cpython-313.pyc
├── code/__pycache__/max9814_mic.cpython-313.pyc
├── code/main.py
├── code/max9814_mic.py
├── code/max9814_mic_async.py
├── examples/main_sync.py
├── LICENSE
└── package.json

文件说明

  • code/:实际发布的运行时 Python 模块;以 package.json.urls 为安装映射依据。
  • code/main.py(若存在):异步演示入口,不是默认发布运行时映射。
  • examples/(若存在):同步保真基线或额外示例,不应当作安装后的运行时模块。
  • package.json、LICENSE:发布元数据和许可证的唯一事实来源。

快速开始

  1. 按 package.json.urls 将运行时文件复制到设备;不要把 examples/ 当作运行时依赖。
  2. 按上文硬件/运行环境配置总线、GPIO、网络或凭证。
  3. 使用包内真实 code/main.py 的 import 与构造方式运行。以下是当前文件逐字读取的异步入口;部署时请保留 try/finally 并调用对象实际提供的 deinit() 或 aclose()。
try:
    import uasyncio as asyncio
except ImportError:
    import asyncio

async def main():
    # Python env   : MicroPython v1.23.0
    # -*- coding: utf-8 -*-
    # @Time    : 2025/8/28
    # @Author  : 缪贵成
    # @File    : main.py
    # @Description : MAX9814麦克风驱动简化测试

    # ======================================== 导入相关模块 =========================================

    from machine import Pin, ADC
    from max9814_mic import MAX9814Mic

    # ======================================== 全局变量 ============================================

    # ======================================== 功能函数 ============================================


    def get_formatted_time() -> str:
        """
        获取格式化时间字符串 (HH:MM:SS)。

        Returns:
            str: 格式化后的时间字符串。

        Notes:
            使用 time.localtime() 获取本地时间。
            适用于日志打印。

        ==========================================

        Get formatted time string (HH:MM:SS).

        Returns:
            str: Formatted time string.

        Notes:
            Uses time.localtime().
            Useful for log printing.
        """
        # 获取当前本地时间元组
        t = time.localtime()
        # 格式化输出时分秒
        return "{:02d}:{:02d}:{:02d}".format(t[3], t[4], t[5])


    def test_basic_reading() -> None:
        """
        基本读取测试:连续打印原始值、归一化值和电压。

        Raises:
            KeyboardInterrupt: 用户中断时退出。

        Notes:
            默认使用 GP26 (ADC0)。
            循环运行约 10 秒。
        ==========================================

        Basic reading test: print raw, normalized, and voltage.

        Raises:
            KeyboardInterrupt: On user interrupt.

        Notes:
            Uses GP26 (ADC0).
            Runs ~10 seconds.
        """
        # 初始化配置
        await asyncio.sleep(3)
        print("FreakStudio:max9814_mic_driver test start")
        print("=== Basic Reading Test ===")
        # GP26 = ADC0 输入
        adc = ADC(26)

        # 初始化麦克风实例
        mic = MAX9814Mic(adc=adc)

        print("Microphone initialized on ADC0 (GP26)")
        # 打印模块状态
        print("State:", mic.get_state())
        print("Reading values for ~10 seconds...")

        try:
            # 每 0.1 秒一次,总共 10 秒
            for i in range(100):
                # 原始 ADC 值
                raw_value = mic.read()
                # 归一化值 (0–1)
                normalized = mic.read_normalized()
                # 电压值 (V)
                voltage = mic.read_voltage()
                print("[{}] Raw:{:5d} | Norm:{:.3f} | Volt:{:.3f}V".format(get_formatted_time(), raw_value, normalized, voltage))
                # 延时 0.5 秒
                await asyncio.sleep(0.5)
        except KeyboardInterrupt:
            print("\n[{}] Basic test interrupted".format(get_formatted_time()))


    def test_with_gain_control() -> None:
        """
        增益控制测试:切换低增益和高增益模式并采样。

        Raises:
            KeyboardInterrupt: 用户中断时退出。

        Notes:
            GP15 用于控制增益。
            低增益模式先运行,再切换到高增益模式。

        ==========================================

        Gain control test: switch low/high gain modes.

        Raises:
            KeyboardInterrupt: On user interrupt.

        Notes:
            GP15 controls gain pin.
            Runs low gain first, then high gain.
        """
        # 初始化配置
        await asyncio.sleep(3)
        print("FreakStudio:max9814_mic_driver test start")
        print("=== Basic Reading Test ===")
        # GP26 = ADC0 输入
        adc = ADC(26)

        # 初始化GP6 作为增益控制引脚
        gain_pin = Pin(6, Pin.OUT)
        mic = MAX9814Mic(adc=adc, gain_pin=gain_pin)
        try:
            # 低增益模式
            print("=== LOW GAIN mode ===")
            mic.set_gain(False)  # 设置为低增益
            print("State:", mic.get_state())
            for i in range(50):
                print("[LOW] {:5d}".format(mic.read()), end=" ")
                if (i + 1) % 5 == 0:  # 每 5 个值换行
                    print()
                await asyncio.sleep(0.6)

            # 高增益模式
            print("\n=== HIGH GAIN mode ===")
            mic.set_gain(True)  # 设置为高增益
            print("State:", mic.get_state())
            for i in range(50):
                print("[HIGH]{:5d}".format(mic.read()), end=" ")
                if (i + 1) % 5 == 0:
                    print()
                await asyncio.sleep(0.6)

        except KeyboardInterrupt:
            print("\n[{}] Gain test interrupted".format(get_formatted_time()))


    def test_sound_detection() -> None:
        """
        声音检测测试:基于阈值判断环境是否有声音。
        Raises:
            KeyboardInterrupt: 用户中断时退出。
        Notes:
            自动校准环境噪声基线。
            阈值 = 基线 + 5000。
            检测结果实时打印。

        ==========================================

        Sound detection test: detect sound above threshold.

        Raises:
            KeyboardInterrupt: On user interrupt.

        Notes:
            Calibrates baseline automatically.
            Threshold = baseline + 5000.
            Prints detection results.
        """
        # 初始化配置
        await asyncio.sleep(3)
        print("FreakStudio:max9814_mic_driver test start")
        print("=== Basic Reading Test ===")
        # GP26 = ADC0 输入
        adc = ADC(26)

        # 初始化麦克风实例
        mic = MAX9814Mic(adc=adc)
        print("Calibrating baseline noise level...")
        # 获取环境噪声平均值
        baseline = mic.calibrate_baseline(samples=200)
        # 设置阈值
        threshold = baseline + 5000
        print("Baseline:", baseline)
        print("Threshold:", threshold)
        print("Make some noise near the mic! (Ctrl+C to stop)")

        try:
            # 计数器,记录静音周期
            silent_count = 0
            while True:
                # 当前读数
                current_value = mic.read()
                # 检测是否超阈值
                is_sound = mic.detect_sound_level(threshold=threshold, samples=10)
                if is_sound:
                    # 获取峰值
                    peak = mic.get_peak_reading(samples=20)
                    print("[{}] SOUND! Current:{} Peak:{}".format(get_formatted_time(), current_value, peak))
                    silent_count = 0
                else:
                    silent_count += 1
                    # 每检测 50 次安静,打印一次状态
                    if silent_count % 50 == 0:
                        print("[{}] Silent... Current:{} (Th:{})".format(get_formatted_time(), current_value, threshold))
                await asyncio.sleep(0.6)
        except KeyboardInterrupt:
            print("\n[{}] Detection stopped".format(get_formatted_time()))


    # ======================================== 自定义类 =============================================

    # ======================================== 初始化配置 ===========================================

    # ========================================  主程序  ============================================

    print("MAX9814 Microphone Simplified Test Suite")
    print("Choose test mode by editing code:")
    print("1. Basic reading test")
    print("2. Gain control test")
    print("3. Sound detection test")
    await asyncio.sleep(5)

    try:
        # 修改下面的函数调用来选择测试模式
        # test_basic_reading()
        # test_with_gain_control()
        test_sound_detection()
    except Exception as e:
        print("Error:", e)

if __name__ == '__main__':
    asyncio.run(main())

异步设计与使用

源状态:sync_source。本包归属当前异步仓库;原始实现的作者和许可证以源包元数据及 LICENSE 为准。协程入口应以 asyncio.run(main()) 启动。若类提供 start()/stop()、deinit() 或 aclose(),必须按其实际签名管理后台任务和资源,且在 finally 中清理。

API Async Matrix

API Level Async strategy Residual blocking Timeout/cancellation
MAX9814Mic.calibrate_baseline cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.detect_sound_level cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.disable cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.enable cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.get_average_reading cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.get_peak_reading cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.get_state cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.read cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.read_normalized cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.read_voltage cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814Mic.set_gain cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.calibrate_baseline_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.detect_sound_level_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.disable_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.enable_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.get_average_reading_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.get_peak_reading_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.get_state_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.read_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.read_normalized_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.read_voltage_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
MAX9814MicAsync.set_gain_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
SyncAdapterMixin.aclose cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
aclose cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
calibrate_baseline cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
calibrate_baseline_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
detect_sound_level cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
detect_sound_level_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
disable cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
disable_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
enable cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
enable_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_average_reading cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_average_reading_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_formatted_time cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_peak_reading cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_peak_reading_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_state cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
get_state_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
main cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read_normalized cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read_normalized_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read_voltage cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
read_voltage_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
set_gain cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
set_gain_async cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
test_basic_reading cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
test_sound_detection cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。
test_with_gain_control cooperative_nonblocking 等待阶段使用协程让出;底层总线调用仍同步 底层总线/同步临界区可能阻塞事件循环 请使用实现中已有 timeout 参数;取消后执行清理。

Source Demo to Async Demo Mapping

Source sync step Source API/protocol action Async implementation Preserved output/error meaning Residual blocking
源包示例 code/main.py code/main.py 或本文快速开始 保留实际构造与调用;异常语义以运行时代码为准 存在

超时、取消、并发与残余阻塞

任何 await 不会自动使底层 I2C/SPI/UART/Pin 操作变为非阻塞。取消时应停止后台任务并在 finally 释放资源;没有实现超时参数的 API 不应被假定具有超时。协议命令、帧界限、ACK、静默间隔及错误含义只以当前实现和源示例可证明的内容为准。

Hardware Acceptance

Level Evidence Not covered
Link 未实测:仅完成静态代码与文档取证。 总线/网络连接、设备身份响应。
Basic function 未实测。 一次真实业务 API 成功及结果正确性。
Complete business flow 未实测。 端到端设备、对端、供电、时序和异常恢复。

注意事项

类别 说明
并发 同一硬件实例应由调用方串行化;UART 额外遵守其并发契约。
阻塞 不把短同步总线访问或严格时序脉冲描述为真正可中断。
验收 文档生成不等于硬件验证;接入真实设备后分别记录三层验收证据。

版本记录

版本号 日期 作者 修改说明
1.0.0 2026-09-17 leeqingshui 基于当前异步代码、来源包和许可证重新取证 README。

联系方式

请通过本仓库的 issue 或维护者渠道联系;包内元数据作者为:leeqingshui。

许可协议

许可证声明:MIT。以下为本包 LICENSE 的逐字内容:

MIT License

Copyright (c) 2026 FreakStudio

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File List
Name Size Type
LICENSE 1.0KB File
README.md 26.8KB Doc
code/main.py 2.3KB Main
code/max9814_mic.py 13.2KB Python
code/max9814_mic_async.py 2.4KB Python
examples/main_sync.py 7.0KB Python
package.json 755B Conf