Shop OBEX P1 Docs P2 Docs Learn Events
Changing a global variable from inside a method? — Parallax Forums

Changing a global variable from inside a method?

bob_g4bbybob_g4bby Posts: 555
edited 2026-02-28 22:49 in PASM2/Spin2 (P2)

I want to add a method to my rotary encoder library for the 8encoder that allows the programmer to link a knob to a variable, so that turning the knob changes that variable.

Say I have a variable and a pointer:-
long myvar
^long myptr

This would set myptr to point to myvar - yes?
[myptr] := @myvar

I create a method :-
pub mymethod(knob#, ptr) | delta
delta := read_knob_change(knob#)
... some code ...

I use the method:-
mymethod(2, myptr)

What would 'some code' have to include to modify the value held in myvar, please?

Couldn't find any clues in the Spin2 manual and have tried all sorts, cheers, bob

Comments

  • JonnyMacJonnyMac Posts: 9,699
    edited 2026-03-01 00:29

    No matter what, you still have to access the encoder hardware in a method to assign your target variable(s). You get nothing using a pointer in this case.

    Where it might be useful is reading all with one method to any arbitrary array.

    pub get_encoders(p_data) | ch
    
      repeat ch from 0 to 7
        long[p_data][ch] := encoder_read(ch)
    

    This code works in the P1 and in the P2. The pointer p_data is the address of the first element of the array.

  • bob_g4bbybob_g4bby Posts: 555
    edited 2026-03-01 08:42

    Cheers, Jon, I'll have to go at it another way - there's always an alternative. The code above is a useful example in it's own right - I would never have guessed the syntax

  • My solution was this in the end:-

    pub read_knob_inrange(channel,min,max) : result | temp
    ' read knob value - channel 1-8 but limit the result to between min and max
    
           temp := read_knob(channel)
           result := min #> temp <# max
           if temp <> result
                write_knob(channel,result)
    

    so controlling a global variable was just a simple assigment:-

    myvar := read_knob_inrange(1,-30,30) ' knob ch1 controls myvar between -30 and 30

Sign In or Register to comment.