can you describe what the code is intended to do? what does it control?
The code is supposed to make a three phase sinewave with PWM to drive a motor
What is the expected frequency range of the output?
Then you should definitely consider @J-M-L's advice in Post #20 to use MCPWM. If you don't need the wireless capabilities of ESP32, there's also the boards in the Teensy Family. Their processors also have dedicated motor control hardware, including provision for dead time.
instead of running asynchronously, can it be run periodically so that the sin/amplitude values can be precomputed in a table once when a new parameter is entered?
PWM: 10kHz, sinewave: up to 500Hz (going to such extents is impractical)
My code does precompute the sinetable. 360 values of it.
based on the frequency parameter, why not determine a reasonable sample rate and pre-compute the amplitude values. Each loop cycle waits the appropriate time and simply advances thru the table at three points.
On RISCV?? It's got a "REM" instruction for calculating remainders (and the compiler uses it.)
Make sure you're not unncessarilly doing double-precision math...
Maybe:
casvlny = 1000000.0F / (float)frekvenciavlny;
caspolvlny = (float)casvlny / 2.0F;
casvovlne = fmodf(cas, casvlny);
(Hmm. The expressions with constants look OK, but using fmod() definitely causes conversions in each direction.)
4200031c: 6ec080e7 jalr 1772(ra) # 40000a04 <__extendsfdf2>
42000320: 14842603 lw a2,328(s0) # 42030148 <_flash_rodata_start+0x28>
42000324: 14c42683 lw a3,332(s0)
42000328: 18b1b0ef jal ra,4201bcb2 <fmod>
phi = fmod(phi, 360.0);
4200032c: fe000097 auipc ra,0xfe000
42000330: 750080e7 jalr 1872(ra) # 40000a7c <__truncdfsf2>
42000334: 82a1a223 sw a0,-2012(gp) # 4080c828 <phi>
uhol = int(phi);
42000338: fe000097 auipc ra,0xfe000
4200033c: 6dc080e7 jalr 1756(ra) # 40000a14 <__fixsfsi>
Some functions might be slower than you'd have reason to expect. For example, it looks like Serial.available() does some a mutex, and can invoke timestamp logging, under some circumstancs (that I'm too lazy to look into further.)
4201039c <uart_get_buffered_data_len>:
4201039c: 1141 addi sp,sp,-16
4201039e: c606 sw ra,12(sp)
420103a0: c422 sw s0,8(sp)
420103a2: c226 sw s1,4(sp)
420103a4: 4789 li a5,2
420103a6: 04a7f263 bgeu a5,a0,420103ea <uart_get_buffered_data_len+0x4e>
420103aa: fe7fa097 auipc ra,0xfe7fa
420103ae: fc0080e7 jalr -64(ra) # 4080a36a <esp_log_timestamp>
420103b2: 4203c7b7 lui a5,0x4203c
420103b6: 420365b7 lui a1,0x42036
420103ba: 42036637 lui a2,0x42036
420103be: 86aa mv a3,a0
420103c0: 6a900813 li a6,1705
420103c4: a4c78793 addi a5,a5,-1460 # 4203ba4c <__FUNCTION__.35>
420103c8: 10458713 addi a4,a1,260 # 42036104 <_flash_rodata_start+0x5fe4>
420103cc: 10c60613 addi a2,a2,268 # 4203610c <_flash_rodata_start+0x5fec>
420103d0: 4505 li a0,1
420103d2: 10458593 addi a1,a1,260
420103d6: fe7fa097 auipc ra,0xfe7fa
420103da: e8c080e7 jalr -372(ra) # 4080a262 <esp_log>
420103de: 557d li a0,-1
420103e0: 40b2 lw ra,12(sp)
420103e2: 4422 lw s0,8(sp)
420103e4: 4492 lw s1,4(sp)
420103e6: 0141 addi sp,sp,16
420103e8: 8082 ret
420103ea: 40810437 lui s0,0x40810
420103ee: 050a slli a0,a0,0x2
in fact you can precompute a 360 element amplitude table either pre-compile or at startup and based on run-time parameter determine the sample rate and step-size thru the table
the table should be a multiple of 3. use 3 indices, 1/3 the table size apart.
at higher freqencies the step-size thru the table may be greater than 1 (even fractional)
run-time computations is just incrementing each index by the step-size and extracting the amplitudes from the table
optimizing the architecture grossly exceeds the impact of optimizing code
I had looked at how long it took, on an WEMOS D1 R32 clone running at 240MHz clock speed, Serial.available() took 6uS to 7uS. The calculations in the original code took 2uS to 3uS, the analogwrite()'s around 30uS total for all six. The commented out analogRead() is quite slow, around 40uS. All measurements were made by recording the value of micros() before and after the code in question and printing the difference.
The ESP analogWrite() uses LEDC
Sure indeed - analogWrite() does use LEDC underneath, so there is no fundamental performance gain in terms of PWM generation itself. The signal is produced by the same hardware either way.
The question was about optimization and the difference is control and overhead. analogWrite() is a convenience wrapper that reconfigures the channel implicitly, chooses default frequency and resolution, and perform extra checks on each call. This introduces a small overhead that adds up if you call it very frequently inside a tight loop / for many channels.
Using LEDC directly lets you configure the timer once and then only update the duty cycle. In that case the call path is shorter, and you avoid unintended reconfiguration.
That was the “optimization” idea with LedC.
Writing directly against ESP IDF and using MCPWM is probably the right way to go but seemed ignored by OP so I moved on.
There is no speed advantage between a 16-bit computation and a 32-bit computation on a 32-bit processor (which the ESP32 is)
So it's better to use 4 byte variables, even when it wastes memory?
I'll try to use LEDC directly and see the performance gains
here's a script the simulates the behavior on the Arduino i.e. computes a new step-size for each freq and uses 3 indices: i, j, k to extract values for a precomputed table
the following plots show waveforms at ~250 Hz
i counted ~35,000 iterations of loop/sec with some minor timing code and 3 calls to analogWrite(). So i assume loop() can be invoked 20,000/sec and for this to work must be invoked at that rate
# gradually increasing sinsoid
awk '
function plot (vec, N, col) {
printf "color = %s\n", col
printf "next\n"
for (n = 0; n < N; n++)
printf " %8d %8.4f\n", n,vec [n]
}
# ----------------------------------------------------------
function loop (n) {
if (! (n % (Ips/5))) {
freq *= 1.2
if (500 <= freq)
exit
step = freq / (Ips/TblN)
printf "# loop: n %4d, freq %6.2f, step %.2f\n", n, freq, step
}
phA [n] = tbl [int(i) %TblN]; i += step
phB [n] = tbl [int(j) %TblN]; j += step
phC [n] = tbl [int(k) %TblN]; k += step
}
# ----------------------------------------------------------
function setup () {
TblN = 360
for (n = 0; n < TblN; n++)
tbl [n] = sin(2*Pi *n/TblN)
Ips = 20000 # kHz
freq = 100
i = 0
j = TblN /3
k = 2*j
}
# ----------------------------------------------------------
BEGIN {
Pi = atan2(0, -1)
setup()
N = Ips
for (n = 0; n < N; n++)
loop(n)
exit
}
END {
dump()
}
# ----------------------------------------------------------
function dump () {
plot(phA, N, "red")
plot(phB, N, "yellow")
plot(phC, N, "green")
}' | tee 3ph.xgr
# ----------------------------------------------------------
function loop (n) {
if (! (n % (Ips/5))) {
freq *= 1.2
if (500 <= freq)
exit
step = freq / (Ips/TblN)
printf "# loop: n %4d, freq %6.2f, step %.2f\n", n, freq, step
}
phA [n] = tbl [int(i) %TblN]; i += step
phB [n] = tbl [int(j) %TblN]; j += step
phC [n] = tbl [int(k) %TblN]; k += step
}
# ----------------------------------------------------------
function setup () {
TblN = 360
for (n = 0; n < TblN; n++)
tbl [n] = sin(2*Pi *n/TblN)
Ips = 20000 # kHz
freq = 100
i = 0
j = TblN /3
k = 2*j
}
# ----------------------------------------------------------
BEGIN {
Pi = atan2(0, -1)
setup()
N = Ips
for (n = 0; n < N; n++)
loop(n)
exit
}
END {
dump()
}
# ----------------------------------------------------------
function dump () {
plot(phA, N, "red")
plot(phB, N, "yellow")
plot(phC, N, "green")
}' | tee 3ph.xgr
You can optimize for memory OR speed. Or some arbitrary mix of those.
Esp has quite some memory available... so indeed: use lookup tables as already suggested.
You chose speed as optimization target. As esp32 is a 32 bit processor, it might well be faster with 32 bit data (4 byte) than with 16 bit data.
You can also use the datatype int_fast16_t.
The compiler will implement it as int32_t if that will lead to faster code.
Verdict: If I wanna also have knobs and buttons to control it, it's better to just get a way faster microcontroller.
