Print this Post

Sound Card Microcontroller/PC Communication



UPDATE: Check out what happened when I revisited this project and made it wireless two years later!:



This page describes a method of sending data from a microchip to a PC using pulses of data. It’s an alternative to more traditional serial or USB methods of connectivity. It’s not intended as a solution for consumer products, but rather an easy hack for hobbyists to employ if they don’t have the equipment for other methods. This method doesn’t require *any* circuitry, just a sound card. The one built in your computer is fine, but I’m using a $1.30 USB sound card for simplicity. It boils down to just a single microcontroller pin connected to a PC sound card microphone jack!

UPDATE: This story was featured on this post of HackADay.com!

This is the finished product ready to send data to a PC:DSCN1532

MY PROBLEM: I want to send data from a simple microcontroller to a PC. While USART and a serial port is the common solution like I’ve done before, it’s not convenient because it requires a level converter (like a MAX232, about $4), crystal (specific values based on bit and error rate, if you’re lucky you might have a right value in your junk box), and an archaic PC which actually has a serial port. A usb serial port adapter sounds clever, but many aren’t supported on Linux, Windows Vista, or Windows 7. Also, many small chips (most of the ATTiny series) don’t have built in serial capabilities, so it has to be bit-banged in software! Yuk! The second choice would be USB. This requires a crystal too, zener diodes, and bit-banging the USB protocol with something like V-USB since most of the AVR series don’t have built in USB (do they even make breadbordable DIP chips with USB?). Even so, it requires drivers, custom software, cross-platform frustrations, etc. I know PIC has some 18f series chips with USB, but I don’t feel like switching architectures just to send a few bytes of data to a PC. FDTI has a FT232R chip which is a USB serial port adapter, but it’s expensive (about $5) and doesn’t come in dip, so no breadboarding! Sure there are adapter boards, but that just adds the cost. I’m not excited about a $5 solution for a $1 microcontroller. I even did a bit of trolling on AVR Freaks to see if anyone could help me out – just more of the same!

MY SOLUTION: Send data through the sound card! USB sound cards are $1.30 (shipped) on eBay! It couldn’t be simpler. Send pulses, measure distance between pulses. Short pulses are a zero, longer ones are a 1, and very long pulses are number separators. A Python solution with PyAudio allows 1 script which will work on Mac, Linux, Windows, etc, and because it calibrates itself, this will work on any chip at any clock rate. Data is initiated with calibration pulses so timing is not critical – the PC figures out how fast the data is coming in. Check it out! (scroll way down for a bidirectional communication solution)

Here is a sound card I used for bidirectional communication:
DSCN1466 DSCN1470

Output graph (python and excel) of temperature when I put a soldering iron near the sensor: pythonexcel


The following code is designed to have a chip send data to your PC automatically. This can be run on any micro-controller (PIC or AVR I guess, the concept is the same) at any clock rate. Just make sure the sound card is recording fast enough to differentiate pulses. (keep scrolling down for a bidirectional solution)

A NOTE ABOUT MY CODE: This is just the code I used for my demonstration. It might be more logical for you to write your own since the concept is so simple. I’m a dental student, not a programmer, so I’m sure it’s not coded very elegantly. I didn’t work hard to make this code easy to read or easy to share. With that being said, help yourself!

/*The following code is written in AVR-GCC for an ATTiny44a. 
It reads ADC values on 3 pins and reports it each second along
 with a number which increments each time data is sent.  
It's designed as a starting point, allowing anyone to 
customize it from here!*/

#include <avr/io.h>
#include <avr/delay.h>
#include <avr/interrupt.h>

// bytes we want to send to the PC
volatile int data1=0;
volatile int data2=0;
volatile int data3=0;
volatile int data4=0;

