I'm trying to make a clapper switch to turn on and off an LED on Raspberry Pi 3B+. I'm using MAX4466 of a kind microphone (didn't buy it by self so don't know the exact model, but it's a mic with 3 outputs - Vcc, GND, Out and looks very similar to the mentioned model) and an MCP3002 ADC.
This is the code I'm using for the RPi (found it on the net): '''
import time
import spidev
import RPi.GPIO as GPIO
import ploting
spi_ch = 0
# Enable SPI
spi = spidev.SpiDev(0, spi_ch)
spi.max_speed_hz = 1200000
def read_adc(adc_ch, vref = 3.3):
# Make sure ADC channel is 0 or 1
if adc_ch != 0:
adc_ch = 1
# Construct SPI message
# First bit (Start): Logic high (1)
# Second bit (SGL/DIFF): 1 to select single mode
# Third bit (ODD/SIGN): Select channel (0 or 1)
# Fourth bit (MSFB): 0 for LSB first
# Next 12 bits: 0 (don't care)
msg = 0b11
msg = ((msg << 1) + adc_ch) << 5
msg = [msg, 0b00000000]
reply = spi.xfer2(msg)
# Construct single integer out of the reply (2 bytes)
adc = 0
for n in reply:
adc = (adc << 8) + n
# Last bit (0) is not part of ADC value, shift to remove it
adc = adc >> 1
# Calculate voltage form ADC value
# voltage = (vref * adc) / 1024
voltage = adc
return voltage
# Report the channel 0 and channel 1 voltages to the terminal
try:
while True:
adc_0 = read_adc(0)
adc_1 = read_adc(1)
print("Ch 0:", round(adc_0, 2), "V Ch 1:", round(adc_1, 2), "V")
time.sleep(0.2)
finally:
GPIO.cleanup()
When I'm connecting a standard potentiometer to CH0/1 it reads values in a range from 0 to 1023 as it should, but when connecting the mic's output, it just reads about the same value all the time and sometimes changes with some random values (no related to any sound detection):
Ch 0: 478 V Ch 1: 1018 V
Ch 0: 485 V Ch 1: 1017 V
Ch 0: 511 V Ch 1: 1017 V
Ch 0: 484 V Ch 1: 1016 V
Ch 0: 484 V Ch 1: 1019 V
Ch 0: 486 V Ch 1: 1020 V
Ch 0: 64 V Ch 1: 1016 V
Ch 0: 1020 V Ch 1: 1016 V
Ch 0: 444 V Ch 1: 1017 V
Ch 0: 470 V Ch 1: 1016 V
Ch 0: 463 V Ch 1: 1016 V
Ch 0: 1023 V Ch 1: 1016 V
Ch 0: 463 V Ch 1: 1019 V
Ch 0: 444 V Ch 1: 1017 V
Ch 0: 432 V Ch 1: 1016 V
Ch 0: 487 V Ch 1: 1022 V
Ch 0: 268 V Ch 1: 1020 V
Ch 0: 433 V Ch 1: 1016 V
Ch 0: 455 V Ch 1: 1016 V
Ch 0: 464 V Ch 1: 1022 V
Ch 0: 1023 V Ch 1: 1019 V
Ch 0: 432 V Ch 1: 1020 V
Ch 0: 412 V Ch 1: 1017 V
also tried to connect the mic through a NE5534 amplifier, although it already has a built-in amp with it. Furthermore, I've tried connecting the mic to an Arduino Uno for testing and it works just fine.
Any ideas why the RPi couldn't manage reading the sound detection?