How to enable Motion Detection Interrupt on MPU6050.

The MPU6050 data sheet has a nice “marketing” section, claiming it has a DMP unit, and a couple of useful interrupts, among them a accelerometer event interrupt.

However, how to actually use these features is not documented there. And I want to use the Motion Detection Interrupt (so I can put the host MCU to sleep and wake it up when the MPU6050 senses motion – quite probably there’s a cheaper and better documented chip that can do this too, but I already bought a few MPU6050’s… “gy521” breakout board). is a in progress development to reverse engineer how to use the DMP. It also has a very useful register map (Thanks!), that fills the gaps in the “RM-MPU-6000A-00” document. With that register map, and a slightly older data sheet that actually has the section 8.3 that’s referred to elsewhere (found at , but that URL seems like it might not stay.), I could figure out how to enable the Motion Detection Interrupt.

After power on (0x00 to register (decimal) 107), the Motion Detection Interrupt can be enabled as follows:

  • (optionally?) Reset all internal signal paths in the MPU-6050 by writing 0x07 to register 0x68;
  • write register 0x37 to select how to use the interrupt pin. For an active high, push-pull signal that stays until register (decimal) 58 is read, write 0x20.
  • Write register 28 (==0x1C) to set the Digital High Pass Filter, bits 3:0. For example set it to 0x01 for 5Hz. (These 3 bits are grey in the data sheet, but they are used! Leaving them 0 means the filter always outputs 0.)
  • Write the desired Motion threshold to register 0x1F (For example, write decimal 20).
  • To register 0x20 (hex), write the desired motion duration, for example 40ms.
  • to register 0x69, write the motion detection decrement and a few other settings (for example write 0x15 to set both free-fall and motion decrements to 1 and accelerometer start-up delay to 5ms total by adding 1ms. )
  • write register 0x38, bit 6 (0x40), to enable motion detection interrupt.

Translate the above into code for your favourite micro controller. (Or, maybe, the existing Arduino library for MPU6050 already supports this. I don’t know, I’m using STM32 this time. But it could be translated to AVR/PIC/MSP430 etc… as long as it has I2C/TWI)

Now, INT pin should go high when MPU6050 is moved/shaken/dropped. Play with threshold, duration and filter to set sensitivity.

Relevant excerpt from the linked older data sheet (PS-MPU-6000A-00 Revision: 3.1) above:

8.3 Motion Interrupt
The MPU-60X0 provides Motion detection capability with similar functionality to Free Fall detection. Accelerometer measurements are passed through a configurable digital high pass filter (DHPF) in order to eliminate bias due to gravity. A qualifying motion sample is one where the high passed sample from any axis has an absolute value exceeding a user-programmable threshold. A counter increments for each qualifying sample, and decrements for each non-qualifying sample. Once the counter reaches a user-programmable counter threshold, a motion interrupt is triggered. The axis and polarity which caused the interrupt to be triggered is flagged in the MOT_DETECT_STATUS register.

Like Free Fall detection, Motion detection has a configurable acceleration threshold MOT_THR specified in 1mg increments. The counter threshold MOT_DUR is specified in 1 ms increments. The decrement rate has the same options as Free Fall detection, and is specified in the MOT_DETECT_CTRL register.

HH! Comment section below is open (no login required) for questions & remarks!

Fine motor skills?

I did not know this was possible.

The hollow core motors of a Cheerson CX-10 can actually be opened, and a new wire can be soldered to the brushes when the original one broke of.


This started as a challenge, me stating it was impossible to open these motors without damaging them beyond repair and my father insisting it is possible. So don’t ask me how to open them, I still think it is impossible. I only soldered the wire and closed it again. (Make a hole for the new wire by removing all residue of the old wire, remove part of the glue over the brushes, tin the new wire, then very quickly solder it, as to not overheat the plastic. Carefully press the back back on the motor again, making sure the brushes don’t bend in ways they are not supposed to)


And now my CX-10 is flying again. With a battery that’s slightly to large, a half-painted side to help orientation (Does not actually help), and rubber bands instead of screws holding it together. Also, half its props are pink because those where the last ones I had around. So its almost as ugly as possible, but it’s flying again. And that’s kind of crazy.


(And yes, I bought new motors just in case, and I still think this repair should be above my fine motor skills (pun intended) as everything is way to tiny and way to melt-able, but apparently its less impossible then I thought.)

Python echo

This adds a echo to a wav file. The file also gets louder, because the result is not normalized. (sample + 0.8*Othersample v.s. sample+0.8*Othersample/1.8). This is my first real experiment with DSP.  Maybe More Later(tm). Comments are welcome. (no registration necessary / pre-moderated by me)

Echo. Usage: python_Echo InpuFile.wav OutputFile.wav Delay_in_Seconds
0.15 seconds gives a believable echo. Pass a file multiple times trough it or modify source for multiple echo's

Only works with 1ch WAV files. To be improved Later(tm).
import sys
import numpy as np
import wave
import struct

if len(sys.argv) != 4:
        print "Usage: python_Echo InpuFile.wav OutputFile.wav Delay_in_Seconds"
delay = float(sys.argv[3])

if delay > 2:
        print "weirdly long delay. Try < 2"
framerate = w.getframerate()
frames = w.getnframes()
channels = w.getnchannels()
width = w.getsampwidth()
print("sampling rate:", framerate, "Hz, length:", frames, "samples,",
"channels:", channels, "sample width:", width, "bytes")
data = w.readframes(frames)
sig = np.frombuffer(data, dtype='<i2').reshape(-1, channels)

echo_output =[2], 'w')
echo_output.setparams((channels, width, framerate, 0, 'NONE', 'not compressed')) #output file matches input file params

values = []

for i in range(0, frames):
        if i > delay*framerate:
                value = sig[i] + 0.8*sig[i-delay*framerate] #add echo
                value = sig[i]
        packed_value = struct.pack('h', value) #this failes for 2 channel files.

value_str = ''.join(values)

outsig = np.frombuffer(value_str, dtype='<i2').reshape(-1, channels)

print "done"

Used sources:

And something about DSP from a dead-tree book.

Continued “data transmission whistle” experiment, more successful this time

Okay, what’s this about?
Oona Räisänen challenged her readers to construct a whistle that could transmit data using FSK.

And if one reads her challenge carefully it says “whistle”. Not “pea whistle“. Now THAT simplifies things a lot!

A whistle design like this can be modified by inserting a magnet and wrapping a coil around it to act as an electromagnet. That way the length of the channel can be varied by moving the magnet, and with it the wavelength of the sound.

Then, by controlling the electromagnet with the bitstream – to – be – transmitted, one can transmit data by whistling.

So, I built such a whistle (Dutch). With a simple arduino sketch and a mosfet it is indeed possible to transmit data by whistling.

Datatransmission by whistle

It sounds like this. (that ticking/clicking noise when I’m not whistling is the magnet moving.)

I do not have the skill level that Oona has when it comes to decoding mystery signals, so I can’t decode the data out of that. I just hope the signal can still be decoded. But it is supposed to say “HELLO”, with leading 0xAA 0xA7. Bit time is 75ms, that is: for every “1” in the bitstream the electromagnet is powered for 75ms, and for every 0 it is left unpowered.

And because it is close to the new year, a bonus audio file for those among us that like to decode mystery signals: clicky.🙂

(Failed) Pea whistle experiment

Well, not really failed, since every result is a result. I just found a way how this does not work. Two in fact.

Okay, what’s this about?
Oona Räisänen challenged her readers to construct a whistle that could transmit data using FSK.

So, I thought about replacing the pea in a pea whistle with a magnet, and then using an electromagnet outside the whistle to slow down (or stop) the pea’s movement during whistling. Since the pea modulates the whistles sound by blocking the “air exit” of the whistle when moving past it, slowing the pea down for a couple of revolutions should frequency modulate the whistle.

pea whistles Lees verder (Failed) Pea whistle experiment

ATX computer power supply current limit.

(This post is also available in Dutch)

For another project I’m tinkering with an old computer power supply. While I’m at it, why not see if I can build some crude current limiting. It does not need to regulate the current neatly, as long as it is short circuit proof.

A LED on the 12V output of a computer PSU would normally be blown to bits. Such a power supply can furnish ridiculously large amounts of current, while a LED only needs 20mA and as a diode won’t self-limit this. The PSU in the picture is an old one, the 12V line is orange instead of yellow. (The 3V3 is brown.) The 12V can deliver about 7A, 350 times more than the LED needs.


Yet, in this picture, the LED does not break, because I added some current limiting circuit. How does this work?

WARNING: Do not try this at home. Or anywhere else. Or at least don’t blame me if you do anything stupid and/or electrocute yourself. There are dangerous (potentially lethal) voltages inside a computer power supply. I won’t tell you to disconnect it from mains and discharge primary capacitors before you work on it, you should know already or else leave the cover on. Put that screwdriver down!

Voltage regulation in a atx computer PSU is done via optocouplers. The controller IC, UC3842 (or similar) is after all connected to mains power.

On the secondary side of the supply a TL431 is used to send current trough the LED of an optocoupler when the output voltage of the PSU goes too high. The TL431 is used as a comparator (it is a programmable zener / shunt regulator / voltage reference). The other side of the optocoupler is connected to the uc3842 so it lowers its duty cycle and therefore the output voltage.

At schematics of computer power supply’s can be found. Go there to see the voltage regulator circuit (And all the protection circuits I removed from my PSU)

A crude form of current limiting is actually quite easy to make.

By connecting a second optocoupler with its transistor side parallel to the transistor of the first, the output voltage will go down if the led in the second optocoupler gets activated. For the UC3842 this is the same situation as when the output voltage goes to high. So now all I need is a circuit that activates the second optocouplers LED when the output current rises to high, and I have a crude form of current limiting.

This circuit is not that hard. Every resistor has a voltage drop if there is current going trough it. Ohms law. So the output current can easily be measured by putting a resistor in series with it. A sense resistor. Then a transistor that starts conducting when the voltage over the sense resistor surpasses 0,7V. Have the transistor drive the LED from the opto, and that’s the circuit.


For this test the sense resistor is 68Ohms. This would be a current of 0,7/68R=10mA. Because the voltagedrop over the sense resistor can be annoying it’s possible to connect the voltage regulation feedback after the sense resistor so it will compensate. I have not done that for this test.

In practice I won’t limit the current to 10mA, but more likely to 10A, and the sense resistor would be much smaller (0,068R).

But for this test it’s fun to light a LED with a computer power supply.

The current limit oscillates, causing the LED to flash, see video below:

If instead of the LED I connect my ammeter, the value fluctuates between 10 and 20 mA, but probably the peak values are further apart and the meter can’t keep up with the change.

But for short circuit protection this works fine. A big disadvantage however is that the fan in the PSU is on the same 12V line and also gets tuned down / turned off when current limit kicks in.

Because all the “modified computer PSU” project i’ve so far seen on the web only mess with the output voltage and not with the current limit, I decided to post this in both Dutch and English in the hope that it will be useful to anyone, however this idea comes with NO WARRANTIES whatsoever. Please note the rectified line voltage inside those supplies is potentially lethal and capacitors might remain charged to this voltage even when the supply is disconnected from mains. Do not attempt this unless you know how to safely deal with this. If you do attempt this, you do so at your own risk.

Please let me know if you see a similar project somewhere that also deals with current limit on a modified computer powersupply.

ATX voeding stroombegrenzing.

Ik ben voor een ander project wat aan het prutsen met een oude computervoeding. Nu ik toch aan het prutsen ben, eens kijken of er een simpele stroombegrenzing te klussen valt. Het hoeft geen nette stroomregeling te zijn, als het maar kortsluitvast is.

Een LED op een uitgang van een computervoeding zal normaal gesproken onmiddellijk stuk gaan, zo’n voeding kan lomp veel stroom leveren. Het exemplaar op de foto is een oudje, de 12V lijn is oranje ipv geel (Normaal is de 3V3 oranje, maar die is hier bruin), en kan zo’n 7A leveren. De 5V (rood) zelfs 22A. De LED mag maar 20mA krijgen, dus 7/0,02=350 keer minder dan de 12V kan leveren.


