It's šŸCircuitPython MondayšŸ at Adafruit! Use the code ADATY to get 20% off CircuitPython and 15% off items storewide!
0

Arduino to Circuitpython code conversion
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Arduino to Circuitpython code conversion

by Daft_vagabond on Thu Oct 14, 2021 9:52 am

I'm porting some code from my Arduino nano to an itsy bitsy M0 express and I'm hoping I could get some opinions on the conversion. I'd also like to know if there might be a better and/or more pythonic way to achieve the same thing. There are a few pieces to this project but I'm going to try to only focus on three of them for now. One is a small device that's sending out a PWM signal, the other is the M0, which I'd like to receive the signal. The last one is a small vibration motor. Now, I've already tested all of this on the nano, so this is mostly just a review of the code. My wiring is similar to this diagram except my power and ground are directly from he power supply, and not either of the boards.

https://techzeero.com/wp-content/upload ... rduino.png

I use pulseIn to read the time between highs and lows and use those numbers to drive the motor at different speeds. I'm making the motor behave differently depending on what the pwm is doing, it'll also react to being turned on from on idle state, or where I'm blocking PWM from being sent. The on/off blocking isn't shown here, but there's a switch involved, though during testing I just controlled this from my PC via USB so this specific thing isn't referenced in the code. With that out of the way, here's the Arduino code:

Code: Select all | TOGGLE FULL SIZE
byte PWM_PIN = 6;  //PWM is coming in here
int motor = 10;    //motor is on PWM pin 10
int pulse;         //Variable used to represent to the time in millis from pulsein
int highmode;      //Boolean variable that allows access to parts of code if (true)
int pwm0_loopcount = -2;    //Stores the number of loops when pulsein reads 0, helps prevent unintentional shut off
int high_mode_loop_count = -1; //Stores the number of loops when in Highmode. Helps prevent vibration from going into low-mode too soon. I also tried hysteresis but I found I liked how this behaved better
int LMsafetyLoops = - 3;    //Stores the number of loops when in low-mode. Prevents code form getting stuck in low-mode when it shouldn't be, and allows loop to re-enter low-mode when appropriate



void setup() {
  TCCR1B = TCCR1B & B11111000 | B00000101; // for PWM frequency of 30.64 Hz. I like how jerky/violent this made the motor feel, that's the only reason for the 30Hz frequency
  pinMode(PWM_PIN, INPUT);                 //PWM_PIN is an input
  pinMode(motor, OUTPUT);                  //motor is an output
  Serial.begin(115200);                    //Another part of this build (not featured here) is interfacing with this via UART(code for that also not featured here) and it's baud rate is 115200
}
void loop() {

  pulse = pulseIn(PWM_PIN, HIGH, 100);     //Setting up a local variable, though this might also function just as well as a global variable.

  while (pulse == 0)                                        //while incoming millis equal 0
  {
    pwm0_loopcount++;                                 //increment the loopcount for consecutive 0s. This is used as a check to prevent other parts of the code from running
    delay (5);                                                    //delay for a bit. This is so that the stacking loop counts don't increment too quickly, thus bypassing this gate
    pulse = pulseIn(PWM_PIN, HIGH, 100);   // check the incoming PWM in millis
    if ((pwm0_loopcount >= 50) || (pulse <= 1)) {  //First part of a gate. This part prevents progress if the loop got here just after coming from low or high-mode since the PWM in millis often dips down to 0 for a moment even while its not specifically in an "off" state
      analogWrite (motor, 0);                      //turns motor off since it would have needed to loop through the previous section 50 consecutive times in order to get here. Ensures it's actually off
      if (pulse >= 1) {                            //Check if the PWM in millis is above 0. A *special* motor animation plays when starting it from "off" state. This check, combined with the previous ones, makes sure that this animation ONLY plays when waking up from an "off" state
        analogWrite (motor, 235);                  //Motor goes fast
        delay (500);                               //holds for a bit
        analogWrite (motor, 40);                   //Motor goes slower
        delay (1000);                              //holds for a bit
        pwm0_loopcount = 0;                        //Resets the loop count for consecutive 0s.
        pulse = pulseIn(PWM_PIN, HIGH, 100);       //updates the current reading of PWM in millis
        break;                                     //Moves on to low-mode
      }
      else {
        continue;          //if it failed to start or move on, it restarts
      }
    }
    else {
      continue;            //if it failed to start or move on, it restarts
    }
  }
  while ((pulse >= 1) || (pwm0_loopcount == 0))  //when looping through low-mode, it'll check these two variables first.
  {
Low_mode:                                    //A label to jump to(not needed but it's still here from when I was testing things.
    pwm0_loopcount = 0;               //reassures that the loop count for consecutive 0s is reset upon every loop
    pulse = pulseIn(PWM_PIN, HIGH, 100);      //updates the current reading of PWM in millis
    if (pulse >= 20) {                        //If pulse value is high enough, it'll begin high-mode right away(high mode just takes all the pulse signals and does the same thing with them as this part of the code, only more exaggerated
      highmode = true;                        //A boolean value that acts as a key to prevent high-mode form happening when it's not appropriate
      goto High_mode;                         //Send loop to high-mode loop. Again, not needed but it's still here form testing
    }
    else {
      highmode = false;                      //Sets the highmode boolean to false. Both of these help to prevent high-mode form happening when it's not appropriate
      high_mode_loop_count = 0;             //Sets the highmode loop count to 0. Both of these help to prevent high-mode form happening when it's not appropriate
      if (pulse >= 2 && pulse <= 4) {      //These next 3 "if" sections all check the pulse value from the beginning of the low-mode loop and apply  different speeds depending on that value
        analogWrite (motor, 20);
      }
      if (pulse >= 5 && pulse <= 8) {
        analogWrite (motor, 25);
      }
      if (pulse >= 9 && pulse <= 19) {
        analogWrite (motor, 35);
      }
      if (pulse == 0) {                   //Checks to see if the pulse is 0
        LMsafetyLoops++;                  //if so, increment the count for those by 1
        delay (5);                        //a slight delay to prevent these from counting up too quickly
      }
      if (LMsafetyLoops >= 15) {          //if too many 0s in a row occur
        break;                            //break from here, sending loop back to the previous section, since it won't be allowed into the next section, where it will likely determine the pulse to be in an "off" state
      }
    }
  }

  while (highmode == true)        //Checks to see if highmode is true, if so, it'll continue through this loop
  {
High_mode:                       //not needed anymore, a label to jump to
    high_mode_loop_count++;      //increments the count for consecutive highmode loops
    highmode = true;             //makes sure that high mode remains true for each consecutive highmode loop
    pwm0_loopcount = 0;          //another measure to prevent an accidental "off" state
    pulse = pulseIn(PWM_PIN, HIGH, 100);            //just like before, but a tiny bit different. The pulse value is updated and the motors activated at certain speeds accordingly. Occasional delays to exaggerate the durations of the vibrations a bit
    if (pulse >= 0 && pulse <= 17) {
      analogWrite (motor, 40);
      pulse = pulseIn(PWM_PIN, HIGH, 100);
    }
    if (pulse >= 18 && pulse <= 20) {
      analogWrite (motor, 175);
      delay (300);
      analogWrite (motor, 40);
      delay (200);
      pulse = pulseIn(PWM_PIN, HIGH, 100);
    }
    if (pulse >= 21 && pulse <= 26) {
      analogWrite (motor, 220);
      delay (300);
      analogWrite (motor, 40);
      delay (200);
      pulse = pulseIn(PWM_PIN, HIGH, 100);
    }
    if (high_mode_loop_count >= 15) {           //once the high-mode has looped a certain number of times, it goes back to low mode. This ensures that when it goes high, it stays there long enough to get the effect I want
      goto Low_mode;
    }
  }
}


I'm a lot less familiar with circuitpython so a lot of this could be off or inefficient. but here's the code:

Code: Select all | TOGGLE FULL SIZE
import time
import board
import busio
import baudrate
import serial
import pulseio

pwm0_loopcount = -2              ##all the same variables
high_mode_loop_count = -1
l_m_safety_loops = - 3

serial.set_baud_rate(baudrate.BAUD_RATE115200)                 ##I'm pretty sure this is the way to change the baud rate on the M0 express
uart = busio.UART(board.TX, board.RX, baudrate=115200)

pulse = pulseio.PulseIn(board.D9, maxlen=1, idle_state=False)         ##this seemed to be the equivalent function to Arduino's pulseIn

