Electronics notes/Signal modulation: Difference between revisions

From Helpful
Jump to navigation Jump to search
mNo edit summary
 
(66 intermediate revisions by the same user not shown)
Line 1: Line 1:
{{#addbodyclass:tag_tech}}
{{Electronics notes}}
{{Electronics notes}}


===Pulse Width Modulation===
Most broadly, pulse modulation refers to modulating or communicating or approximating a signal in a way involving pulse trains.
 
Note also that PAM resembles AM, PPM resembles PM, and PWM (moderately) resembles FM.
 
(Also, some of these parts run into analog and digital (passband) modulation,
and for decent handling of said topics you're much better off on serious sites for those.)
 
 
 
Purposes and best uses are varied.
<!--
Pulse Width Modulation is the best known to DIYers, because it is a good way to get output of variable-level voltage (and, indirectly, current) from microcontrollers, from general-purpose IO pins i.e. without having to add a DAC.
-->
 
 
=Side note: Pulse Code Modulation=
 
Pulse-code modulation refers more widely to the idea of samples at at regular (uniform) intervals, and storing them as distinct values.
 
It that we're quantizing in time and amplitude, roughly how to store, and what it represents.
: ...and is not a reproduction technique, like most of this page. {{comment|(reproduction was a separate thing even in the earliest development of these concepts)}}
 
 
Variants include:
 
Unqualified '''PCM''' usually means
: quantization levels are linearly uniform (so [[ratiometric]]) with amplitude
:: ...physical amplitude, so not with ''perceived'' loudness
: used for sound, it means most of the bits are used on really quiet stuff (because human perception is logarithmic).
:: which is actually quite useful (for human consumption of audio)
:: also why 8-bit PCM is audibly not enough, and 16-bit ''is'' (for most things)
: probably easiest raw format to deal with (particularly when storage/bandwidth are not an issue)
: Directly used in Audio CDs (Red Book), in WAV files, and quite a few others.
: Also used in some way or other in a number sound- or music-related electronics, although note that mu-law and a-law are seen in some older hardware
 
 
'''logarithmic PCM'''
: Because of the nonlinear way we hear loudness, and given a fixed, limited bandwidth, people at different volume levels get similar signal-to-quantizing noise ratio - than linear PCM{{verify}}
: since the original input and eventual reproduction is often LPCM (it's a choice most hardware makes), this is often used to effectively [http://en.wikipedia.org/wiki/Companding compand] signal while in transmission/storage
: implementations include '''&#956;-law (mu-law)''' and '''A-law'''
:: which historically implied 8-bit and often 8000Hz implementations, as used in early digital phone transmissions (see e.g. ITU-T G.711)
: if storage is not a hard constraint (and harder than CPU use), then linear PCM is easier and log PCM is probably more work than it's worth
:: u-law and a-law are quoted as ''roughly'' comparable to the quality of 12-bit linear PCM (in what regard?{{verify}})
: {{comment|(even though technically 16-bit logarithmic still give better detail than linear 16-bit{{verify}}, you generally don't need it)}}
 
 
 
Differential PCM
: says that instead of storing the absolute values, we store the difference from the last, or to a (deterministically) ''predicted'' next value.
: If the prediction is reasonable, we need to send fewer bits.
: This is generally a smaller number, so allows a slight reduction in storage, but not much
 
 
<!--
Delta PCM
: when not being confused with differential PCM (as I did)
: [https://en.wikipedia.org/wiki/Delta_modulation delta modulation] refers to cases where direction of change is more important than amount of change
:: and you may be using oversampling to help
:: related to [[Delta-Sigma modulation]]
-->
 
 
 
'''ADPCM''' is ''Adaptive'' Differential PCM.
 
It takes the differential PCM output, and ''varies'' the amount of quantization of it over time.
 
This is a lossy format that allows you to tweak bandwidth/SNR on noisy / low bandwidth channels.
: often 5-, 4-, or 3-bit
 
 
'''SB-ADPCM''': ADPCM, but applied to distinct frequency '''s'''ub-'''b'''ands.
: For example, [[G.722]]
:: splits into two bands (roughly 0Hz to 4kHz, and 4kHz to 8kHz), then applies ADPCM to each
:: This mainly so that you can spend bits differently, e.g. 48 of the 64 kbit/s on the lower sub-band that includes most voice energy, and 16 kbit/s on the rest. {{comment|(G.722 actually has a few different target bitrates)}}
 
 
 
 
Even when storage/transmission is mu-law/A-law or ADPCM or some other codec,
processing on endpoints is often LPCM, mostly because it's easier and faster to work with.
 
 
For context on companding: linear PCM is not clever about spreading quantization to where our (approximately logarithmic) perception hears it best. Companding basically rescales (in a reversible way) to reduce that issue.
 
The companding step is lossy, but since the signal to noise ratio is better than linear PCM in the same amount of bits, it provides quality improvements - and rather useful whenever you are bandwidth-limited.
 
 
Both &#956;-law and A-law are used in analog and digital telecommunication {{comment|(in analog it was mostly for quality, in digital tranfer it was also handy for compression)}}, in different countries.
 
The .au sound format uses &#956;-law.
 
 
 
 
See also:
* http://en.wikipedia.org/wiki/Pulse-code_modulation
 
* http://en.wikipedia.org/wiki/Mu-law
* http://en.wikipedia.org/wiki/A-law_algorithm
* http://en.wikipedia.org/wiki/Companding
 
* http://en.wikipedia.org/wiki/DPCM
* http://en.wikipedia.org/wiki/Adaptive_DPCM
* http://en.wikipedia.org/wiki/Delta_modulation
 
<!--
* R Stroh, M Paez (1973), "{{search|A Comparison of Optimum and Logarithmic Quantization for Speech PCM and DPCM Systems}}"
-->
 
 
 
See also:
* http://en.wikipedia.org/wiki/ADPCM
 
-->
 
=Continuous wave modulation=
 
==Amplitude Modulation (AM)==
 
==Frequency Modulation (FM)==
 
==Phase Modulation (PM)==
 
 
=Related: Dimming practicalities=
 
<!--
Classical TRIAC dimmers basically take an existing AC waveform able to drive reasonable current,
and switch on some time into each wave.
 
This related to various things here, but not very clearly
 
You could call it PWM-like in that the power delivered comes from the duty cycle
 
You could relate it to phase modulation (maybe PLL) in that it ''relies'' on the waveform
 
You could call it AM-like (if boolean)
 
-->
 
=Pulse modulation=
 
==Pulse Amplitude Modulation (PAM)==
<!--
 
Alternating zero and a leveled signal.
 
(so like generic amplitude modulation with just amplitudes 0 and 1)
 
 
Usually assumed to be wire-level applications so introduced in analog terms.
For example, if you have an existing sine wave, you can might regularly zero portions of it out, e.g. using some gate.
 
 
PAM can be useful to transmit both
* analog signal
* a clock
 
The other side can synchronize to the clock, and sample the voltage signal at the right time.
 
Because you do this over a single wire,
you can send clearly distinct voltage levels, over the same amount of wire in the same amount of time.
 
 
Variants of PAM are used in Ethernet [https://www.edn.com/electronics-blogs/absolute-eda/4441982/PAM---Ethernet--A-perfect-match]
which does actually interpret it digitally, sending few-bit codes with some noise immunity.
 
 
 
It turns out that you can build slightly more efficient LED dimming with PAM rather than PWM,
roughly because a lower forward current is more efficient than averaging all-or-nothing.
That said, it takes more components{{verify}}
 
 
 
 
You can have more analog goals.
 
You can reconstruct something closeish to the original signal with just a lowpass filter, because that gating is a specific higher frequency (plus its harmonics).
(There is some in-band loss, which is relatively predictable so this amplitude distortion can be normalized back)
 
Upsides:
* simple to implement both modulation and demodulation
 
Downsides:
* often noisy
 
...so the question becomes more about your goal
 
 
 
 
 
 
https://www.elprocus.com/pulse-amplitude-modulation/
-->
 
==Pulse Skip Modulation (PSM)==
<!--
Given a constant pulse rate, deliver some pulses and not others.
 
 
The most common use is probably around power conversion, though there are others.
 
 
On a related note, when you are gating AC mains power (see e.g. dimming, also solid state relay switching),
it is often a good idea to detect when that wave is at zero, so you can do [[zero cross switching]] to avoid sudden current changes.
 
This is e.g. the idea behind simple dimmers - at least the ones intended for incandescent because the filament's thermal inertia means they smooth over the gaps. (rather than flicker wildly or stop working, as the first generations of power saving bulbs would do).
 
 
PSM is often higher higher efficiency with light loads (why?)
 
 
It is also easier to apply to AC
 
 
 
https://arduino.stackexchange.com/questions/51852/arduino-code-for-pulse-skip-modulation-psm
-->
 
==Pulse Position Modulation (PPM)==
<!--
Signifies values by the time delay a (fixed-length) pulse is transmitted in.
 
Which makes it typically used for digital communication, a digital code with 2<sup>bits</sup> positions.
 
For higher amounts of bits, you put increasing requirements on accurate synchronization.
It's also sensitive to e.g. multipath arrival,
impedance problems,
capacitance,
and such
 
It is not very common as a generic tool, but e.g.
: efficient in optical telecom
: some space communication
: and in (primarily low-frequency) RF
: an augmented form of PPM is one of the systems of [[RC aircraft control]] (in part because this is a natural choice for [[servo]]s)
 
 
https://en.wikipedia.org/wiki/Pulse-position_modulation
 
 
 
-->
 
==Pulse Density Modulation (PDM), Delta-Sigma modulation (&#x394;&#x3A3;M)==
<!--
Modulating: using portions, over time
 
The relative density of these boolean pulses is used to represent amplitudes.
 
You're probably going 'wait, how is that different from PWM?' because yes, they share the "proportion of on and off over time". See more below, but roughly,
but where PWM has a regular period with a single long single pulse that stays on for more or less time,
you can see as PDM switching as quickly as sensible based on how much off the target value it currently is.
 
 
PDM used for audio will, like PWM, need to be run multiples faster than the target audio rate.
MHz clock rates make sense for PDM.
 
Which makes it just as impractical to output with [[bit banging]] from code as PWM is, but also like PWM, with the right peripheral it's relatively simple.
 
 
And yes, PDM is in theory smoother than PWM
Though at the same time, transistor switches need energy so doing so faster means more losses. (TODO: check what amount of power we're talking about),
so not all situatoins call for PDM even in theory.
 
 
 
 
Note that [[Electronics_notes_/_Inputs_and_outputs#PDM_in_the_context_of_DACs_and_ADCs|PDM as an audio transfer protocol]] is a specific implementation of the general PDM concept.
 
==Pulse Width Modulation (PWM)==
 
Pulse width modulation refers to switching between on and off, changing the amount it's held on, relative to the time it's held off,
to vary the energy delivered (or average voltage level) over a somewhat ''longer'' term.
 
 
 
When implemented digitally (as it usually is), this is typically a counter plus a threshold above which to switch on.
 
This means there is a clock rate at which it ''could'' switch between the two.
 
...and a much lower speed at which the entire thing goes on and off and repeats.
 
 
For example, if it can count at 1MHz, and have a 8-bit counter,
and switch at the same speed
then the waveform it creates repeats at {{comment|<nowiki>(1000000/256 ~=)</nowiki>}} 3.9kHz.
 
This will sometimes be called the 'PWM speed', or just output speed.
This isn't the best name, so check what is meant.
 
=See also=
<!--
https://www.elprocus.com/pulse-amplitude-modulation/
-->
 
=Practical notes=
 
 
===PWM Types===
<!--
 
Because PWM is typically a digital implementation, there are some variations that are easy to point out.
 
 
 
'''Single slope PWM''' (Atmel calls it Fast PWM{{verify}})
describes the simpler design, that was historically common.
 
It's
: a counter
: a threshold at which it switches the output (controls the duty cycle),
:: often on below the threshold, off above
: a threshold of counter reset (often fixed)
 
The start of an output pulse is always at the same interval,
Altering the output threshold moves aroudn the end of the pulse.
 
You could say that the leading edge is fixed, and you control the place of the trailing edge.
 
 
 
This is simple to implement, but comes with some footnotes.
 
In particular, from the view of the center of the pulse, that center moves.
So when changing duty cycle, you also get an effective a phase change relative to where it was before.
 
This doesn't matter for most control, but may when generating more precise signals.
 
 
 
 
'''Symmetric PWM''', sometimes '''dual slope PWM''', or '''Phase correct PWM''' (an Atmel name), is a little different:
: a counter
: a threshold to control the output (controls the duty cycle),
: counts to the maximum (may be fixed), then counts down to zero.
 
If the output is off below the threshold, and on above, this places the output pulse in the ''center'' of a cycle.
 
You could say that you move both leading edge and trailing edge, equally towards/away from the center of the pulse.
 
 
While the duty cycle is constant, you can't really this output apart from simple PWM (same amount of on/off time).
For bang-bang control (heaters, many lights), you wouldn't care.
 
However, it avoids a phase shift, which makes it preferable for doing signal generation, maybe when you combine outputs, etc.
 
 
Side note: because it has two slopes, in comparison with single-slope the cycles are twice as long the maxiumum PWM output frequency is half.
 
 
 
'''Phase and frequency correct PWM''' seems a specific name for a minor tweak of double slope that avoids glitches caused by changing comparator instantaneously, by only changing it when it gets to one edge (PRETTY SURE I MISUNDERSTOOD THIS) {{verify}}
 
 
 
 
Some PWM has a variation (may apply to single-slope as well as double-slope),
where you have a threshold as well as a value where the counter resets.
 
This gives finer control over the frequency, and effectively makes it faster (but varying with the duty cycle so not in a simple way).
In the case of the AVR this means you can only do this on one pin per timer{{verify}} instead of the usual two.
 
https://www.arduino.cc/en/Tutorial/SecretsOfArduinoPWM
 
 
 
 
'''PWM and motors'''
 
There are a few further types that apply mostly to specifics in motor control or power conversion.
 
 
(phase correct is slightly preferable - around speed changes?)
 
 
...though also note that the electric field and momentum of a motor is effectively a lowpass
 
 
There are also a few footnotes to avoiding motors unnecessarily squealing from PWM.
 
http://ijesat.org/Volumes/2014_Vol_04_Iss_01/IJESAT_2014_01_01_03.pdf
 
https://www.quora.com/What-are-the-disadvantages-of-PWM
 
 
PWM and motors also means signals at audio frequencies at decent currents.
That means you're emitting EM, and should consider shielded cables.
 
 
Also, while it acts like an RC filter on the PWM, the motor is likelier to squeal.
 
There are various things that may or may not help:
* capacitors
* faster PWM
* different motor types{{verify}}
 
 
https://www.quora.com/What-are-the-disadvantages-of-PWM
-->
 
===PWM for average energy===
<!--
 
When the main goal is delivering a relatively large and clunky amount of energy,
then you care mostly about duty cycle, less about switching speed, and even less about phase stuff.
 
 
Speed that turns out to be ''sufficient'' varies mostly with the sort of momentum of the thing you're driving energy into.
 
Consider '''regulating an oven, or electric stove-top, or water boiler''' involves a ''lot'' of [https://en.wikipedia.org/wiki/Thermal_mass thermal mass].
Even if you switch a chunky 1kW heater just on or off every second or two, you will still regulate the temperature well enough for almost any need - the air or pan or water just isn't going to change temperature that quickly, the food less so.
 
 
For another example, various types of '''electrical motors''' can be PWMed well.
The idea is still roughly that the duty cycle ends up meaning more average output.
 
Here you want to the PWM output to be somewhat faster. Yes, any speed will average the same energy, but the translation to physical force is often fairly direct, which would make it much twitchier, and harder to control precisely, also because the interaction between other forces (like friction and gravity) may work out a little differently.
 
As such, motor PWM is preferably done at above a few hundred Hz, in a few cases preferably a few khZ.
 
 
 
'''Driving LEDs''' depends.
The LEDs themselves can light up at the order of nanoseconds {{comment|(which e.g. makes them interesting for optical communication [https://en.wikipedia.org/wiki/Visible_light_communication easily at tens of MBit])}}, so PWM can make it blink hard-on, hard-off ''very'' quickly.  LEDs are faster than most PWM.
 
...but ''most'' of the time we're only doing it for human eyes, and our persistence of vision means that above ~40Hz we ''barely'' notice it's blinking (but might notice some visible weirdness and minor eyestrain), while above 100Hz or 200Hz most of the eyestrain is also gone (so aim for higher rates when you easily can).
 
 
'''Changing and regulating voltage''' was classically often done with just transformers,
but you can get more efficient conversion and more precise voltage regulation
with a well-controlled charge-discharge cycle.
 
Switching (and capacitors and/or inductors) is part of the design.
While in some designs you can use a simpler/cheaper component than PWM,
in some designs PWM is a sensible choice.
 
 
Since you often care about low [[ripple]] in power supply output,
faster duty cycle makes it easier to lower ripple.
 
As such, PWM in power supplies (primarily pointing to switch-mode power supplies)
tends to go at tens or hundreds of kHz or more,
and most of their noise is at those frequencies
(though intermodulation means there is still ''some'' lower frequency noise)
 
 
 
 
Notes:
: The typically-pulsed nature of LED dimming is why LEDs often look weird on camera: cameras tend to do very short samples at a regular rate that is also similar, so you are likely to get frames with the LEDs on or off. 
:: this effect is stronger in brighter environments, because the camera's shutter time will become shorter. The way you're capturing and then presenting frame is essentially visual [[sample and hold]])
:: And because PWM has its own timebase, which parts of that whole you actually see shifts over time (often slowly).
 
: It's also why you can actually communicate data over LEDs - without noticing that it's blinking
 
: LEDs are a pain around lab benches and some music gear, though because it's an EM emitter.
:: Both because it's switching moderate current, and because it's usually switching at a lowish speed (a few hundred Hz to few kHz range) which is well within audible range
 
: ''' ''Induction'' cooking''' is a more complex story. While often controlled by PWM, the heater coil is an LC circuit, and the process that actually heats introduces a few more practical physical constraints, relating also to pan thickness, material, and trying to avoid introducing interference at audio frequencies. Which together mean the aim is typically for ~24kHz resonance. Also in part because of IC quality at the time of invention.)
 
 
 
-->
 
===Hardware PWM, software PWM, and inbetween===
<!--
 
PWM is often implemented as a counter and comparator, in some way or other.
 
 
 
For PWM as done by a microcontrollers like AVRs and PICs (or larger embedded CPUs, like ARMs),
it matters how much attention it needs to actually do the job (at a particular speed), because
that affects CPU use and the timing of other things.
 
(For '''PWM ICs''' the details don't matter so much, as it's dedicated to just one job)
 
 
 
'''Dedicated PWM hardware''' usually refers to  that
put PWM circuitry on a few GPIO pins,
typically based on a fast existing clock (typically configure a divisor),
that can trigger pin state (possibly interrupts),
and have some well defined behaviour you can probably also configure via registers.
 
Details may matter, in that timers used by the PWM may be shared (so entangled) with other things.
 
 
 
If there is no such hardware, you have two other options.
 
'''Interrupt-based bit-banging''' - if you don't have such a counter-and-comparator setup, but still have the ability to trigger interrupts from a timer, you can write an interrupt handler that sets the pin,
based on your own counter.
(Alternatively, have that interrupt just count, and use that counter in your main loop)
 
Depending on your hardware, and what else the code has to do,
this may still be relatively fast and regularly, at little CPU cost.
It's typically less precise, though can be good enough e.g. for LED dimming.
 
 
 
'''Naive bit-banging'''
Consider:
set pin high
sleep 10ms
set pin low
sleep 90ms
...or such, here for 10% 10Hz duty cycle.
 
The upside is that you can do this on basically any microcontroller, and it can be fairly precise timing.
 
The obvious downside is that that you occupy all CPU so can do nothing else, meaning you've just made an expensive PWM IC.
 
 
 
'''Analog PWM''' - if you just want an adjustable average,
but a knob is enough and you don't need digital control,
then you don't need a microcontroller/counter setup.
 
You can use basically just a 555 to get a very decent approximation.
 
Or even a discrete-element bistable [[multivibrator]] (e.g. transistor flip-flop).
 
 
 
 
 
For example:
* The ATmega328 (think Arduino) has three timers, which each have two comparator outputs,
: which you can configuring via registers, that can provide PWM outputs on six pins. This is hardware PWM, in that it's (almost) entirely independent of what else you're doing
 
* The ESP8266 has no dedicated PWM, and just one timer (which you probably share).
: You can still get PWM of sorts - by updating pins from the timer interrupt i.e. interrupt-based bit banging {{verify}}, or even the naive sort
: This can be done fairly quickly, but still occupies main CPU, and getting more than one pin at more than one frequency out of this isn't easy.
 
* Some PICs do PWM, others do not {{verify}}
 
* The BCM2835 (think Raspberry Pi) seems to be a 2-pin 32-bit ~100MHz thing
: which is why it's fast enough to do some oversampling and its results are good enough to produce decent quality sound.
 
* {{search|555 PWM}}, {{search|transistor based PWM}}
 
 
 
 
http://www.righto.com/2009/07/secrets-of-arduino-pwm.html
-->
 
===PWM or PDM as a simple DAC===
<!--
PWM plus a lowpass filter can be used as a DAC.
 
But there are a handful of footnotes to this.
 
The lowpass is necessary because squarewaves by nature have all the overtones.
 
For a similar reason, you need the PWM's switching to go at a rate faster  than your highest produces frequency,
to be able to make that filter's attenuation strong by the time it gets to that frequency.{{verify}}
 
 
This is little different from most of the driving-average-energy sort,
where there is often some implied, physical averaging going on,
meaning you'll get average right on a shorter, nearly-continuous term.
 
Not without footnotes, mind.
For example, PWMing a DC motor without filtering may get you the speed you want, but additionally makes it whiny.
 
 
Generating DC levels (with a small ripple) this way is not very hard
(in part because PWM speed is hardly a constraint then).
 
-->
====Sound PWM====
<!--
 
PWM is a serviceable square-wave generator, except that you often can't change its base frequency very quickly or precisely (unless it takes an external clock).
 
 
 
And a moderately serviceable generator of more arbitrary waveforms, with some constraints.
 
Primarily that that if you want decent precision, the rate of that signal should be a few multiples slower than the PWM output rate.
 
 
For example, the Raspberry Pi's audio jack is PWM-based. The PWM behind it runs at megaHertz range (apparently 19.2 MHz for RPi), so depending on how much smoothing you find acceptable, you can get decent output to 10kHz.
 
 
You can get away with less, so even on microcontrollers you ''have'' less and can still make decent beepy oscillators.
 
 
Sound/music synthesis sees some uses of PWM (>tens of khz, sometimes hundreds),
but it's not very common for sound because even the cheapest DACs tend to be better at the same job. There are some bordercases
 
https://www.electrosmash.com/forum/pedal-pi/210-pwm-audio-on-raspberry-pi-zero
 
 
RPi:
Balanced mode sends a combination of clock pulses that results in an overall DATA pulses per RANGE pulses
 
Mark-Space mode - sets the output HIGH for DATA clock pulses wide, followed by LOW for RANGE-DATA clock pulses.
 
 
 
 
Implementations:
* analog solutions, e.g.
** a sawtooth and comparator
** the control signal you send to a servo is effectively a PWM signal
 
 
* digital: often a counter (from the main clock signal) and a theshold
** microprocessors that have PWM-capable pins typically do it this way
** and may then easily have multiple (often not fully separable) PWM signals
** e.g. arduino [http://arduino.cc/en/Tutorial/PWM]
** if tied to the primary clock, and not a divided variant, this can go very fast
 
* code-based version of the above
** which is often much slower (100Hz or so is a lot)
 
* e.g. the raspberry Pi's PWM is somewhat unusual - the frequency it can PWM at seems to vary with duty cycle
** apparently to balance the
** See http://raspberrypi.stackexchange.com/questions/4906/control-hardware-pwm-frequency and {{search|BCM2835 ARM Peripherals}}
 
 
 
 
 
TLC5940 16 channels of 12-bit PWM (meant for LEDs)
e.g. on the Sparkfun PWM shield
 
 
 
 
See also:
* http://en.wikipedia.org/wiki/Pulse-width_modulation
* https://learn.sparkfun.com/tutorials/pulse-width-modulation
 
-->
 
====On PWM resolution====
<!--
 
PWMs are typically a comparators run off a timer.
So they work like "keep on counting to 1024 and output a 1 while the count is below 256" is how you get a a 25% duty cycle.
 
Altering that threshold lets us generate 1024 distinct duty cycles,
so 1024 unique average voltages.
 
Spec sheets might mention this as 10-bit PWM, particularly if they can be configured to other things, random example [http://www.t-es-t.hu/download/microchip/an539c.pdf]
 
 
 
So, 10-bit PWM is a 10-bit DAC?
 
Ehh no, that' a fuzzy comparison at best. Yes, it means both can be told to go to 1024 different states, but what they output is not the same..
 
The various imprecisions is not directly expressible in bits, but it certainly reduces it.
 
 
There will still be
* ripple
: varying with filter design
 
* harmonics
: part of why you want a filter
: coming for a good part because filters and square-waves are not the best bedfellows (consider its FT)
 
* nonlinearities particularly noticeable when you're generating a varying/AC signal,
 
* most of which will vary with the speed you PWM at.
 
 
The choice of filter matters.
* A lower cutoff for the filter means less noise, but also slower adaptation.
(as in the end, both are frequencies). For some purposes this smoothness is actually a nice thing. Exact reproduction of a signal is not one of those, though.
 
* A passive filter is not ideal in terms of cutoff, and will e.g. attenuate the DC a bit
: better filter designs would help, yet getting a cheap DAC is very quickly a better deal in terms of cost, component count, and specs.
 
 
PWM of higher speed is handier, because this allows us to oversample,
basically making
 
 
 
 
When you want to generate precise signals, like sound, then
 
Speed also matters. Given the counter design, note that if you could control the number you count to, then e.g. counting to 512 instead sacrifices the amount of levels you could produce, but lets you do it twice as fast, effectively reducing ripple.
 
 
 
 
 
This may matter, for example, if you want to use PWM for audio.
However, this is a case where you will easily notice
 
 
It turns out that oversampling PWM helps reduce the nonlinearities,
so if you have a very fast PWM, it's actually a halfway decent DAC.
 
For example, the raspberry Pi built-in audio is quite-fast (MHz-range) PWM plus RC filter, capable of only mildly distorted audio.
 
While e.g. the standard arduino's ATmega328 is kHz-range and can at the highest speed barely cover audio frequencies, so will be low-fi. (Footnote: There are AVRs and other uCs with better specs)
 
 
 
 
https://hackaday.com/2018/07/13/behind-the-pin-how-the-raspberry-pi-gets-its-audio/#more-314654
 
 
-->
 
===On PWM distortion===
<!--
https://www.allaboutcircuits.com/technical-articles/low-pass-filter-a-pwm-signal-into-an-analog-voltage/
 
 
 
http://www.openmusiclabs.com/learning/digital/pwm-dac/pwm-distortion-analysis/
 
-->
====On PWM oversampling====
<!--
If you can run PWM multiples faster than the signal you need to generate,
you improve linearity of the output.
 
(this is also something many DACs do, for similar reasons)
 
 
That is, if you can PWM at perhaps 16 times faster than you the signal frequency that you need.
 
(note that you really might consider DACs at this point)
 
 
-->
 
====Unsorted====
<!--
 
There are other design notes, such as that a given duty cycle, run a lot faster, can be smoothed a lot more easily.
 
 
One valid reason is that the speed the PWM can go at puts a hard limit on how much resolution you ''could'' try to get.
 
 
And the higher the speed, the lower the effective resolution.
 
Note that in particular oversampled PWM is comparable to how oversampling DACs work - look at the workings of an [https://en.wikipedia.org/wiki/1-bit_DAC 1-bit DACs], and in fact most DACs ''internally'' do this.
 
 
 
triangle?: http://www.ti.com/lit/an/slaa116a/slaa116a.pdf
-->
===On PWM filtering===
<!--
 
PWM itself is a stark on and off.
 
In some cases you would really want to filter it to roughly get the  average voltage over a somewhat-longer-time-than-the-switching-rate.
 
 
The simpler circuit for this would be an RC lowpass filter.
 
Which is passive, and will slightly lower the level of your signal,
so when this matters you may want make an active filter (~= passive filter plus current buffer).
 
 
Since a lot of PWM signals come from ICs with lowish current capacity (order of 20mA), so the structure would then often have a transistor to drive something larger while not breaking that IC.
 
This helps in that the filter can assume it is sensed high-impedance (which you may need to organize yourself, probably via a current-limiting resistor in series), i.e. doesnt have to worry much about the effects of current drawn from it, and it's ''sort of'' an active filter construction.
 
 
There are better ways of doing it, when precision matters.
A better defined one that is still relatively simple,
is probably a Sallen-Key lowpass (an active filter).
 
http://sim.okawa-denshi.jp/en/OPseikiLowkeisan.htm
 
 
 
Note that with filters, often the lower the cutoff,
the slower the response to change.
This is great for making DC signals,
less so if you were actually making a signal which has shape over time.
 
It also means that faster PWM is better for lower ripple even on filtered output.
 
 
 
-->
 
===PWM IC notes===
<!--
 
PWM chips are useful when you don't necessarily need a DAC, or you may wish to drive a little current (PWM chips are often aimed at LEDs).
 
-->
 
====TLC5940====
<!--
TLC5940 is a 16-channel PWM with 12-bit duty cycle control.
 
It is made for constant-current LED driving (also has 6-bit current limit setting, and that in relation to a global reference),
up to ~120mA at 5V and ~60mA at 3.3V.
 
You can abuse it for more generic signal output.
 
It has a serial-style interface, and has approx four wires you need to control, plus one clock that the PWM speed will be based on.
 
In theory you can put a ~30MHz clock for a ~7kHz 12-bit PWM,
though controlled off an uC you'ld probably be hard pressed to put more than 1MHz on one pin from a timer,
so would not get more than about 244Hz on the output.
You could go faster if you want to give up bit depth, but regardless, this is on the scale of 'great for LEDs, not good enough for audio'.
 
 
Minimal connection:
* SIN, SCLK, XLAT, are used to send in data  ([[SPI]]-like?{{verify}}, SIN is MOSI)
 
* GSCLK is input clock
: on an AVR you may want to sacrifice existing PWM output, because that way you can generate 1MHz
 
* BLANK
: driving this low disables all outputs, and resets the PWM counter
: required low while sending in new values, and the XLAT pulse that makes them active
 
* You probably want [[bypass caps]] (e.g. 1uf, 100uf{{verify}})
 
* Iref depends on your use, the current is 39/R, so e.g. 2k makes for 20mA
 
 
Optional:
* VPRG and DCPRG control what you're currently doing with the chip
: both tied to ground is Grayscale programming mode, which is probably your main interest
: the other two things you can do is altering the dot correction, and talking to the EEPROM (which stores dot correction data - and also requires ~22V on VPRG to do. You may just want to leave them at their default, 63)
: (if you tie DCPRG to Vcc then you really want to set dot correction before anything else {{verify}})
 
* SOUT can be ignored until you want to daisy chain multiple of these.
 
* XERR can be ignored until you want to listen to the chip complaining about certain things
: broken/disconnected ports (can also be fetched using SOUT)
: thermal problems
 
 
Grayscale values are unknown at startup (dot correction defaults to eeprom{{verify}}, depending on what you tied DCPRG
to{{verify}}), so you probably want to set at least grayscale values before first enabling output via BLANK.
 
And since BLANK may be in an unknown state while your controller boots, you probably want a (~10k) pullup resistor to Vcc so that the LEDs are blanked whenever you don't actively drive BLANK low. (This may be less necessary if you have low currents via a higher resistor on Iref)
 
 
Setting new output values is a shifting thing (192 bits in grayscale PWM mode, 96 for dot correction), and becomes active after pulsing XLAT.
 
Both of these things need to happen with BLANK high (meaning outputs off)
so you probably want to minimize programming time.
 
Since BLANK also resets the PWM counter, the output is more correct if you
do so at the end of its PWM cycle (using a counter and/or timer from the controlling end).
 
 
If your controller has PWM, you probably want to use it for at least GSCLK,
and probably also use its (or a similar) timer interrupt hander to control BLANK and communication.
Without this it's harder to get ppredictable, regular behaviour from the TLC5940.
 
 
 
https://playground.arduino.cc/Learning/TLC5940/
 
https://sites.google.com/site/artcfox/demystifying-the-tlc5940
 
https://effluviaofascatteredmind.blogspot.com/2012/05/tlc5940-tlc5941-and-arduino.html
-->
 
====PCA9685====
<!--
 
PCA9685 is a 16-channel, 12-bit, PWM IC
with an I2C interface,
and can run off 5V, 3.3V, or 2.5V.
 
The rate of PWM cycles is between ~24Hz and 1.5kHz so you can e.g. use it for servos at 50-60Hz, or for LEDs probably at at least a few hundred Hz.
 
The switching rate is 98kHz to 6.2MHz {{verify}},
the PWM cycle rate (/4096) is 24 Hz to 1526 Hz.
 
 
All channels share this rate, each has its own value (in )
 
{{comment|(You control at what count it's turned on and off, so on top of duty cycle
you could control the phase between channels, though this matters for just a few things,
e.g. controlling specific motors)}}
 
 
It has an integrated 25MHz oscillator meaning it's a little more independent than some (e.g. the TLC5940)
and a clock-in pin that accepts up to 50MHz.
 
The clock division of that is configurable, but shared by all channels.
 
 
As per the doc
Prescale = round(osc / (4096*updaterate))-1
So approximately (because I'm ignoring the rounding), the update rate is
6103Hz / (prescale+1)
So e.g.
* prescale of 0x03 (the maximum) makes for ~1526 Hz
* default prescale of 0x1E (30) makes for  ~203Hz
* prescale of 0xff (the minimum) makes for ~23.8 Hz
 
 
Current capacity is aimed at driving basic LEDs directly:
: [[Open-drain]] at 25 mA (at 5V)
: Or [[totem pole]] with at 25 mA sink or 10 mA source (at 5V)
 
(effectively current limited?{{verify}})
 
Variants:
* PCA9635 - 8-bit PWM, fixed 97kHz, no clock in, less common?
 
 
-->
 
===Comparing PDM and PWM===
 
<!--
 
PWM and PDM are often compared, because at lower level they are very similar approaches:
: made of signals being on or off
: typically run at fixed speed
: levels of signal are represented by longer-term average
 
 
In fact, PWM can be considered a specific case of PDM  (PWM also happens to be easier to implement).
And the choice can depend on context.
 
 
One major difference is that
: PWM places all highs next to each other, and lows next to each other, while
: PDM aims for the same high/low average but as fast as possible.
 
e.g. A 10Hz, 50% duty cycle output
: in PWM will be on,on,on,on,on, off,off,off,off,off
: in PDM  may be on,off,on,off,on,off,on,off,on,off
 
 
 
Comparison gets a little confusing,
because there are distinct reasons to go for one or the other, that vary with context.
 
For example, PWM may be a little more sensible when you have a microcontroller,
PDM is theoretically better at representing analog levels at the same switching speed,
though as FET switches generate some heat PWM can be preferable.
 
And none of those are directly relevant to why PDM microphones are a neat idea.
 
 
Let's go through some examples.
 
PWM is an easy concept if you have a duty cycle as a number
: because the core of PWM is a (regular-clocked) counter and a comparator
:: also why it's almost as simple to do in code if there's no PWM hardware
: But PWM counts on some sort of smoothing
:: In LED strings, we're counting on your eyes's [https://en.wikipedia.org/wiki/Flicker_fusion_threshold flicker fusion threshold]
:: in applications like audio-rate signals, we count on a lowpass
 
 
 
'''PDM microphones''' (transducer, ADC, and PDM transducer) are ''not'' intended to have their signal interpreted as analog (even though that would produce sound).
 
This amounts to getting a data line and a clock line (that runs ''much'' faster than audio rates, it seems an oversampling factor of 64 is common),
and basically just counting how it's in high state.
 
Because each constituent data state is received as boolean high or low, you effectively get immunity from induced noise (until it's strong enough to alter those states).
 
 
 
As to '''why PDM at the same rate can be better than PWM''', there's a good analogy in images: it's similar to the difference between a paletted image without and with dithering[https://en.wikipedia.org/wiki/Dither#Examples_2].
 
You're using the same levels, but from a distance / when you squint (~=lowpass) the dithered version looks like a better approximation.
 
 
 
So why don't microcontrollers have PDM hardware instead of PWM?
 
Because when they do, it's usually called a delta-sigma DAC, a.k.a. an 1-bit DAC.
 
{{comment|(And note that oversampling within DACs and ADCs, which is now common, ''is'' a form of PDM)}}
 
 
 
 
 
It gets more interesting when trying to use both to approximate a waveform.
 
Bit-banging PDM from a microcontroller, for analog consumption, can give smoother output than (particularly bit-banging) PWM, but only makes sense when you can basically dedicate its CPU{{verify}}.
 
That said, it makes more sense for audio than for other signals, because the lowpass involved is by definition a delay.
 
 
https://hackaday.io/project/6356-delta-sigma-versus-pwm
 
https://users.ece.utexas.edu/~bevans/courses/rtdsp/lectures/10_Data_Conversion/AP_Understanding_PDM_Digital_Audio.pdf
 
 
-->
 
===Combining PWM or PDM outputs for bit depth===
<!--
 
tl;dr: can be done. May or may not be worth it in practice.
 
Also, some other pulse output methods can be
 
 
 
When you control distinct PWM channels from the same source,
then you could combine them for more precision than each individual pin has.
 
This means voltage-dividing them down to take care of smaller detail.
 
 
If you just average the two signals as-is, you basically get 1 bit more resolution.
 
 
If you e.g. have an arduino so basically 8-bit PWM, and divide one by 256 (see e.g. Mozzi's HIFI mode), then you theoretically get 16 bits, but you shouldn't assume you'd get all that precision, for a handful of reasons (not least of which distortions).
 
Another practical issue is that the higher the resistor ratio you need,
the more you need resistors of increasingly disparate ''and'' precise values (in fact, a ratio of 256 is already starting to push the boundaries of resistor specs - ''if'' you care about precision), and increasing sensitivity to resistors all being temperature-varying to some degree.
 
 
You can divide by less - basically every factor of two gets you an extra bit,
and it can be more manageable.
 
In fact, due to the way PWM works (counting), spreading a target amount of bits to multiple pieces of PWM hardware (and assuming a fixed clock) means each needs to count to less, meaning you might configure it for higher frequencies at the same clock. Though two or three is usually the maximum.
 
 
 
This lowers noise floor somewhat,
and lowers some types of distortion but not e.g. distortion, and the PWM carrier may well be introducing noise (e.g. from its carrier) that you want to filter away, and by the time you're adding a second-order active filter, you have to ask yourself why.
 
 
So it's not very simple or efficient,
or as effective as getting a finer PWM, or better yet, a DAC,
but it's interesting whenever an IC or [[uC]] has unused PWM outputs.
 
 
 
 
One practical analysis is at:
* http://www.openmusiclabs.com/learning/digital/pwm-dac/dual-pwm-circuits/
 
Also potentially relevant:
* https://www.edn.com/combine-two-8-bit-outputs-to-make-one-16-bit-dac/
* http://wiki.openmusiclabs.com/wiki/PWMDAC
* http://www.openmusiclabs.com/learning/digital/pwm-dac/pwm-distortion-analysis/
 
-->
 
 
 
=Modulating data to send: ASK, FSK, PSK=
 
<!--
'''Frequency-shift keying''' (FSK) uses distinct frequencies.
 
The simplest form of FSK is binary FSK (BFSK, 2FSK),
 
-->
 
https://en.wikipedia.org/wiki/Amplitude-shift_keying
 
https://en.wikipedia.org/wiki/Frequency-shift_keying
 
https://en.wikipedia.org/wiki/Phase-shift_keying

Latest revision as of 16:27, 26 April 2024

⚠ This is for beginners and very much by a beginner / hobbyist

It's intended to get an intuitive overview for hobbyist needs. It may get you started, but to be able to do anything remotely clever, follow a proper course or read a good book.


Some basics and reference: Volts, amps, energy, power · batteries · resistors · transistors · fuses · diodes · capacitors · inductors and transformers · ground

Slightly less basic: amplifier notes · varistors · changing voltage · baluns · frequency generation · Transmission lines · skin effect


And some more applied stuff:

IO: Input and output pins · wired local IO · wired local-ish IO · ·  Various wireless · 802.11 (WiFi) · cell phone

Sensors: General sensor notes, voltage and current sensing · Knobs and dials · Pressure sensing · Temperature sensing · humidity sensing · Light sensing · Movement sensing · Capacitive sensing · Touch screen notes

Actuators: General actuator notes, circuit protection · Motors and servos · Solenoids

Noise stuff: Stray signals and noise · sound-related noise names · electronic non-coupled noise names · electronic coupled noise · ground loop · strategies to avoid coupled noise · Sampling, reproduction, and transmission distortions

Audio notes: See avnotes


Platform specific

Arduino and AVR notes · (Ethernet)
Microcontroller and computer platforms ··· ESP series notes · STM32 series notes


Less sorted: Ground · device voltage and impedance (+ audio-specific) · electricity and humans · power supply considerations · Common terms, useful basics, soldering · landline phones · pulse modulation · signal reflection · Project boxes · resource metering · SDR · PLL · vacuum tubes · Multimeter notes Unsorted stuff

Some stuff I've messed with: Avrusb500v2 · GPS · Hilo GPRS · JY-MCU · DMX · Thermal printer ·

See also Category:Electronics.

Most broadly, pulse modulation refers to modulating or communicating or approximating a signal in a way involving pulse trains.

Note also that PAM resembles AM, PPM resembles PM, and PWM (moderately) resembles FM.

(Also, some of these parts run into analog and digital (passband) modulation, and for decent handling of said topics you're much better off on serious sites for those.)


Purposes and best uses are varied.


Side note: Pulse Code Modulation

Pulse-code modulation refers more widely to the idea of samples at at regular (uniform) intervals, and storing them as distinct values.

It that we're quantizing in time and amplitude, roughly how to store, and what it represents.

...and is not a reproduction technique, like most of this page. (reproduction was a separate thing even in the earliest development of these concepts)


Variants include:

Unqualified PCM usually means

quantization levels are linearly uniform (so ratiometric) with amplitude
...physical amplitude, so not with perceived loudness
used for sound, it means most of the bits are used on really quiet stuff (because human perception is logarithmic).
which is actually quite useful (for human consumption of audio)
also why 8-bit PCM is audibly not enough, and 16-bit is (for most things)
probably easiest raw format to deal with (particularly when storage/bandwidth are not an issue)
Directly used in Audio CDs (Red Book), in WAV files, and quite a few others.
Also used in some way or other in a number sound- or music-related electronics, although note that mu-law and a-law are seen in some older hardware


logarithmic PCM

Because of the nonlinear way we hear loudness, and given a fixed, limited bandwidth, people at different volume levels get similar signal-to-quantizing noise ratio - than linear PCM(verify)
since the original input and eventual reproduction is often LPCM (it's a choice most hardware makes), this is often used to effectively compand signal while in transmission/storage
implementations include μ-law (mu-law) and A-law
which historically implied 8-bit and often 8000Hz implementations, as used in early digital phone transmissions (see e.g. ITU-T G.711)
if storage is not a hard constraint (and harder than CPU use), then linear PCM is easier and log PCM is probably more work than it's worth
u-law and a-law are quoted as roughly comparable to the quality of 12-bit linear PCM (in what regard?(verify))
(even though technically 16-bit logarithmic still give better detail than linear 16-bit(verify), you generally don't need it)


Differential PCM

says that instead of storing the absolute values, we store the difference from the last, or to a (deterministically) predicted next value.
If the prediction is reasonable, we need to send fewer bits.
This is generally a smaller number, so allows a slight reduction in storage, but not much



ADPCM is Adaptive Differential PCM.

It takes the differential PCM output, and varies the amount of quantization of it over time.

This is a lossy format that allows you to tweak bandwidth/SNR on noisy / low bandwidth channels.

often 5-, 4-, or 3-bit


SB-ADPCM: ADPCM, but applied to distinct frequency sub-bands.

For example, G.722
splits into two bands (roughly 0Hz to 4kHz, and 4kHz to 8kHz), then applies ADPCM to each
This mainly so that you can spend bits differently, e.g. 48 of the 64 kbit/s on the lower sub-band that includes most voice energy, and 16 kbit/s on the rest. (G.722 actually has a few different target bitrates)



Even when storage/transmission is mu-law/A-law or ADPCM or some other codec, processing on endpoints is often LPCM, mostly because it's easier and faster to work with.


For context on companding: linear PCM is not clever about spreading quantization to where our (approximately logarithmic) perception hears it best. Companding basically rescales (in a reversible way) to reduce that issue.

The companding step is lossy, but since the signal to noise ratio is better than linear PCM in the same amount of bits, it provides quality improvements - and rather useful whenever you are bandwidth-limited.


Both μ-law and A-law are used in analog and digital telecommunication (in analog it was mostly for quality, in digital tranfer it was also handy for compression), in different countries.

The .au sound format uses μ-law.



See also:



See also:

-->

Continuous wave modulation

Amplitude Modulation (AM)

Frequency Modulation (FM)

Phase Modulation (PM)

Related: Dimming practicalities

Pulse modulation

Pulse Amplitude Modulation (PAM)

Pulse Skip Modulation (PSM)

Pulse Position Modulation (PPM)

Pulse Density Modulation (PDM), Delta-Sigma modulation (ΔΣM)

Practical notes

PWM Types

PWM for average energy

Hardware PWM, software PWM, and inbetween

PWM or PDM as a simple DAC

Sound PWM

On PWM resolution

On PWM distortion

On PWM oversampling

Unsorted

On PWM filtering

PWM IC notes

TLC5940

PCA9685

Comparing PDM and PWM

Combining PWM or PDM outputs for bit depth

Modulating data to send: ASK, FSK, PSK

https://en.wikipedia.org/wiki/Amplitude-shift_keying

https://en.wikipedia.org/wiki/Frequency-shift_keying

https://en.wikipedia.org/wiki/Phase-shift_keying