Need Help with counting time between inputs

I am trying to count the milliseconds between two inputs when their states change to calculate how fast my hot wheels are traveling. I looked through the libraries and found mstime which counts the duration of a cog while it’s running but I was unsuccessful at getting any returned values. I’m almost certain the code is wrong because I’m still a beginner and the libraries are usually lacking in examples which help me tremendously. Any input to mstimer.h or any other method for counting milliseconds is greatly appreciated.

Comments

  • tomcrawfordtomcrawford Posts: 1,046
    edited 2019-03-11 - 23:58:39
    Something like
    repeat until ina[first_sensor] <> 0
      startTime := CNT
      repeat until ina[Second_sensor] <> 0
      endTime := CNT
      DeltaTime := endTime - StartTime
      Velocity := Distance/DeltaTime
    
    Re-inventing the wheel is not a waste of time if, when you are done, you understand why it is round.
  • Is this for the simpleIDE? I haven’t seen CNT but I’ll try it out, thank you.
  • Oh, heck! I'm sorry. My example is spin. Don't know nothin' 'bout C.
    Re-inventing the wheel is not a waste of time if, when you are done, you understand why it is round.
  • No, but your comment does give insight to much cleaner code than mine, and seeing how you approached the problem is beneficial.
  • JonnyMacJonnyMac Posts: 6,182
    edited 2019-03-12 - 22:49:13
    I prefer Spin for the Propeller, but as I've been doing a bunch of coding in C for another processor, I decided to download SimpleIDE and give it a try.

    This code measures the event time in system ticks and displays the result in 1/100ths milliseconds (10 microseconds). If you use optical sensors the output will probably be active-low which is how this code works. If your sensors are active-high you'll need to change waitpne to waitpeq. Timed events must be less than ~26 seconds, otherwise there will be a roll-over error with the CNT register.
    /*
      Event timer
      -- measures milliseconds between falling edges of two sensors
    */
    
    #include "simpletools.h" 
    
    #define SENSOR_1 4                            // active-low sensor inputs
    #define SENSOR_2 5
    
    
    void main()
    {
      int et;
      
      while(1) {
        pause(3000);  
        for(int i = 3; i > 0; i--) {
          printf("%d... ", i);
          pause(1000);
        }  
        printf("Go!\n");
        et = elapsed_ticks() / 800; 
        printf("Event time: %d.%02d ms\n\n", et / 100, et % 100);   
      }  
    }
    
    
    // Return elapsed time between active-low sensors
    // -- units returned is in system ticks
    
    int elapsed_ticks()
    {
      int elapsed;
    
      waitpne(1 << SENSOR_1, 1 << SENSOR_1);      // wait for input to drop
      elapsed = -CNT;                             // start timing
      
      waitpne(1 << SENSOR_2, 1 << SENSOR_2); 
      elapsed += CNT - 144;                       // stop timing & remove overhead
        
      return elapsed;
    }
    


    Jon McPhalen
    Hollywood, CA
    It's Jon or JonnyMac -- please do not call me Jonny.
  • Jon as brilliant as - usual(?) - well done …
    JonnyMac wrote: »
    I prefer Spin for the Propeller, but as I've been doing a bunch of coding in C for another processor, I decided to download SimpleIDE and give it a try.

    Just like that. Give it a try. And I can read C code. Wonderful.

    I do love the style you program in Spin, and I try to reach that goal with my own stuff, but I fail miserable.

    It proves again that programming and style is independent of the language used and I wish I had the ability of you to separate meaningful subroutines and name them correctly. Does not happen here but in most of your objects I was bound to use, I was in awe about the structure and naming.

    Some people know that programming is a art form, and in my opinion you are already a great artist. I know you want to be a actor, but - hell - why?

    Sorry if I offended you, but gosh Jon, with all the stuff you did with props and controllers, didn't you figured out that that is where you belong? You should teach the art of programming, not trying to get more - hmm- screen time(?)

    Please be not offended. I am a big fan of you.

    Enjoy!

    Mike
    I am just another Code Monkey.
    A determined coder can write COBOL programs in any language. -- Author unknown.
    Press any key to continue, any other key to quit

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this post are to be interpreted as described in RFC 2119.
  • JonnyMacJonnyMac Posts: 6,182
    edited 2019-03-12 - 19:54:39
    Why can't I be both an engineer and an actor? When my boss, [former Parallaxian] Ryan Clarke, offered me a job, one of the conditions was that I do not walk away from acting for this job. He told me that when I have an audition to go audition. If I get a gig, do it. Opportunities like the one he offered me don't come up very often, and I am grateful. Like me, Ryan is an artist. Few are as creative at puzzle creation as he. It's part of the reason why he and our other boss are consultants to the TV show "Mr. Robot."

    Tony Robbins once posed the question: What do you have to give up to have more?
    The answer: Nothing!

    I will agree with you, though, that good form/style is independent of language. Part of my charge at the new job is to teach our young staff how to code well. Language is irrelevant. We primarily use Python and C, but I have been showing the kids (as I call them) the wonders of the Propeller and a couple are jumping on.

    I also get to do product development and was recently granted the funds to develop a product for the company. I'm using the Propeller. I'm also going to build an ICS demo device with a couple of the youngsters that uses the Propeller and modular IO over and I2C and SPI bus structure.

    It's hard for people who are not actors to understand those of us who are. There is nothing at all logical about that choice. My coach and dear friend, the late Cliff Osmond, told actors that they literally had to be out of their minds to act. It was a double entendre . First, it's not a logical choice for an secure life. Second, by being out of our own mind, we can occupy the mind of character we are playing.

    Few make it big, a few more make a living, most of us have other jobs. No matter where we are, we are driven to get on a stage or in front of a camera. While in Texas I had the opportunity to work with casting director Shari Rhodes ("Jaws"). She told a group of us that people are born to be actors and it's best that they pursue that profession -- regardless of outcome -- lest they become serial killers. She was being a bit jokey, of course, but with a point: we are happy pursuing our dreams. Enjoy the journey.

    Those who look at my code can tell that I enjoy it. I try to do with with care, because most of the code I write will be viewed by others. That's the thing about source code: it's for humans. That said, I think we should be kind to the fellow humans who see our code by giving them something that is clean, concise, and appropriately documented.

    Finally, I was able to write that little demo in a language I don't routinely use (but do routinely swear at) because I know the Propeller well. My message to those of you that are new to the Propeller is that learning to code in Spin -- even if you won't use it heavily later -- is valuable because it really helps you learn the hardware. Understanding the hardware is one of the keys to writing clean code.
    Jon McPhalen
    Hollywood, CA
    It's Jon or JonnyMac -- please do not call me Jonny.
  • 3snke3snke Posts: 7
    edited 2019-03-13 - 07:06:57
    Thanks Jon this was just what I was looking for, sorry for the late reply but i was at work. I just got to class and ran the code and it works like a charm (using my hand which is slower). When I get home I will update the results on the mph of the hotwheels. Out of curiosity is waitpne a function that can be used in all c programs (sorry I'm still new and foreign to this), also

    "et = elapsed_ticks() / 800;
    printf("Event time: %d.%02d ms\n\n", et / 100, et % 100);
    "
    elapsed += CNT - 144; // stop timing & remove overhead
    "
    is the 800 referring to the speed at which the propeller runs at? I was able to piece together how the code works but these three lines confuse me.

    - Thanks
  • JonnyMac wrote: »
    Understanding the hardware is one of the keys to writing clean code.

    I'll just re-quote this one for emphasis. The importance of understanding the general functions in a CPU, how they go about accessing memory, fetching instructions, why registers exist, decoding and executing each instruction, one by one.

    Programming languages become far more understandable once the hardware beneath is learnt.

    "There's no huge amount of massive material
    hidden in the rings that we can't see,
    the rings are almost pure ice."
  • 3snke wrote: »
    is the 800 referring to the speed at which the propeller runs at?
    Yes, 80 MHz is the system clock frequency. dividing the ticks by 800 scales it to 100ths of milliseconds.

    The " - 144" is subtracting 144 ticks (1.8 microseconds) from the measured interval. This is done because that is the excess number of ticks in spin processing time required to acquire the interval measurement.

    The two part " / 100" and " % 100" in the printf() is for presentation of what's called a fixed point number. In this case, treating it as milliseconds with two decimal places.
    "There's no huge amount of massive material
    hidden in the rings that we can't see,
    the rings are almost pure ice."
  • JonnyMacJonnyMac Posts: 6,182
    edited 2019-03-13 - 14:52:51
    3snke wrote: »
    Thanks Jon this was just what I was looking for, sorry for the late reply but i was at work. I just got to class and ran the code and it works like a charm (using my hand which is slower). When I get home I will update the results on the mph of the hotwheels. Out of curiosity is waitpne a function that can be used in all c programs (sorry I'm still new and foreign to this), also

    "et = elapsed_ticks() / 800;
    printf("Event time: %d.%02d ms\n\n", et / 100, et % 100);
    "
    elapsed += CNT - 144; // stop timing & remove overhead
    "
    is the 800 referring to the speed at which the propeller runs at? I was able to piece together how the code works but these three lines confuse me.

    - Thanks

    The waitxxx instructions are specific to the Propeller. This is part of my point about leaning the hardware well in order to write the most efficient code. You could, of course, use a loop to monitor a pin; but the waitxxx instructions simplify that and remove a lot of overhead (not all, though).

    Using C the Propeller is forced to run at 80MHz; dividing the number of system ticks in the event by 800 reduces the result to 10 microsecond units (0.01 milliseconds). I thought -- considering the short length of your speed trap -- that sub-millisecond resolution would be appropriate.

    There is always some amount of overhead in coding, and coding is an iterative process. The "- 144" was not part of the first cut, though I knew from past experience I would need to subtract some overhead. In the first cut of code I simply looked at the raw result when the second sensor was blocked before the first tripped; this would simulate a zero-duration event. The result of this test was the overhead that needed to be removed from the timing result. After that it was a simple matter to divide to an appropriate resolution and format the output.
    Jon McPhalen
    Hollywood, CA
    It's Jon or JonnyMac -- please do not call me Jonny.
  • Hello!
    Jon I fully agree to both of your statements. Regarding how the prop works, certainly. Regarding the work you do, both acting, and even behind the scenes, it is still amazing.

    I have several of your examples here for the Prop, the one for the RGB Pixels is one. For the Stamp? That's the Calculator one I use to confirm that I'd managed to get the thing running properly.
    And as usual this is being sponsored by the friends of Dwarf Grumpy.
Sign In or Register to comment.