B4R Question is faster digitalRead possible?

Discussion in 'B4R Questions' started by wcieslik, Nov 22, 2018.

  1. wcieslik

    wcieslik Member Licensed User

    is there a way to read input pins directly, without using digitalRead ?

    eg. in the Arduino IDE you can read the pin status directly using :
    unsigned int MyPins =PIND; // PIND is an internal register and reserved keyword

    and now MyPins is the binary representation of the first 8 pins. In one instruction.

    As opposed to using digital read for each pin.
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    You can implement it with inline C. Call a method that sets the value to a global variable.
     
    wcieslik likes this.
  3. wcieslik

    wcieslik Member Licensed User

    Thanks Erel,

    I tried this tonight and got it working as you suggested.
    testing a loop of 10000 digitalReads of two pins against 10000 reads of the PIND register.
    97ms vs 9ms . Nice!

    Code:
    Sub Process_Globals
        
    Public Serial1 As Serial
        
    Private  n1 , n2 As Boolean
        
    Private P5,P6 As Pin
        
    Private LEN As Int
        
    Private pinreg As UInt
        
    Private TT As Long
      
    End Sub

    Private Sub AppStart
        Serial1.Initialize(
    115200)
        
    Log("AppStart")

        P5.Initialize(
    5,P5.MODE_INPUT_PULLUP)
        P6.Initialize(
    6,P6.MODE_INPUT_PULLUP)
        LEN = 
    10000
      

        
    Log("test 1 digitalRead ")
        TT = Millis
        
    For a=1 To LEN
            n1 = P5.DigitalRead
            n2 = P6.DigitalRead
        
    Next
        
    Log("time to run ",Millis-TT,"ms")  
        
    Log(n1,n2)
        Delay(
    1000)
      
      
        
    Log("test 2 PIND register ")
        TT = Millis
        
    For a=1 To LEN
            RunNative(
    "readpin",Null)
        
    Next
        
    Log("time to run ",Millis-TT,"ms")
        
    Log(Bit.Get(pinreg,5),Bit.Get(pinreg,6))
        Delay(
    7000)
      
      
      
    End Sub

    #if C
    void readpin (B4R::Object* o) {
       //use lower case variables
       b4r_main::_pinreg = PIND;
    }
    #End if
    On an Arduino Nano my result is :

    ********************* PROGRAM STARTING ****************
    AppStart
    test 1 digitalRead
    time to run 97ms
    01
    test 2 PIND register
    time to run 9ms
    01
     
    Erel and BaGRoS like this.
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice