Skip to content

Instantly share code, notes, and snippets.

@codejoust
Created March 29, 2014 05:52
Show Gist options
  • Save codejoust/9849298 to your computer and use it in GitHub Desktop.
Save codejoust/9849298 to your computer and use it in GitHub Desktop.
import alsaaudio
import serial
#import numpy
import struct
import math
ser = serial.Serial('/dev/ttyUSB0', 19200)
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, 'Device')
inp.setchannels(1)
inp.setrate(1000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(120)
def update_lights(rms):
num = max(min(int(rms*1000.0), 254), 40)
print num
ser.write("1c%iw" % num)
ser.write("2c%iw" % num)
ser.write("5c%iw" % num)
ser.write("5c%iw" % abs(100-num))
ser.write("7c%iw" % num)
def get_rms( block ):
count = len(block)/2
format = "%dh"%(count)
shorts = struct.unpack( format, block )
sum_squares = 0.0
for sample in shorts:
# sample is a signed short in +/- 32768.
# normalize it to 1.0
n = sample * (1.0/32768.0)
sum_squares += n*n
print sum_squares
return math.sqrt( sum_squares / count )
while True:
l, data = inp.read()
if (l > 0):
update_lights(get_rms(data))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment