Shop OBEX P1 Docs P2 Docs Learn Events
How do variable affect objects? — Parallax Forums

How do variable affect objects?

Hello,

I'm trying my hand at coding objects for the first time. As a starting point I used some code from the tutorial in the prop manual v1.0. The goal is an object: "monitor" that will do serial output:
VAR
  long Stack [9]
  long delay
  long time
  byte Cog

PUB  Start (Pin, Baud, Data): Success
  Stop
  Success := (Cog:= cognew(Ser (Pin, Baud, Data), @Stack) +1)

Pub Stop

  if Cog                        ' any value greater than 0 must be true
    cogstop(Cog~ -1)
 
Pub Ser (Pin, Baud, Data)

  dira[Pin]~~
  delay := ( clkfreq / Baud )
  Data <-= ( Pin + 1 )          'Rotates MSB left until it is at  correct Pin for OUTA
  time :=cnt                       
  repeat
    repeat 4
      outa[Pin]~~                  'output a start bit  of each byte
     waitcnt (time += delay)
      repeat 8
        outa:= !Data
        Data <-= 1
        waitcnt (time +=delay)
      outa[Pin]~
      waitcnt(time+= delay)      'output 2 stop bits between bytes of data
      waitcnt(time += delay)
    waitcnt( time += delay*50)

When I call the ser(pin,baud,data) method from another object:
OBJ
  sout : "monitor"

PUB main

  sout.ser(17,9600, 25)
  repeat
.... it works fine.
However, when I attempt to call it from the start method and use another cog:
sout.start(17,9600, 25)
....it fails.

However, if I eliminate the global variables 'time' & 'delay' from the 'ser' method and just fudge in some numbers then everything works as expected. Is there something funny in how I'm using the variable or is that a red herring?

Thanks for any suggestions.

mo

Comments

  • AribaAriba Posts: 2,690
    Looks like the stack is too small, so the global variables get overwritten

    Andy
  • ElectrodudeElectrodude Posts: 1,658
    edited 2016-04-17 02:18
    Your stack size of only 9 longs is certainly not large enough. Make it 32 or so and see if that fixes it. Once you're sure it works, you can find the minimum value that works using "Stack Length.spin" if you're short on memory.

    Also, I would recommend making your "time" and "delay" variables local to the "ser" method instead of global, unless you need to modify them somewhere else that you didn't show.

    Once you get it working, it wouldn't be a bad idea to make the "ser" method private.
  • Yes, the stack was too small. That is what I get for borrowing snippets of code without thoroughly understanding how they work. When programming in assembly reserving space seems a bit more self evident. In the tutorial I stole the code from the relationship of the stack size to the code was not really explained so it didn't dawn on me to adjust it for more variables.

    Thanks for the quick, accurate and relevant suggestions.

    mo
Sign In or Register to comment.