Op deze foto gaat de LED niet stuk, want ik heb een stukje stroombegrenzing toegevoegd. Boven de connector is al een stukje van het circuit te zien. Maar hoe werkt het?

Waarschuwing: Niet thuis uitproberen, of waar dan ook elders, als je niet al weet hoe veilig om te gaan met de (potentieel dodelijke) gelijkgerichte netspanning in zo’n computervoeding. Als je het uitprobeert, dan doe je dat op eigen risico. Condensators kunnen nog lading bevatten ook als de voeding niet meer met het lichtnet verbonden is. De Engelse versie van deze blogpost heeft een uitgebreider disclaimer, voor de Nederlanders hoop ik op wat common sense. (Wat Engelstaligen ook moeten hebben gezien het een Engels woord is. Maar ik dwaal af)

De spanningsregulatie van een atx computervoeding gaat via optocouplers. Het regelIC, UC3842 (of variant) is immers vrijwel direct met het lichtnet verbonden.

Aan de secundaire kant van de voeding wordt een TL431 gebruikt om indien een de uitgangsspanning te hoog wordt, de LED van een opto te laten oplichten. De andere kant van de opto zit aan de uc3842, zodanig dat deze de pulsbreedte naar beneden regelt en de uitgangsspanning dus weer lager wordt.  De TL431 wordt eigenlijk als een soort comparator gebruikt, al is het een instelbare zener / voltage reference / shunt regulator.

Op zijn wat schema’s van voedingen te vinden, zie aldaar voor het spanningsregelcircuit. (En alle overvoltage/overcurrent beveiligingen die ik er bij mijn voeding uitgesloopt heb)

Een lompe vorm van stroombegrenzing blijkt veel simpeler te maken dan gedacht.

Door een 2e optocoupler met z’n transistorkant parallel te zetten aan de eerste, valt de uitgangsspanning naar beneden te regelen als er stroom door de LED van de 2e opto loopt. Vanuit de UC3842 gezien gebeurt er namelijk precies hetzelfde als wanneer de eerste opto gaan geleiden in geval van een te hoge uitgangsspanning. Nu nog een circuitje dat stroom door die optocoupler LED stuurt bij teveel uitgangsstroom, en ik heb een lompe vorm van stroombegrenzing.

Dat circuitje is niet zo moeilijk. Over elke weerstand valt spanning als er stroom door loopt, dus de uitgangsstroom laat zich makkelijk meten door een weerstand in serie te zetten. Een senseweerstand. Verder een transistor die als de spanning over de senseweerstand boven de 0,7V komt gaat geleiden. En vervolgens die transistor de LED van de 2e opto aan laten sturen.


Voor deze test is de senseweerstand 68R. Dit zou een stroombegrenzing opleveren op 0,7V/68R= ongeveer 10mA. Om de spanningsval over de senseweerstand vervelend kan zien, is het leuk de feedback van de spanningsregeling ná de senseweerstand af te tappen. Dat heb ik voor deze test niet gedaan.

In de praktijk ga ik de stroom van een voeding die zo veel stroom zou kunnen leveren als deze natuurlijk niet op 10mA begrenzen, maar eerder op rond de 10A, en de senseweerstand zou dan 0,068R worden. Maar als test is het leuk eens te proberen een LED te laten branden op een ATX voeding.

De stroombegrenzing gaat oscilleren, wat leid tot een knipperende LED. Zie het volgende filmpje.

Als ik in plaats van een LED mijn stroommeter aansluit, schommelt de waarde tussen de 10 en de 20mA, maar waarschijnlijk zijn de pieken groter en kan de multimeter het allemaal niet bijhouden.

Maar als kortsluitbeveiliging werkt dit prima. Nadeel is wel dat de ventilator van de voeding op dezelfde 12V rail zit, en dus ook naar beneden wordt geregeld/uit gaat als de stroom begrensd wordt.

Laat het me weten als je een soortgelijk project ergens tegenkomt, wat ik tot nog toe tegenkwam was alleen spanningsregeling, daarom post ik dit.