Continue to Site

# basic code need help: cannot produce correct result

Status
Not open for further replies.

#### huanyong

##### New Member
Code:
cnt var byte
trisb=%00000000

cnt=0
main:
portb.4=cnt.0
portb.5=cnt.1
portb.6=cnt.2
portb.7=cnt.3
cnt=cnt+1
goto main

i wan pic to count from 0 in portb (4~7), but the result simulated in mplab doesn't seem to be correct, can anyone tell me why?

thanx!

#### Eclipsed

##### New Member
What do you mean by count in port b? which basic are you using?

#### huanyong

##### New Member
count is cnt, which means that i wanna produce 0000,0001,0010,0011,0100 ........ at portb4~portb7

p/s: im using pic basic pro

#### Eclipsed

##### New Member
Trythis...
cnt=0
main:
portb=cnt
cnt=cnt+16
if cnt = 240 then cnt = 0; add this if you want to start from zero again
goto main

I tried this and it works.Probably not the most efficient, but the first thing that came to my mind.

#### ivancho

##### New Member
huanyong:
There is a problem with your program and that is that the variable will overvlow since it is never reset to 0. Adding a 1 when you are at 255 will make the next count 0, but mplab perhaps doesn't know how to "resolve" this.

What results are you getting? I would be confident that your code should work, I am not sure how well mplab simulates a PBP code, since I have never done it

I would add a reset when cnt = 255, like this:

Code:
cnt var byte
trisb=%00000000

cnt=0
main:
portb.4=cnt.0
portb.5=cnt.1
portb.6=cnt.2
portb.7=cnt.3

If cnt = 255 then
cnt= 0
else
cnt=cnt+1
endif

goto main

Ivancho

#### Eclipsed

##### New Member
Ivancho, are you refering to my code? I tried this in PIC simulator IDE, I have 0 experience with MPLAB.And it worked perfect(after I removed the "if" statement,that is).This should give the result he is looking for, not sure what he wants to do with the lower nibble on portb though.Also this assembles into 14 words, the other code is 33 words.

cnt=0
main:
portb=cnt
cnt=cnt+16
goto main

#### ivancho

##### New Member
Do you get any trouble because of the variable overflowing?

You still want that IF cnt=240 then cnt=0 so that it doesn't stay at 1111 for 15 more counts.

Still is a great solution! 8)

#### Eclipsed

##### New Member
I didn't investigate too much, but it counted incorrectly with the "if" statement(never got to 1111).The original "if" statement was in the wrong place, it should have been before the"cnt=cnt+16".It worked correctly with the if statement in the right place,but it also worked correctly with no "if" statement at all(each count was 6 instruction cycles including 1111 and 0000).I see what you are saying, and I guess I never put much thought into how PBP rolls variables.I don't know much about mplab, I think I will have to learn.

Status
Not open for further replies.

Replies
3
Views
423
Replies
11
Views
2K
Replies
10
Views
1K
Replies
3
Views
753
Replies
1
Views
787