bbcmicrobit / micropython

Port of MicroPython for the BBC micro:bit
https://microbit-micropython.readthedocs.io
Other
603 stars 284 forks source link

Analog Pins don't correctly switch to Digital #665

Open 4tronix opened 5 years ago

4tronix commented 5 years ago

We're using 4 pins to control 2 dc motors, 2 pins for each motor. PWM on one pin or the other depending on direction. The other pin is set to a 0 (write_digital). To coast to a stop, set both pins to 0 - this always works regardless of analog or digital. To use regenerative braking, set both pins to 1 - this goes wrong if use write_digital and only works by using write_analog with 1023 for PWM.

The following complete program "should" work I think to set both pins to high after driving the motors forward with PWM value of 600. However, instead of the motors stopping, they start moving backwards slowly. If the "write_digital(1) are replaced with "wire_analog(1023)" then it all works as it should.

from microbit import * pin12.write_analog(600) pin8.write_digital(0) pin16.write_analog(600) pin14.write_digital(0) sleep(2000) pin12.write_digital(1) pin8.write_digital(1) pin16.write_digital(1) pin14.write_digital(1)

dpgeorge commented 5 years ago

Can you please state the version of firmware that shows the issue, eg the output of os.uname().

4tronix commented 5 years ago

Using mu version 1.0.2

os.uname() (sysname='microbit', nodename='microbit', release='1.0.1', version='micro:bit v1.0.1+b0bf4a9 on 2018-12-13; MicroPython v1.9.2-34-gd64154c73 on 2017-09-01', machine='micro:bit with nRF51822')

Also, only one pair of pins is required to show the issue. This code fails in the same way: from microbit import * pin12.write_analog(600) pin8.write_digital(0) sleep(2000) pin12.write_digital(1) pin8.write_digital(1)

4tronix commented 5 years ago

And, just to complete the issue, the following code with the write_analog replaced with a write_digital stops correctly after 2 seconds. This shows the hardware works as epected. from microbit import * pin12.write_digital(1) pin8.write_digital(0) sleep(2000) pin12.write_digital(1) pin8.write_digital(1)

dpgeorge commented 5 years ago

Thanks for the further info.

I didn't test it out but I suspect the issue is that once a pin goes into analog mode it's staying in analog mode even if it has a write_digital applied to it. The PWM driver runs in the background and keeps outputing the analog signal.

Does it work if you set the analog value to 0 before doing the digital write, like:

from microbit import *
pin12.write_analog(600)
pin8.write_digital(0)
sleep(2000)
pin12.write_analog(0) # add this
pin12.write_digital(1)
pin8.write_digital(1)
4tronix commented 5 years ago

Yes "PWM dirver ... keeps outputing the analog signal" I think you've hit the problem on the head. Making the suggested change does indeed fix it. I'll use this as the preferred workaround until it is fixed in the code. Thanks alot.