Page 1 of 1

Converting C++ to MicroPython for a Raspberry Pico Project

Posted: Thu Mar 11, 2021 7:13 pm
by ChipNod2020
Greetings all,

I have a working C++ Script. I'm not 100% fluent with Python yet so I'm hoping someone could take pity on me and help.

This is the working C++ Script.

Code: Select all

// NAV - Navitgation Light Prefix
#define NAV_LED_PIN 2
// Navigation Lights
#define NAV_LED_ON 150    
#define NAV_LED_OFF 1000
unsigned long NAV_msLast;  // last time the LED changed state
boolean NAV_ledState;    // current LED state
pinMode(NAV_LED_PIN, OUTPUT);


LOOP:
// Normal Stuff
now = millis();
// Navigation Lights
if (now - NAV_msLast > (NAV_ledState ? NAV_LED_ON : NAV_LED_OFF)) {
digitalWrite(NAV_LED_PIN, NAV_ledState = !NAV_ledState);
NAV_msLast = now;
My 2 questions.
How would I initialize the boolean string for NAV_ledState?
Is the if statement syntax similar and how would one toggle the LED other than digital write?

Re: Converting C++ to MicroPython for a Raspberry Pico Project

Posted: Fri Mar 12, 2021 6:52 am
by OlivierLenoir
You can do something like this using sleep_ms().

Code: Select all

from machine import Pin
from utime import sleep_ms

NAV_LED_PIN = const(2)
NAV_LED_ON = const(150)
NAV_LED_OFF = const(1000)

led = Pin(NAV_LED_PIN, Pin.OUT)

while True:
    led(not(led()))
    if led():
        delay = NAV_LED_ON
    else:
        delay = NAV_LED_OFF
    sleep_ms(delay)

Re: Converting C++ to MicroPython for a Raspberry Pico Project

Posted: Fri Mar 12, 2021 7:10 am
by OlivierLenoir
This version is a lot closer to your C++ code and use ticks_ms() and ticks_diff().

Code: Select all

from machine import Pin
from utime import ticks_ms, ticks_diff

NAV_LED_PIN = const(2)
NAV_LED_ON = const(150)
NAV_LED_OFF = const(1000)

NAV_msLast = ticks_ms()
led = Pin(NAV_LED_PIN, Pin.OUT)

while True:
    now = ticks_ms()
    if ticks_diff(now, NAV_msLast) > (NAV_LED_ON if led() else NAV_LED_OFF):
        led(not(led()))
        NAV_msLast = now

Re: Converting C++ to MicroPython for a Raspberry Pico Project

Posted: Fri Mar 12, 2021 7:12 am
by Roberthh
There is also a supported ternary statement, which is a littel bit different to C. It would read:

Code: Select all

    delay = NAV_LED_ON if led() else NAV_LED_OFF

Re: Converting C++ to MicroPython for a Raspberry Pico Project

Posted: Fri Mar 12, 2021 8:36 am
by OlivierLenoir
Considering Roberthh post, we can also remove delay.

Code: Select all

from machine import Pin
from utime import sleep_ms

NAV_LED_PIN = const(2)
NAV_LED_ON = const(150)
NAV_LED_OFF = const(1000)

led = Pin(NAV_LED_PIN, Pin.OUT)

while True:
    led(not(led()))
    sleep_ms(NAV_LED_ON if led() else NAV_LED_OFF)
An other approach to use a tuple.

Code: Select all

from machine import Pin
from utime import sleep_ms

NAV_LED_PIN = const(2)
NAV_LED_OFF_ON = (1000, 150)

led = Pin(NAV_LED_PIN, Pin.OUT)

while True:
    led(not(led()))
    sleep_ms(NAV_LED_OFF_ON[led()])