A small change as below should be made in the code for working correctly in Hi-TECH - C compiler [ in order to differentiate between binary and octal].
Wrong code:
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
| TRISA = 00000000;
TRISB = 00000001;
TRISC = 00000000;
TRISE = 00000000;
PORTA = 00000000;
PORTB = 00000000;
PORTC = 00000000;
PORTE = 00000000;
ANSELA = 00000000;
ANSELB = 00000000; |
Correct one:
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
| TRISA = 0b00000000;
TRISB = 0b00000001;
TRISC = 0b00000000;
TRISE = 0b00000000;
PORTA = 0b00000000;
PORTB = 0b00000000;
PORTC = 0b00000000;
PORTE = 0b00000000;
ANSELA = 0b00000000;
ANSELB = 0b00000000; |
Also instead of writes to PORT (though works well many times), writes should be made to LAT registers as recommended by datasheet.
Instead of :
Code C - [expand] |
1
2
| #define LED RC6
LED = 1; // ON LED which is connected on RC6 of PORTC |
Use like this:
Code C - [expand] |
1
2
| #define LED LATCbits.LATC6
LED = 1; // ON LED which is connected on RC6 of PORTC |
for better dynamic code (even in polling method)
Instead of waiting for indefinte period.
Code C - [expand] |
1
2
3
4
| while(!ECHO);
TMR1ON = 1;
while(ECHO);
TMR1ON = 0; |
We can use the following code. If the pin does not receive ECHO within 120 mS,
exit the loop and continue. [*The delay period should be chosen according to our distance calculation]
Code C - [expand] |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| int j = 0;
do{
if(ECHO_STARTED_SENSOR4){
IOCBN2 = 1;
ECHO_BIT2 = 1;
TMR1ON = 1;
}
if(ECHO_COMPLETED_SENSOR4 && ECHO_BIT2){
TMR1ON = 0;
IOCBP2 = 1;
ECHO_BIT2 = 0;
break;
}
j++;
}while(j < 4800); // 120mS delay [FOR 4MHz CLOCK] |
Also, MPLAB v8.63/V8.89, HI-TECH-C v9.80/V9.83,
Instead of using the following code;
Code C - [expand] |
1
| distance = (int) ((TMR1L | (TMR1H << 8)) / 59); // in CM (58.82) |
We can use,
Code C - [expand] |
1
2
| distance = (int) (TMR1 / 59) // in CM [if Timer prescaler 1:1]
distance = (int) (TMR1 / 14.70); // in CM [if Timer prescaler 1:4] |
we don't need to bother about the reading squence of 16 bit register.
thanks to all,
pmk