void solid(){  // dont touch
	pulse(3);pulse(5);pulse(5);// CALIBRATION PULSES
void pulse(char size){ // dont touch
	while (size){size--;_delay_us(100);}
void sendVal(unsigned long tosend){ // dont touch
	pulse(5); // send a space
	while (tosend){
		if (tosend&1){pulse(3);} // send ONE
		else {pulse(1);} // send ZERO

int readADC(char adcNum){
	ADMUX=adcNum; // select which ADC to read, VCC as ref.
	ADCSRA=0b11000111; // enable, start, 128 prescale
    while (ADCSRA&( 1<<ADSC)) {}; // wait for measurement
	return ADC;

void takeReadings(){
        data1=readADC(0); // ADC0
        data2=readADC(1); // ADC1
        data3=readADC(2); // ADC2
		data4++; // incriment just because we want to

void sendStuff(){ // EDIT to send what you want
	solid(); //required
	sendVal(12345); //required
	sendVal(12345); //required
	sendVal(54321); //required


	pulse(1); //required

int main(){
	for (;;){
	return 0;
file name: listenOnly.py

This is the PC code to listen to the microphone and display 
and log the data. It probably does NOT need adjustment! 
 Make sure the correct sound card is selected (in the code)
 and make sure microphone input is turned up in volume control.

This code is what was used on my PC for the demonstration 
video. This is the listenOnly.py file which will turn any audio
 detected from a sound card into data, optionally logging it 
(if the last few lines are uncommented). This also works to 
capture data for the bidirectional communication method,
described below on this website.

If this is running but no data is coming through, make sure the
microphone is selected as a recording device, the correct sound
card is selected, and the microphone volume is turned to high.

REQUIRED: To run this, you need to have the following installed:
-- Python 2.6
-- numpy for python 2.6
-- matplotlib for python 2.6
-- pyaudio for python 2.6
(other versions may work, but this is what I'm using)
import numpy
import pyaudio
import matplotlib.pyplot as plt
import wave
import time

def listCards(dontAsk=True):
    print "SOUND CARDS:"
    for i in range(p.get_default_host_api_info()["deviceCount"]):
        if p.get_device_info_by_index(i)["maxInputChannels"]>0:
                cardName = p.get_device_info_by_index(i)["name"]
                cardIndex = p.get_device_info_by_index(i)["index"]
                print "[%d] %s"%(cardIndex,cardName)
    if dontAsk: return
    return int(raw_input("CARD NUMBER TO USE:"))

print "USING CARD:",cardID


def data2vals(data):
    for i in range(1,len(data)):
        if data[i]==True and data[i-1]==False:
            if lastPeak>0: vals=numpy.append(vals,i-lastPeak)
    return vals

def binary2dec(binary):
    for i in range(len(binary)):
    #print s,"=",dec #11111100101100000 = 3391
    return dec

def readVals(vals):
    if len(vals)<7: return False
    aLow = min(vals[0:3])
    aMed = min(vals[3:6])
    aHigh = vals[6]
    #print "tresholds:",thresh1,thresh2
    #print vals
    for i in range(len(vals)):
        if vals[i]>thresh2:
        if vals[i]>thresh1:binary=[1]+binary
    for i in range(len(vals2)):
        if vals2[i]==54321: return vals2[i+1:]
    return False

def playFile():
    chunk = 1024
    wf = wave.open("short_onenum.wav", 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format =
                    channels = wf.getnchannels(),
                    rate = wf.getframerate(),
                    output = True)
    data = wf.readframes(chunk)
    while data != '':
        data = wf.readframes(chunk)

def captureData():
    pyaud = pyaudio.PyAudio()
    stream = pyaud.open(format=pyaudio.paInt16,channels=1,
        rate = 44100,input_device_index=cardID,input=True,output=True)
    while True:
        if True in sampleNew: sample=numpy.append(sample,sampleNew)
            if len(sample):
                return sample


def buildNumber(num=123):

    if num>255: print "NUMBER TOO HIGH!!!"
    #print num,'=',
    for i in [7,6,5,4,3,2,1,0]:
        if num>2**i:one();num=num-2**i;#print"1",
        else: zero();#print"0",

def pulse():
    global data

def space():
    global data

def one():
    global data

def zero():
    global data

def silence(msec=1000):
    global data

def sendAudio(numbers=[11,66,77]):
    global data
    print "SENDING",
    for numba in numbers:
        print numba,

    p = pyaudio.PyAudio()
    stream = p.open(rate=44100, channels=1, format=pyaudio.paInt16,
                    input_device_index=cardID, output=True)

while True:
    if val == False: continue
    for item in val: line+=str(item)+","
    print i,line


What if we want to send data TO the microcontroller? The solution is a little more complex, but quite doable. Just add an extra wire to the sound card’s speaker output and attach it to PCINT0 (the highest level internal interrupt). This is intended for advanced users, and if you’re doing this you probably are better off with USB or serial anyway! … but heck, why not do it as a proof of concept!

Note that the USB sound card speaker output was not powerful enough to trigger the digital input pin of the AVR, so an inverting buffer was made from a single NPN transistor (2n3904). The hardware interrupt was attacked to the collector, and the collector was attached through +5V through a 220 ohm resistor. The emitter was grounded. The base was attached directly to the sound card output. I also tried running the sound card output through a small series capacitor (0.1uF) and biasing the base to ground through a 1Mohm resistor and it worked the same. Hardware, simple. Chip-side software… a little more complex.

### VIDEO ###

This code is what was used on my PC for the
 demonstration video. The listenonly.py file
 (above on site) was also used without modification.
import pyaudio
from struct import pack
from math import sin, pi
import wave
import random
import numpy
import time

maxVol=2**15-1.0 #maximum amplitude
p = pyaudio.PyAudio()
stream = p.open(rate=44100, channels=1, format=pyaudio.paInt16,
		input_device_index=1, output=True)

def pulseZero():
    global wvData
    wvData+=pack('h', 0)*30
    wvData+=pack('h', maxVol)

def pulseOne():
    global wvData
    wvData+=pack('h', 0)*40
    wvData+=pack('h', maxVol)

def pulseSpace():
    global wvData
    wvData+=pack('h', 0)*50
    wvData+=pack('h', maxVol)

def buildNumber(num=123):
    if num>255: print "NUMBER TOO HIGH!!!"
    for i in [7,6,5,4,3,2,1,0]:
        if num>2**i:

wvData+=pack('h', 0)*2000
pulseOne() #required before sending data


wvData+=pack('h', 0)*2000

while True:
	print "SENDING",
This code is what was used on my AVR 
microcontroller for the demonstration video
#include <avr/io.h>
#include <avr/delay.h>
#include <avr/interrupt.h>

volatile long commandIncoming=0;
volatile char command1=0;
volatile char command2=0;
volatile char command3=0;
volatile char command4=0;
volatile char bitsGotten=0;

// timing thresholds are critical! Send pulses to the chip
// and have it report the time between them. Use this to 
// determine the best threshold value for your application.
// The ones here must be changed if you run at a speed other 
// than 1mhz or if you use different timings in PC software
#define thresh_low 100 // between this and the next
#define thresh_high 130 // is the range for a logical 'one'

// ######## OUTGOING AUDIO DATA #########
void solid(){
	_delay_ms(1); //LONG LOW
	pulse(3);pulse(5);pulse(5);// CALIBRATION PULSES
void pulse(char size){
	while (size){size--;_delay_us(100);}
void sendVal(unsigned long tosend){
	pulse(5); // send a space
	while (tosend){
		if (tosend&1){pulse(3);} // send ONE
		else {pulse(1);} // send ZERO

// ######## INCOMING AUDIO DATA #########
SIGNAL (PCINT0_vect) { // audio input trigger
	TIMSK0|=(1<<TOIE1); //Overflow Interrupt Enable
	if (TCNT0<10){return;} // seem too fast? ignore it!
	// Enable the following line to test custom timings
	commandIncoming=commandIncoming*2; // shift left
	if (TCNT0>thresh_low){commandIncoming++;} // make 1

	if (bitsGotten){sendStuff();}	

void fillCommands(){

void sendStuff(){
	TIMSK0=0; //Overflow Interrupt
	cli(); // disable interrupts!
	solid(); // start data transmissions with this
	sei(); // enable interrupts again!
	TIMSK0|=(1<<TOIE1); //Overflow Interrupt

// ######## MAIN PROGRAM #########
int main(){


	MCUCR = 0b00000010; // trigger interrupt on falling edge
	GIMSK = 0b00010000; // pin change interrupt enable 0
	GIFR =  0b00010000; // flag register, same as above
	PCMSK0 = (1<<PCINT0); // Set Pin to use (PCINT0)
	sei(); // enable global interrupts

	// SET UP 8-bit COUNTER
	//TCCR1B|=(1<<CS12)|(1<<CS10); // prescaler 1024
	TIMSK0|=(1<<TOIE1); //Enable Overflow Interrupt Enable
	TCNT0=0;//Initialize our varriable (set for 1/15th second?)

	for (;;){}
	return 0;


In closing, I’m tickled this works so well. It’s funny to me that no one’s really done this before in the hobby field. I’m sure I’m not the only one who wished there were an easy way to do this. I’m sure the process could be greatly improved, but this is a fun start. Wow, it’s late, I should get to bed. I have to treat patients tomorrow morning!

PS: If you replicate this concept, let me know about it! I’d love to see your project!

About the author

Scott W Harden

Scott Harden has had a lifelong passion for computer programming and electrical engineering, and recently has become interested in its relationship with biomolecular sciences. He has run a personal website since he was 15, which has changed names from HardenTechnologies.com, to KnightHacker.com, to ScottIsHot.com, to its current SWHarden.com. Scott has been in college for 10 years, with 3 more years to go. He has an AA in Biology (Valencia College), BS in Cell Biology (Union University), MS in Molecular Biology and Microbiology (University of Central Florida), and is currently in a combined DMD (doctor of dental medicine) / PhD (neuroscience) program through the collaboration of the College of Dentistry and College of Medicine (Interdisciplinary Program in Biomedical Science, IDP) at the University of Florida in Gainesville, Florida. In his spare time Scott builds small electrical devices (with an emphasis on radio frequency) and enjoys writing cross-platform open-source software.

Permanent link to this article: http://www.SWHarden.com/blog/2011-07-09-sound-card-microcontrollerpc-communication/


  1. Philipp

    This type of communication could be easily implemented on a smartphone such as android or iphone, cause those have a 3,5mm stereo 4 contact tip, with the additional 4th contact for the microphone. If there is any possibility to run your script on an android phone, this would be very cool!

  2. Rock Kennedy

    Do you need wires? I’m interested in the “wireless” possibility. Use a mic for the computer and a speaker on the micro-controller. Wonder how ambient noise might interfere?

  3. alfredo ricciotti

    Well, to avoid ambient noise you could just well-modulate your signal. A lock-in comes to mind or, if you fell adventurous, a Spread Spectrum soluction could be the optimum if a bit slow.

  4. Ian

    You can program on Android in C/C++ also
    So executing the script on a Android phone should not be a problem.

  5. dan

    After reading your article it just seems so obvious. Great work.

  6. Ervin

    Is there a particular frequency you’re using with the sound or will any loud sound do?

  7. Scott

    Any loud sound will do!

  8. N3krodamus

    Excelent work, I have a question . Why don’t use a simple microphone plug instead of soldering the wires? (Sorry my english Im not an english speaker) Thanks.

  9. Scott

    …because experimenting with a cheap sound card is safer than experimenting with the sound card built into an expensive motherboard.

  10. ssd

    You could implement psk31 and then get some _real_ data transfer ;-P

  11. Scott

    @ssd – if by “real” you mean unnecessarily slow, I completely agree

  12. Clifford

    I have thought about something like this for awhile now but the idea was to do something along the lines of the old style carter phone which the computer sent a tone out and in much like a 56k dial up modem. Think about it say your using this usb sound card thing with your unlimited talk time on your cell phone getting free internet from back home with no caps or limits from a server with a second usb sound card setup and someone to answer the phone. Hey even a pair of CB’s might work.

  13. Gisele Bundchen Photoshoot Videos

    It’s actually a nice and useful piece of info. I am glad that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

  14. Jason

    I wasn’t thinking but it all clicked all of a sudden a few minutes ago. Why not use the dac and adc of your normal sound card to send data. stereo signal, left channel = clock signal, right channel data.

    I’m not sure about initializing microcontrollers, but I’d guess you can hand them power and they’re ready to take instructions right off the bat. I’m going to try analog audio through audio out to see if I can get some led’s to light up. Yeah! running a program using windows media player!

  15. Nida

    An outstanding share! I’ve just forwarded this onto a colleague who has been conducting a little research on this.
    And he in fact ordered me breakfast because I found it for
    him… lol. So allow me to reword this…. Thanks for the meal!!
    But yeah, thanx for spending time to discuss this topic here
    on your site.

  16. Sherry

    Admiring the persistence you put into your site and in
    depth information you present. It’s nice to come across a blog every once in a while that
    isn’t the same out of date rehashed information. Great read!
    I’ve bookmarked your site and I’m adding your RSS feeds to my
    Google account.

  17. Remington

    Am I missing something? Why did you connect the ground wire? It seems that you only needed the mic input, not ground. Unless I am misunderstanding a part of your code somewhere? Also I am guessing this is running at 5v? How did you not blow the mic on the sound card unless somehow you are using the ground input as the logic “low”?

    Sorry if I sound new to this, I am to an extent!

  18. Leonidas

    Bit Error Rate at given Signal to noise Ratio?
    Implemented Error Correction and/or Error Detection?
    Why re-invent the wheel?
    There other more efficient modulation methods very well documented
    Nice try however.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>