microbit-foundation / micropython-microbit-v2

Temporary home for MicroPython for micro:bit v2 as we stablise it before pushing upstream
MIT License
42 stars 23 forks source link

music.pitch seems to cause fluctuations in read_analog results #66

Closed AndyLindsay closed 3 years ago

AndyLindsay commented 3 years ago

A call to music.pitch seems to affect the results of the next read_analog call.

Edit: The symptoms are evident with or without a sleep call between music.pitch and pin0.read_analog.

Test Script

# music_pitch_v_read_analog
# connect pin0 to 3.3 V

from microbit import *
import music

n = 0

while True:
    n += 1
    if (n%5) == 0:
        print("beep")
        music.pitch(3000, 100)
    #sleep(100)
    v0 = pin0.read_analog()
    print("v0 =", v0)
    if v0 < 1010:
        print("pin0 measurement error")
        sleep(2000)
    sleep(100)

Terminal Results

v0 = 1020 v0 = 1021 v0 = 1021 v0 = 1020 beep v0 = 958 pin0 measurement error v0 = 1021 v0 = 1021 v0 = 1020 v0 = 1021 beep v0 = 957 pin0 measurement error v0 = 1021 v0 = 1021 v0 = 1021 v0 = 1021 beep v0 = 957 pin0 measurement error v0 = 1021 v0 = 1021 v0 = 1021 v0 = 1021 beep v0 = 957

dpgeorge commented 3 years ago

Is this related to #65?

dpgeorge commented 3 years ago

I can reproduce the issue as described above using the above code.

Simpler code to show the problem:

# connect pin0 to 3V
for i in range(10):
    if i == 5:
        music.pitch(3000, 100)
    print(pin0.read_analog())

I also wrote the equivalent code in pure C++:

int main() {
    uBit.init();

    for (int count = 0; count < 10; ++count) { 
        if (count == 5) { 
            uBit.audio.virtualOutputPin.setAnalogPeriodUs(1000000 / 3000);
            system_timer_wait_us(100000);
            uBit.audio.virtualOutputPin.setAnalogValue(0);
        } 
        uBit.serial.printf("%d\r\n", uBit.io.P0.getAnalogValue());
    } 

    return 0;
}

The same issue exists with the above C++ code (analog read after the virtual pin output is about 5% lower than it should be).

So this looks like a CODAL issue (or hardware limitation?).

microbit-carlos commented 3 years ago

Thank you Damien and @martinwork, and thank you @AndyLindsay for the report! I can confirm this is fixed in the latest builds from the CI., both the original script and the minimal from the previous comment now always output 1023 while it beeps.

Likely fixed in the latest CODAL added in 291e05c8440de4e90dcf1f443136d2b7005272a1.

The fix will be present in the next MicroPython release, in the meantime a hex can be downloaded from the CI artefacts in https://github.com/microbit-foundation/micropython-microbit-v2/actions/runs/887027270.