motor_pwm = pulseio.PWMOut(board.D10, duty_cycle=2 ** 15, frequency=30)       ##I didn't really think I needed to use a motor library because I'm really just sending out a PWM to a transistor

while True:                   ##infinite loop
    while pulse == 0:
        pwm0_loopcount += 1              ##the increment
        time.sleep(.005)                        ##the delay
        if pwm0_loopcount >= 50 or pulse <= 1:
            motor_pwm.duty_cycle = 0
            if pulse >= 1:
                motor_pwm.duty_cycle = 60395           ##for the duty cycle numbers, I just took 65535, the max value I can use here, representing always-on, and divided it by 255, the max number I could have used in my Arduino code. 65535/255=257, So I took each PWM output value from the Arduino code and multiplied it by 257, so 235X257=60395. I don't know if this was the correct thing to do, but it made sense to me.
                time.sleep(.500)
                motor_pwm.duty_cycle = 10280
                time.sleep(1)
                pwm0_loopcount = 0
                break
            else:
                continue
        else:
            continue     ##again, these keep the code looping down here during a confirmed "off" state
    while pulse >= 1 or pwm0_loopcount == 0:            ##lowmode begins
        pwm0_loopcount = 0
        if pulse >= 20:                                                      ##my assumption is that circuitpython will just check the pulse whenever it's called upon, whereas in Arduino I had to call it just before it was checked in order to update the value. So you'll see all of the normal pulseIn reads removed.
            highmode = True
            break                                                                                   ##this SHOULD break it out of lowmode and send it to highmode by default, as its the next part of the code after this
        else:
            highmode = False
            high_mode_loop_count = 0
            if pulse >= 2 and pulse <= 4:
                motor_pwm.duty_cycle = 5140
            if pulse >= 5 and pulse <= 8:
                motor_pwm.duty_cycle = 6425
            if pulse >= 9 and pulse <= 19:
                motor_pwm.duty_cycle = 8995
            if pulse == 0:
                l_m_safety_loops += 1
                time.sleep(.005)
        if l_m_safety_loops >= 15:
            break
    while highmode == (True):
        high_mode_loop_count += 1
        highmode = True
        pwm0_loopcount = 0
        if pulse >= 0 and pulse <= 17:
            motor_pwm.duty_cycle = 10280
        if pulse >= 18 and pulse <= 20:
            motor_pwm.duty_cycle = 44675
            time.sleep(.300)
            motor_pwm.duty_cycle = 10280
            time.sleep(.200)

        if pulse >= 21 and pulse <= 26:
            motor_pwm.duty_cycle = 56540
            time.sleep(.300)
            motor_pwm.duty_cycle = 10280
            time.sleep(.200)

        if high_mode_loop_count >= 15:
            break                                                                ##logically, this should break it out of high mode and it should continue back to low mode as it won't be allowed in "off" mode at the beginning



This might be an eyeful, idk, but let me know what you think, if I've gotten anything wrong here, or if there's a way you'd feel this could be done much better.

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Fri Oct 15, 2021 7:25 pm

You have the right idea. I ported a bunch of guides from Arduino to CircuitPython and one tip I can suggest is to break the different components into seperate files. eg.

1) one CP script that receives PWM

2) one CP script that outputs PWM

3) one CP script that drives a motor

Make those work indepently, trim the code and then merge into a 4th script that includes all the features.

I would regularly scan the example guide codes for what I was trying to do in CircuitPython:

https://github.com/adafruit/Adafruit_Le ... tem_Guides

Maybe you can reduce some of your code size with 'elif' usage rather than separate 'if' statements.

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Fri Oct 15, 2021 11:52 pm

Thank you for the input. I've made a lot of progress since posting this. Though
I've run into a big snag and maybe you can help me with it. I purchased an Itsy Bitsy M0 Express for this project. I got it because it had native 3v3 output on nearly every pin, and the 5! pin has found a good purpose in this project, too.

This issue I'm having is that the pulseio library, and the pulsein that it comes with, aren't on the M0, and I can't seem to find anything similar for reading up and down time on the M0, or even something that reads PWM in general.

I'd rather not need to buy an M4, but I will if I have to.

My understanding is that it's virtually the same as the M0 Express, just with more memory. Is that right?

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Mon Oct 18, 2021 12:58 pm

@Daft_vagabond,

Are you saying that hthe pulseio library is not supported on your ItsyBitsy M0 Express? It is a built in core library for this board.

Screen Shot 2021-10-18 at 9.56.55 AM.png
Screen Shot 2021-10-18 at 9.56.55 AM.png (44.65 KiB) Viewed 170 times


https://circuitpython-jake.readthedocs. ... atrix.html

Can show me the error you are getting when you try to access PulseIn?

The main different between M0 and M0 express is flash memory space (extra 2MB). You would have that extra flash though on the ItsyBitsy M0 Express.

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Mon Oct 18, 2021 2:11 pm

Oooo, now this is odd. I received a response in another thread that reads

"by danhalbert on Fri Oct 15, 2021 10:49 pm

PulseIn used to be in pwmio, now it's only in pulseio. There isn't room for pulseio on the M0 boards, sorry.

To see what is available on which boards, see https://circuitpython.readthedocs.io/en ... atrix.html"

Now, sure enough, both the link they provided and the link you provided show different results, each supporting what you said.

That being said, here's the message I get when trying to use pulseio

"Traceback (most recent call last):
File "main.py", line 5, in <module>
ImportError: no module named 'pulseio'
"

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Mon Oct 18, 2021 4:53 pm

This looks like we have a documentation issue. I'm sure Dan is right when he says there is not enough room to include pulseio.

You probably should not try to work around this by going to an older CircuitPython release. I would take the easiest path and upgrade to an M4 Express board to get the pulseio support you need. Plus you get all the performance enhancements that come with the M4 (clock / sram / flash).

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Mon Oct 18, 2021 4:55 pm

Yeah, that's the route I ended up taking. Thank you for your help!

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Fri Oct 22, 2021 11:43 pm

PulseIn seems to be working differently in Circuitpython than it did on Arduino

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Sat Oct 23, 2021 2:25 pm

What differences have you observed.

Here are the doc links and sample code:

Arduino:
https://www.arduino.cc/reference/en/lan ... o/pulsein/

Code: Select all | TOGGLE FULL SIZE
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
}

void loop() {
  duration = pulseIn(pin, HIGH);
  Serial.println(duration);


CircuitPython:
https://circuitpython.readthedocs.io/en ... index.html

Code: Select all | TOGGLE FULL SIZE
import pulseio
import board

pulses = pulseio.PulseIn(board.D7)

# Wait for an active pulse
while len(pulses) == 0:
    pass
# Pause while we do something with the pulses
pulses.pause()

# Print the pulses. pulses[0] is an active pulse unless the length
# reached max length and idle pulses are recorded.
print(pulses)

# Clear the rest
pulses.clear()

# Resume with an 80 microsecond active pulse
pulses.resume(80)

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Sun Oct 24, 2021 2:42 am

Here's a snippet form the serial monitor for arduino(Which, to be clear, is what I want my output to look like in circuitpython, what my code is designed around)

Code: Select all | TOGGLE FULL SIZE
02:22:04.699 -> 8
02:22:04.699 -> 3
02:22:04.699 -> 6
02:22:04.699 -> 10
02:22:04.699 -> 7
02:22:04.699 -> 3
02:22:04.699 -> 4
02:22:04.699 -> 6
02:22:04.699 -> 5
02:22:04.699 -> 7
02:22:04.699 -> 5
02:22:04.699 -> 7
02:22:04.699 -> 5
02:22:04.699 -> 6
02:22:04.745 -> 3
02:22:04.745 -> 7
02:22:04.745 -> 6
02:22:04.745 -> 8


And here's what circuitpython repl had to say

Code: Select all | TOGGLE FULL SIZE
Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
main.py output:
<PulseIn>

Code done running.

Press any key to enter the REPL. Use CTRL-D to reload.


The only way I've gotten circuitpython to produce anything similar to what arduino is putting out is by using this

Code: Select all | TOGGLE FULL SIZE
import board
import pulseio
import time

pulse_in = pulseio.PulseIn(board.D13, maxlen=100, idle_state=True)

while True:
    pulse_in.clear()
    while len(pulse_in) == 0:

        pass
   
    if len(pulse_in):
        pulse_in.pause()
        print(len(pulse_in))
        time.sleep(0.005)
        pulse_in.clear()
        pulse_in.resume()

    else:
        print("loop")




Which outputs this

Code: Select all | TOGGLE FULL SIZE
3
6
5
3
6
6
3
5
6
5
3
5
4
3
5
5
2
6
4
4
2
6
5
4
5
4
5
6
3
5
6
5
4
4
5
4
5
5
5
4
5
5
4
6


Which aren't really the individual pulse values, but the total number in the array of stored values. But it did make me curious, though I'm not certain if this is accurate, but what if pulseIn on arduino wasn't actually showing me the duration of the individual HIGH pulses, but instead was showing me the total number of pulses stored in an array, just like circuitpython was when I got it to produce similar number. Both documentations suggest that this should return the duration in microseconds of the total time an individual pulse remained HIGH, but if one was maybe-incorrect, maybe the other one could be too.

So I wrote a code for the nano that asked for an index of pulseIn, and sure enough I got some interesting readings. Here's the code

Code: Select all | TOGGLE FULL SIZE
int pin = 7;
unsigned long duration;

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
}

void loop() {
int pulse[pulseIn(pin, HIGH, 100)]; //Variable to be used later

Serial.println(pulse[1]);
}


And here's what it spat out

Code: Select all | TOGGLE FULL SIZE
02:27:53.945 -> 14595
02:27:53.945 -> 25600
02:27:53.945 -> 25600
02:27:53.945 -> 2560
02:27:53.992 -> 2560
02:27:53.992 -> 2560
02:27:53.992 -> 0
02:27:53.992 -> 2560
02:27:53.992 -> 0
02:27:53.992 -> -29181
02:27:53.992 -> 25600
02:27:53.992 -> -29181
02:27:53.992 -> -29181
02:27:53.992 -> 25600
02:27:54.039 -> -29181
02:27:54.039 -> 25600
02:27:54.039 -> 25600
02:27:54.039 -> -29181
02:27:54.087 -> 25600
02:27:54.087 -> -29181
02:27:54.087 -> 0
02:27:54.087 -> -29181
02:27:54.087 -> 2560
02:27:54.087 -> 2560
02:27:54.087 -> 14595
02:27:54.087 -> -19906
02:27:54.087 -> 0
02:27:54.087 -> 14595
02:27:54.087 -> 14595
02:27:54.135 -> 2560
02:27:54.135 -> 14595
02:27:54.135 -> 0
02:27:54.135 -> -9720
02:27:54.135 -> 25600
02:27:54.182 -> 0
02:27:54.182 -> 2560
02:27:54.182 -> -24320
02:27:54.182 -> -9720
02:27:54.182 -> -9720
02:27:54.182 -> -29181
02:27:54.182 -> 0
02:27:54.182 -> -29181
02:27:54.182 -> 25600
02:27:54.182 -> -24320
02:27:54.229 -> 0
02:27:54.229 -> 4609
02:27:54.229 -> 0
02:27:54.229 -> 2560


It may also be worth adding that if I try something similar in circuitpyhton with something like

Code: Select all | TOGGLE FULL SIZE
import pulseio
import board

pulses = pulseio.PulseIn(board.D13)


while True:
    # Wait for an active pulse
    while len(pulses) == 0:
        pass
    # Pause while we do something with the pulses
    pulses.pause()

    # Print the pulses. pulses[0] is an active pulse unless the length
    # reached max length and idle pulses are recorded.
    print(pulses[0])

    # Clear the rest
    pulses.clear()

    # Resume with an 80 microsecond active pulse
    pulses.resume(80)


It gives me readings like this

Code: Select all | TOGGLE FULL SIZE
27
23
27
27
27
26
27
27
27
27
27
27
27
27
27
22
21
27
27
21
21
27
22
6
27
27
27
27
27
27
27
27
22
27
27
27
27
27
27
22
27
27
27
27
27
27
27
27
27
27
27
27
27


I don't know if I misread something or if I'm expecting the wrong thing from each of these in their respective languages. Though, if I'm at all correct with any of this, it might suggest that these functions might not be properly described, but also I'm really new to all this and I could easily have little idea what I'm talking about

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Mon Oct 25, 2021 1:20 pm

Interesting results from your test cases.

PulseIn is going to give you the duration in microseconds of the positive or negative pulse.

Looking at your original Arduino code you seem to be expecting pulses in the 18 - 26 microsecond range. However, in your most recent post you are showing much shorter pulse durations on the arduino side in the 3-10 microsecond range.

What is the small device sending out the PWM signal that you are measuring?

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Mon Oct 25, 2021 3:47 pm

Which arduino code, the first one?

The device is a small board designed to be used in prop-making. It has motion sensors and stuff. There are pads for running leds and those pads have a feature where they'll try to mimic the behavior of the speaker by producing a PWM, so the more intense the sound is, the brighter the leds will be.

It's working fine on the arduino, at least the pulseIn is producing consistent results that I wrote my code around, but I expected those same results from the pulseIn of the M4 express.

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Tue Oct 26, 2021 12:32 am

I've been trying to figure out PulseIn and how it's supposed to function for days, and I still haven't been able to get readings similar to Arduino's PulseIn.

Even the test/example code only prints <PulseIn> to repl.

As a control group. I am still able to get the readings I have come to expect by making a simple pulseIn on arduino.

I even changed my M4 to an Arduino board for a sec, just to see if it's a hardware thing, but even the M4 started giving back normal readings as an Arduino.

I'm not certain what to do from here, unfortunately.

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Re: Arduino to Circuitpython code conversion

by mikeysklar on Tue Oct 26, 2021 2:47 pm

Thanks for trying the M4 configured with Arduino to confirm you saw the same behavior as another Arduino controller.

Just to confirm you are running CircuitPython 7.x with bootloader 3.13.0 on a Feather M4 Express?

What if you were to collect more pulses without the pause line and print out the entire pulses array. Do you see a change in the timing that better matches the Arduino code?

Code: Select all | TOGGLE FULL SIZE
import pulseio
import board

pulses = pulseio.PulseIn(board.D7, maxlen=20)

# Wait for an active pulse
while len(pulses) == 0:
    pass
# Pause while we do something with the pulses
#pulses.pause()

# Print the pulses. pulses[0] is an active pulse unless the length
# reached max length and idle pulses are recorded.
print(pulses)

# Clear the rest
pulses.clear()

# Resume with an 80 microsecond active pulse
pulses.resume(80)

mikeysklar
 
Posts: 6198
Joined: Mon Aug 01, 2016 8:10 pm

Re: Arduino to Circuitpython code conversion

by Daft_vagabond on Tue Oct 26, 2021 3:25 pm

I have the latest version of Circuitpython and I'm running it on an Itsy Bity M4 Express.

using the code you posted, though with the pin changed, its printed this

Code: Select all | TOGGLE FULL SIZE
Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
main.py output:
<PulseIn>

Code done running.

Press any key to enter the REPL. Use CTRL-D to reload.


So just that"<PulseIn>" again. In order to get any numbers to print I either have to request len(pulses) or pulses[indexn umber].

Trying to have it print each reading from each index with the following code:

Code: Select all | TOGGLE FULL SIZE
import pulseio
import board

pulses = pulseio.PulseIn(board.D13, maxlen=20)

while True:
    # Wait for an active pulse
    while len(pulses) == 0:
        pass
    # Pause while we do something with the pulses
    # pulses.pause()

    # Print the pulses. pulses[0] is an active pulse unless the length
    # reached max length and idle pulses are recorded.
    for i in range(len(pulses)):
        print(pulses[i])

    # Clear the rest
    # pulses.clear()

    # Resume with an 80 microsecond active pulse


Gave me this:

Code: Select all | TOGGLE FULL SIZE
27
6
21
6
21
7
21
6
21
27
6
22
27
27
6
21
7
21
6
21
27
6
21
6
21
7
21
6
21
27
6
22
27
27
6
21
7
21
6
21


If it interests you, I recorded a video of 3 different codes running side-by-side. The first is on Arduino, reading PulseIn as though it were an array, the second is just reading PulseIn normally(that values I want and wrote my original code around), and the third is Circuitpython in Mu, measuring the value of pulses[0], since the only other thing that could produce numbers was len(pulses) and I don't think that'd be what I want.

Daft_vagabond
 
Posts: 43
Joined: Thu May 28, 2020 2:53 pm

Please be positive and constructive with your questions and comments.