<h1>THE FORUM HAS MOVED,  VISIT US AT OUR NEW SITE www.picbasic.org. Access to this Archive is restricted. Visit the NEW site at www.picbasic.org.  Unless you use the url http://www.picbasic.org you will not gain access to the support forum, wiki and knowledge base. Visit WWW.PICBASIC.ORG  Do not try to log in or register here, use your keyboard and enter the url http://www.picbasic.org directly into your browser. </h1>  

Go Back  

THE FORUM HAS MOVED, VISIT US AT OUR NEW SITE www.picbasic.org. Access to this Archive is restricted. Visit the NEW site at www.picbasic.org. Unless you use the url http://www.picbasic.org you will not gain access to the support forum, wiki and knowledge base. Visit WWW.PICBASIC.ORG Do not try to log in or register here, use your keyboard and enter the url http://www.picbasic.org directly into your browser.

> Proton Development Suite > Proton Plus Compiler v3

Proton Plus Compiler v3 Coding problems and general discussion related to the Development Suite

Reply
 
Thread Tools Search this Thread Rate Thread Display Modes
Old 26th August 2009, 21:36   #91
~ Sy ~
Licensed User
 
Join Date: Jun 2009
Location: Near Norwich
Posts: 283
~ Sy ~ is on a distinguished road
Default

IPEN should have been RCON.7, not .0
~ Sy ~ is offline   Reply With Quote
Old 26th August 2009, 21:43   #92
~ Sy ~
Licensed User
 
Join Date: Jun 2009
Location: Near Norwich
Posts: 283
~ Sy ~ is on a distinguished road
Default

It works !

Code:
    Symbol IPEN = RCON.7   ' Interrupt Priority Enable bit   
    Symbol TMR1IP = IPR1.0 ' TMR1 Overflow Interrupt Priority bit    
    Symbol TMR1IF = PIR1.0 ' TMR1 Overflow Interrupt Flag bit
    Symbol TMR1IE = PIE1.0 ' TMR1 Overflow Interrupt Enable
    Symbol GIEL = INTCON.6 ' Peripheral Interrupt Enable bit
Initialisation for low priority interrupt:
Code:
    IPEN = 1            ' Enable priority interrupts.
    TMR1IP = 0          ' Set Timer1 as a low priority interrupt source
    TMR1IF = 0          ' Clear the Timer1 interrupt flag
    TMR1IE = 1          ' Enable Timer1 interrupts
    TMR1ON = 1
    IntsOn
Read the manual over and over and with the Proton help too, Thanks Tim.

Any reply on the other query regarding the peeking into the serial buffer?
~ Sy ~ is offline   Reply With Quote
Old 27th August 2009, 21:21   #93
~ Sy ~
Licensed User
 
Join Date: Jun 2009
Location: Near Norwich
Posts: 283
~ Sy ~ is on a distinguished road
Default

So chuffed, I now have a PC emulating my control module, soon to be a PIC once I get the hardware made up, this sends out data which is recieved by my PIC module on interrupt. The PIC runs a low priority interrupt to perform a stop watch function in the background whilst communicating with the other device via serial, all works really well.

Almost at the stage where I am ready to build the hardware...this is where it all goes pair shaped. My knowledge of electronics isn't very good.
~ Sy ~ is offline   Reply With Quote
Old 28th August 2009, 13:07   #94
~ Sy ~
Licensed User
 
Join Date: Jun 2009
Location: Near Norwich
Posts: 283
~ Sy ~ is on a distinguished road
Default

It would seem I have a problem....at first I thought everything was ok, but then I started getting lock ups or what appeared to be lock ups.

I seem to be missing the first byte of data transmitted and this seems to be quite repeatable.

I have checked the PC transmitting the data by connecting to another PC and verifyig that the data is indeed being sent.

I am using a high priority interrupt for the serial comms and a low priority interrupt for a MS timer.

I've modified the macros IntsOff and IntsOn to disable both interrupts and enable both:

Code:
    $define IntsOff While GIEL = 1: GIEL = 0: Wend: While GIEH = 1: GIEH = 0: Wend
    $define IntsOn GIEH = 1: GIEL = 1
In my main program loop I do the following:

Code:
MAIN:
' Disable interrupts
    IntsOff
    
' How many bytes in the serial buffer?
    While _USART_INDEX_IN <> _USART_INDEX_OUT
' Transfer everything buffered from the serial port into our packet buffer        
        HRSIn aryBuffer[bytNextIdx]
        Inc bytNextIdx
            
        If bytNextIdx >= SIN_BUFFER_SIZE Then
            Clear aryBuffer
            bytNextIdx = 0                    
        EndIf                 
        Set bitCheckBuffer
    Wend

    If bitCheckBuffer > 0 Then    
        Clear bitCheckBuffer
        GoSub DECODE_PACKET
If bytDecodeStatus <> PACKET_OK Then
    Cls
    Print At 0, 5, Hex2 bytDecodeStatus
EndIf
        If bytDecodeStatus > 0 Then  
    ' Clear the packet buffer ready for the next message            
For bytIdx=0 To bytNextIdx-1
    Print At bytIdx, 0, Hex2 aryBuffer[bytIdx]
Next          
            Clear bytNextIdx
            Clear aryBuffer
        EndIf
    EndIf

' Enable interrupts
    IntsOn
    GOTO MAIN
There main loop does other stuff to, but this shouldn't be relevant. In my decode routine I do the follow:

Code:
DECODE_PACKET:
' If the first byte of the packet is not CC then we are out of sync. 
    If aryBuffer[0] <> $CC Then 
        bytDecodeStatus = SYNC_ERR
        Return
    EndIf
' Do we have a full packet?    
    If aryBuffer[1] > 0 And bytNextIdx < aryBuffer[1] Then 
        bytDecodeStatus = TO_SHORT
        Return
    EndIf
' Before we waist time validating the packet is it addressed to this node ?
    If (aryBuffer[2] & $0f) <> 0 And (aryBuffer[2] & $0f) <> bytNodeAddr Then 
        bytDecodeStatus = ADDR_ERR
        Return
    EndIf
' We should have a complete packet, does it have an end byte in the 
' correct place?
    bytIdx = aryBuffer[1] - 1
                
    If aryBuffer[bytIdx] <> $DD Then
        bytDecodeStatus = PROTOCOL_ERR
        Return
    EndIf
' Save the CRC in the packet
    bytChar = aryBuffer[1] - 2
    bytChar = aryBuffer[bytChar]
' Calculate a CRC for this packet
    GoSub CALC_CRC
' Compare CRC's                    
    If bytChar <> bytCRC  Then
' If the CRC is invalid, discard the packet                
        bytDecodeStatus = CRC_ERR
        Return
    EndIf
' CRC is ok, what type of packet is this?
'...code to progress packet contents ...
    bytDecodeStatus = PACKET_OK
    Return
The decodestatus byte has the following values:

Code:
    Dim bytDecodeStatus As Byte
    Dim TO_SHORT        As $0
    Dim PACKET_OK       As $1
    Dim SYNC_ERR        As $2
    Dim CRC_ERR         As $3
    Dim ADDR_ERR        As $4
    Dim PROTOCOL_ERR    As $5
The protocol I've come up with is as follows:

Byte 1: Start Byte always $CC
Byte 2: Bytes in packet, including start and end bytes
Byte 3: Lo nibble (address 1 to 8), hi nibble function code
Byte 4: Lo nibble (data nibbles to follow min value 1), Hi nibble (first data nibble)
Byte 5: CRC (calculated using byte 3 to 4)
Byte 6: End Byte always $DD

In the above example the packet is only 6 bytes, and so far this is all I'm working with, but what I receive is always missing the $CC

Last edited by ~ Sy ~; 28th August 2009 at 13:14.
~ Sy ~ is offline   Reply With Quote
Old 28th August 2009, 14:25   #95
~ Sy ~
Licensed User
 
Join Date: Jun 2009
Location: Near Norwich
Posts: 283
~ Sy ~ is on a distinguished road
Default

I've fixed it, but I've no idea why ?

I put some debug info inside the loop that calls HSRIn, and found that with the Print At statements in the loop, it always works and never misses the start byte.

So I removed the debug print statements and sure enough the fault was back, so I changed the code to:

Code:
    While _USART_INDEX_IN <> _USART_INDEX_OUT
' Transfer everything buffered from the serial port into our packet buffer        
        HRSIn bytChar   
        aryBuffer[bytNextIdx] = bytChar
' No idea why, but without this we miss the first character
        DelayMS 1
        Inc bytNextIdx
            
        If bytNextIdx >= SIN_BUFFER_SIZE Then
            Clear aryBuffer
            bytNextIdx = 0                    
        EndIf                 
        Set bitCheckBuffer
    Wend
With the 1 ms delay it works everytime, without the delay it always misses the first character. I am using 57600 baud.
~ Sy ~ is offline   Reply With Quote
Old 15th October 2009, 05:55   #96
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

Code has been working well, thanks Les!

I do have one question. I'm not sure exactly how to set the timeout value? I would like to set it to 100ms similar to how we used to set it in the HRSin command:

tempB = HRSin, {100,Timeout}

Only with this buffering code I imagine it is impossible to time out the HRSin command now.

Thanks,
PICnoob is offline   Reply With Quote
Old 15th October 2009, 07:40   #97
Tim
Super Moderator
 
Tim's Avatar
 
Join Date: Jan 2003
Location: london
Posts: 8,196
Tim is on a distinguished road
Default

Having a timeout on a serial buffer does not really make sense. It was written to negate the need to be hanging around in a wait routine
__________________
Tim
If in doubt read the manual
Tim is offline   Reply With Quote
Old 15th October 2009, 09:23   #98
crankshaft
Licensed User
 
crankshaft's Avatar
 
Join Date: Feb 2003
Location: Singapore
Posts: 948
crankshaft is on a distinguished road
Send a message via Skype™ to crankshaft
Default

Quote:
Originally Posted by Tim View Post
Also will had indicate data in on X so it will say when a chr 13 has arrived etc.
Hi Tim, I have scanned through the posts, but can't seem to find whether this was actually added.

I have 6 bytes of data being received with a start byte, 2 data bytes, and end byte and and I want to be able to verify that they've all been received before grabbing the data bytes.

i.e. "[AB]",13

How can I test for say the [CR] and then read the buffer contents if the buffer length = 5 ??

Many Thanks
crankshaft is offline   Reply With Quote
Old 15th October 2009, 13:04   #99
crankshaft
Licensed User
 
crankshaft's Avatar
 
Join Date: Feb 2003
Location: Singapore
Posts: 948
crankshaft is on a distinguished road
Send a message via Skype™ to crankshaft
Default

Hi;

I ended up with this:
Code:
dim bufBytes as Byte
dim cmdStr as string * 5

Clear cmdStr
bufBytes = HrsInBuffLen		' Read the Serial Buffer Rcv Bytes
If bufBytes > 4 Then
HSerIn [Str cmdStr\5]
CLEAR_SERIAL_BUFFER		
EndIf
Is there a better way ??
crankshaft is offline   Reply With Quote
Old 15th October 2009, 16:20   #100
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

Quote:
Originally Posted by Tim View Post
Having a timeout on a serial buffer does not really make sense. It was written to negate the need to be hanging around in a wait routine
In the scenario where noise is received, won't the buffering algorithm hang waiting for a transmission that will never be coming?
PICnoob is offline   Reply With Quote
Old 15th October 2009, 17:36   #101
Tim
Super Moderator
 
Tim's Avatar
 
Join Date: Jan 2003
Location: london
Posts: 8,196
Tim is on a distinguished road
Default

If there is noise all that will happen is the buffer will fill up with rubbish.
__________________
Tim
If in doubt read the manual
Tim is offline   Reply With Quote
Old 16th October 2009, 18:04   #102
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

Quote:
Originally Posted by Tim View Post
If there is noise all that will happen is the buffer will fill up with rubbish.
In our case we have a loop that must run at least 50 times per second, and it seems sometimes when you first plug the RS232 cable in, etc, it locks up. I noticed there are flags to set timeouts but no example of how to use them properly. Ideally I'd like to put in a 100ms timeout to verify if noise is causing our lockup.
PICnoob is offline   Reply With Quote
Old 17th October 2009, 01:38   #103
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

Was able to verify the interrupt routine is sticking, and as a test tried setting 'GEN' and PP1' in the main program, with no impact. Guidance appreciated.

Quote:
INIT_USART_INTERRUPT ' Initiate the USART 1 serial buffer interrupt
CLEAR_SERIAL_BUFFER ' Clear the serial buffer and reset its pointers

GEN = 10
PP1 = 10
PICnoob is offline   Reply With Quote
Old 21st October 2009, 00:23   #104
Alan R.
Licensed User
 
Join Date: Jan 2005
Location: California
Posts: 240
Alan R. is on a distinguished road
Default

Quote:
Originally Posted by ~ Sy ~ View Post
I've fixed it, but I've no idea why ?

I put some debug info inside the loop that calls HSRIn, and found that with the Print At statements in the loop, it always works and never misses the start byte.

With the 1 ms delay it works everytime, without the delay it always misses the first character. I am using 57600 baud.
- Your post was while I was on vacation so I didn't see it until now -

That is very interesting, I regularly loose the first two bytes - fortunately always the same chars - and I'm running at 115,000 baud.....

I do need to sort this so I'll post my results when I understand what's going on....

-Alan R..
Alan R. is offline   Reply With Quote
Old 21st October 2009, 03:48   #105
crankshaft
Licensed User
 
crankshaft's Avatar
 
Join Date: Feb 2003
Location: Singapore
Posts: 948
crankshaft is on a distinguished road
Send a message via Skype™ to crankshaft
Default

Hi;

Can I confirm whether the WAIT modifier will work with this routine ?

Thanks

EDIT
===

Looks like it does not, Tim any chance you can add this functionality ??


Quote:
A bit later I will add to the code, stuff like how much data is in the buffer and a wait for command so it only starts stuffing the buffer once the chars your looking for arrive.

Also will had indicate data in on X so it will say when a chr 13 has arrived etc.

Last edited by crankshaft; 21st October 2009 at 03:57.
crankshaft is offline   Reply With Quote
Old 21st October 2009, 06:12   #106
crankshaft
Licensed User
 
crankshaft's Avatar
 
Join Date: Feb 2003
Location: Singapore
Posts: 948
crankshaft is on a distinguished road
Send a message via Skype™ to crankshaft
Default

I just created a routine to try and simulate the WAIT modifier, but I am unable to catch the String I am searching for.

Problem is that my Serial Input is a dump from another device and it's a whole page of data (more than 100 lines), and I am trying to catch some data and read it which is in the early part of the dump.

But the early data in the buffer is being overwritten by the data received later, and I do not want to create a very large buffer as I only read this once during the bootup sequence and am only interested in about 15 characters in total, in fact I am trying to grab the device's IP address from the page dump.

I am able to catch the data I need using the normal Hserin command, however I need the buffer elsewhere in the program and I believe that you cannot switch between the normal hserin and the buffer hserin ?

So as I cannot store the entire page into a buffer, I need to try and read it in real time, and every time I see a Carriage Return I clear the buffer and read in that line before the buffer fills up.

Code:
        StartChr = 13
        waitStr = "IP addr " 
        StrLen = Len(waitStr) - 1
        
        Clear bufStr
        CLEAR_SERIAL_BUFFER

WaitSC:
        'Wait for the startChr and clear buffer if we get it
        Bytein = HRSIn
        If Bytein <> StartChr Then
            GoTo WaitSC
        EndIf
        CLEAR_SERIAL_BUFFER
WaitST:
        Bytein = HRSIn
        'If we receive the startChr again then restart
        If Bytein = StartChr Then
            CLEAR_SERIAL_BUFFER
            GoTo WaitSC
        EndIf
        
        ' Wait for the First STRING Character
        If Bytein <> waitStr[0] Then GoTo WaitST
        
        ' First Chr Found, Now compare restof string
        Found = 1
        bufStr[0] = waitStr[0]
        For i = 1 To StrLen
            Bytein = HRSIn
            If ByteIn <> waitStr[i] Then Found = 0 
            bufStr[i] = Bytein
            Print At 2,i,Bytein
        Next
        
        If Found = 1 Then
            Print At 1,1,"Found"
        Else
            Print At 1,1,"Not Found"
        EndIf
But of course this does not appear to work - any suggestions ??

Last edited by crankshaft; 21st October 2009 at 06:13.
crankshaft is offline   Reply With Quote
Old 21st October 2009, 08:29   #107
AlbertoFS
Licensed User
 
Join Date: Apr 2005
Location: Barcelona Spain
Posts: 40
AlbertoFS is on a distinguished road
Send a message via Skype™ to AlbertoFS
Default

Hello Pete,
Have try to count the UART Frame or Overrun?
You can sincronyze the buffer inside the interrupt routine with a semafor flag and a temp Variable. If there is not a StarChr in the UART the buffer do not start.
I write an example, I don't text it.

'RX UART Interrupt
If PIR1bits_RCIF = 1 Then
movlw 6
andwf RCSTA,W
bnz _Uart_Error
'------------------------------------------
if SincroFlag = 0 then
TempRCREG = RCREG
if TempRCREG = StartChr then
SincroFlag = 1
else
retfie fast
endif
endif
'-----------------------------------------
_USART_FSR1_Save = _USART_FSR1
Inc _USART_IndexIn
If _USART_IndexIn >= _USART_BufferSize Then
_USART_IndexIn = 0
EndIf
_USART_FSR1 = VarPtr _USART_RingBuffer
_USART_FSR1 = _USART_FSR1 + _USART_IndexIn
'----------------------
'INDF1 = RCREG
INDF1 = TempRCREG
'----------------------
_USART_FSR1 = _USART_FSR1_Save
retfie fast
'
_Uart_Error:
Clear RCSTAbits_CREN
Set RCSTAbits_CREN
inc UART_ERROR_COUNTER
retfie fast
'-----------------------------------

In your main program you can reset the flag and the buffer pointers when you get the tail of the frame.

Alberto
AlbertoFS is offline   Reply With Quote
Old 23rd October 2009, 03:14   #108
Alan R.
Licensed User
 
Join Date: Jan 2005
Location: California
Posts: 240
Alan R. is on a distinguished road
Default

Quote:
Originally Posted by ~ Sy ~ View Post
I've fixed it, but I've no idea why ?

With the 1 ms delay it works everytime, without the delay it always misses the first character. I am using 57600 baud.

I could use some insight.
I have a bug that seams identical to Sy's except that it is always the first two bytes that are corrupted after I transmit out using HRSout. The first received byte is always the same as the last transmitted byte and the second byte seams to always be a "7B" see below

6 7B 1 2 3 4 5 6 < first data after an HRSout xmit
BE EF 1 2 3 4 5 6 < Good data until the next xmit
BE EF 1 2 3 4 5 6 < More good data

The in this example, the expected string is "BE EF 1 2 3 4 5 6".

I have tried re-writing my code to avoid the HRSout command in case the issue is a re-used var but it didn't help.

Does any one have any ideas?
-Alan R..
I can not add a delay like since I have some large bursts of dat
Alan R. is offline   Reply With Quote
Old 24th October 2009, 17:20   #109
Alan R.
Licensed User
 
Join Date: Jan 2005
Location: California
Posts: 240
Alan R. is on a distinguished road
Default

I understand why the Received bytes get corrupted, or rather how to prevent it. I was setting up the EUSART registers every time I entered my RS232 Transmit subroutine. If I move those lines to the start of the program the problem is gone. That is strange behavior.

There is a tiny bug in the BUFFERED_USART.inc file:

Under the error handling section inside the interrupt, it traps on two errors but only handles one of them.

movlw 6 ' Yes. So Mask out unwanted bits
andwf RCSTA,W ' Check for errors
bnz _UART_ERROR ' Was either error status bit set?

bit 2 FERR: Framing Error bit
1 = Framing error (can be updated by reading RCREG register and receiving next valid byte)
0 = No framing error
bit 1 OERR: Overrun Error bit
1 = Overrun error (can be cleared by clearing bit CREN)
0 = No overrun error


Adding a ‘movf RCREG” inside the error handling section will clear the framing if necessary

_UART_ERROR:
movf RCREG ' Clear Framing error by reading RCREG
Clear RCSTA.4 ' Clear receiver status
Set RCSTA.4
retfie Fast


Alan R..
Alan R. is offline   Reply With Quote
Old 24th October 2009, 22:20   #110
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

Still hoping for some help on the timeout value... But a new issue came up.

We're using a 512 byte boot loader now, using RCREG commands for input to save space. The boot loader works great. But is there a way to use the buffered HSRIN for the main program without using it for the boot loader? It takes too much space for the boot loader. The loader header looks like this:

Quote:
Device = 18FXXXX
XTAL 8
BOOTLOADER = off
OPTIMISER_LEVEL 1

@config_req
@__config config1h, OSC_IRCIO_1 & FCMEN_OFF_1 & IESO_OFF_1
@__config config2l, PWRTEN_OFF_2 & BOREN_OFF_2 & BORV_20_2
@__config config2h, WDTEN_OFF_2 & WINEN_OFF_2 & WDPS_1_2
@__config config3h, MCLRE_OFF_3
@__config config4l, STVREN_OFF_4 & LVP_OFF_4 & DEBUG_OFF_4
'@__config config5l, CP0_ON_5 & CP1_ON_5 & CP2_ON_5 & CP3_ON_5
'@__config config5h, CPB_ON_5 & CPD_ON_5

'EEPROM
EData 1,0,3,40,6.00,7.50 '0 = boot-load flag

'Oscillator settings
OSCCON = %01111111 '8 Mhz internal oscillator
DelayMS 300 'let oscillator stabilize

'I/O port settings
TRISA = %01011111
TRISB = %00000000
TRISC = %10011001 'Pin 18 is input (Rx), 17 is output (Tx), and 15-14 are inputs (mapsw1 and mapsw2).
ANSEL0 = %00001111 'Pins 2,3,4,5, are analog inputs; they are multiplexed to the AD converter. Pins 6,9,10 are digital inputs.

'BOOTLOADER
'--------------------------------------------------------------------------------------------------------------------------------------------------------
'--------------------------------------------------------------------------------------------------------------------------------------------------------

'Serial settings
HSERIAL_BAUD = 19200 ' Set baud rate to 19200
HSERIAL_RCSTA = %10010000 ' Enable serial port and continuous receive
HSERIAL_TXSTA = %00100100 ' Enable transmit and asynchronous mode
HSERIAL_CLEAR = On ' Enable Error clearing on received characters
Symbol RCIF = PIR1.5

'Enter bootloader?
If ERead 0 = 0 Then
@GoTo 0x200
EndIf
Then our main program has a "PROTON_START_ADDRESS = $0x200" in it.
PICnoob is offline   Reply With Quote
Old 27th October 2009, 19:19   #111
PICnoob
Forum User
 
Join Date: May 2008
Posts: 33
PICnoob is on a distinguished road
Default

It appears the problem with the boot-loader is to do with interrupt vector remapping. Will research and make a new thread if needed. So disregard above post.

On the timeout issue, another programmer suggested the hardware interrupts are interfering with PWMs, which would cause problems in our case. Will try to explore it once I get the interrupts working again.
PICnoob is offline   Reply With Quote
Old 31st January 2010, 19:31   #112
Eriond
Licensed User
 
Eriond's Avatar
 
Join Date: Sep 2005
Location: Stockholm, Sweden
Posts: 82
Eriond is on a distinguished road
Post Timeout, anybody?

I have to join PICnoobs query abuot the undocumented "timeout" feature. Having very little knowledge of asm, I can't really figure out the .inc file...
Using the original syntax HRSIn {Timeoutperiod, Timeoutlabel}, Variable I can get my code to compile without errors, but I can't make it to behave properly.

Tim questioned the neccesity of a timeout feature when you have a buffered handler, but I need it to detect "link lost" conditions. At the moment my code hangs if the link is removed/interrupted.

As always, any and all commets are highly appreciated!
Code:
'****************************************************************************
'*                                                                          *
'*  Application: Closed loop over Fibre receiver                            *
'*  Date:        2010-01-28                                                 *
'*                                                                          *
'****************************************************************************

  Device 18F1320
		
  Declare Xtal  		8
  Declare Optimiser_Level	3		' Full optimisation
  Declare Bootloader	OFF
  Declare Hserial_Baud 	1200		' Set baud rate for USART 1
  Declare Hserial_RCSTA 	%10010000	' Enable serial port and continuous receive
  Declare Hserial_TXSTA 	%00100000	' Enable transmit and asynchronous mode
  Declare All_Digital		True
      	
  Dim Sync As Byte                		' To keep packets synchronized
  Dim i As Byte				' incremental integer...
  Dim InData[6] As Byte		   	' Used for serial comm.
  Dim LoopCount As Byte			' A simple message counter
  Dim LCheckSum As Byte			' Locally calculated checksum
  Dim Suspicious As Byte			' A counter to keep track of how many good/bad packets have been received
				
  Include "BUFFERED_HSERIN2.INC"  ' Load the USART 1 interrupt handler and buffer read subroutines into memory

  Symbol StatLED = PORTA     
  Symbol LnkGreen = PORTA.0		' Green part of dual-colour LED
  Symbol LnkRed = PORTA.1	   		' Red part...
  Symbol TempWarn = PORTA.2		' Temperature high warning LED
  Symbol Alarm = PORTA.3			' Sum alarm LED
  Symbol Relay1 = PORTB.1
  Symbol Relay2 = PORTB.2
  Symbol Relay3 = PORTB.3
  Symbol Carry = STATUS.0			' Maybe useful to detect HRSIn timeouts?
	
  OSCCON.4 = 1                    		' Set up internal oscillator for 8MHz
  OSCCON.5 = 1
  OSCCON.6 = 1
  'INTCON2.7 = 0				' Activate PORTB pullups ("PortB_Pullups" declare doesn't work in the beta)

  TRISA = %00000000			' Set all of the RA0 as outputs
  TRISB = %00010001              		' Set all portb pins as outputs except pin 10 (RX data) and 8 (Button)

  DelayMS 200				' Stabilize PIC
  Sync = 0                       			' Clear the packet synchronization
  Low StatLED				' Clear all the status lights
  Low Relay1				' Open all of the relays
  Low Relay2
  Low Relay3
  High LnkRed                    			' Light a LED to show we're alive...

  INIT_USART_INTERRUPT			' Initiate the USART 1 serial buffer interrupt 
  CLEAR_SERIAL_BUFFER			' Clear the serial buffer and reset its pointers
				
MainLoop:	
  DelayMS 10
  Sync = Sync + 1				' Counter to keep track of timeout interval
  If Sync > 10 Then Low LnkGreen		' apx 100ms after last packet, shut off the link led to make it flash 
  If Sync > 50 Then GoTo Timeout		' In case the counter reaches 500ms, handle a timeout
  
  If HRSIN_BUFFLEN < 6 Then GoTo MainLoop
  If HRSIN_BUFFLEN > 6 Then 		' This should only occur right after connecting/starting the unit
    CLEAR_SERIAL_BUFFER			' Since there are too many chars in the buffer (maybe junk?); discard them
    Sync = 0				' Clear the timeout counter
    GoTo MainLoop				' I personally don't like exiting if..endif constructs this way, but...
  EndIf
	
  'In case we made it this far, there's probably data to take care of in the buffer
  Sync = 0				' Clear the timeout counter
  High LnkGreen				' In case this wasn't done before...
  'The incoming packet should be like this: 170, 170, MsgCounter, SensePoints, Temperature, CheckSum
  For i=0 To 5
    HRSIn {500, Timeout}, InData[i]
  Next i
	
  'From this point on, we have apx 300ms to do whatever we need to do before looping back
	
  LCheckSum = (170 + 170 + InData[2] + InData[3] + InData[4]) // 256
  If InData[0] = 170 And InData[1] = 170 And LCheckSum = InData[5] Then
  'Only handle data that has its checksum verified!
    Low LnkRed				' We are in sync, so turn the amber (red+green) into green alone
    GoSub Parse				' Handle the data
    If Suspicious > 0 Then Suspicious = Suspicious - 1	' Decrease the counter for every verified packet
    If Suspicious = 0 Then Low LnkRed		' Handle the Link LED to show proper operation
  Else					' Either the checksum or header failed verification
    Suspicious = 10				' Turn the link LED amber (red+green) for apx 4 sec
    High LnkRed
  EndIf	
  GoTo MainLoop

Parse: 		
  LoopCount = LoopCount + 1		' Our local packet counter should be in sync with the remote side
  If LoopCount <> InData[2] Then
    Suspicious = 10
    High LnkRed
    LoopCount = InData[2]	' Synchronize local counter with remote side
  End If
	
  If InData[4] > 40 Then			' Light the led if temperature rises above 40°C
    High TempWarn
  Else
    Low TempWarn
  EndIf
		
  If InData[3] > 0 Then			' Give local feedback 
    High Alarm
  Else
    Low Alarm
  EndIf
  PORTB = InData[3]			' Set the relays
	
  Return
		
		
Timeout:
  CLEAR_SERIAL_BUFFER
  Sync = 0
  Low LnkGreen				' A timeout means lost link; should be indicated by a red-only link LED
  High LnkRed
  Suspicious = 10
  GoTo MainLoop
/Eriond
Eriond is offline   Reply With Quote
Old 6th February 2010, 20:17   #113
hassawfaa
Licensed User
 
Join Date: Mar 2008
Location: From Roots
Posts: 210
hassawfaa is on a distinguished road
Default

If you interface your code with a PC then I have a suggestion to check the DTR then if you open the port the DTR will be high and if you close the port then DTR will be low.
hassawfaa is offline   Reply With Quote
Old 9th February 2010, 14:28   #114
wirecut
Licensed User
 
wirecut's Avatar
 
Join Date: May 2008
Location: Milano - Italy
Posts: 160
wirecut is on a distinguished road
Default RB0 interrupt fail to run.

I'm using a modified version of the serial buffer modified by Tim for the buffer. Attached find it for convenience.

This great transparent buffer works really well. I'm using it at 115,200bps on a 18F550 and never misses a character.

Thanks Les & Tim.

Now I have a problem; if I introduce into the program an RB0 interrupt section, the program no longer works.

Of course the program that handles the interrupt RB0, without transparent serial buffer, works perfectly.
Follow the non working RB0 interrupt, with transparent buffer.

Code:
Device = 18F2550

XTAL = 20
PORTB_PULLUPS true

OPTIMISER_LEVEL = 6                           ' Full optimisation   
ALL_DIGITAL = True                            ' Make PORTA and PORTE digital inputs

'------------- Declares USART  --------------------
HSERIAL_RCSTA  = $90                      'Set receive register to receiver enabled
HSERIAL_TXSTA  = $24
HSERIAL_SPBRG  = 10                      ' set serial bps 115200 Bauds         -1,357%       
HSERIAL_CLEAR  = On

'------------- Include ------------------------------
Include "HRsin_Tim_Les.inc"  ' Load the interrupt handler, buffer read subroutines with IncCounter

'-------------- Initilize the USART serial buffer Interrupt -------------------------
INIT_USART_INTERRUPT             ' Initiate the USART 1 serial buffer interrupt 
CLEAR_SERIAL_BUFFER              ' Clear the serial buffer and reset its pointers

Symbol GRE     = PORTB.4 : Output PORTB.4     'LED green
Symbol BEEP    = PORTC.1 : Output PORTC.1     'Beeper
Symbol BootSw  = PORTC.0 : Output PORTC.0     'BootSwitch
Symbol CTS     = PORTA.5 : Input  PORTA.5     ' 0 = not clear    1 = Clear To Send
Symbol ButtonA = PORTA.2 : Output PORTA.2     ' ButtonA     0 = button pressed
Symbol ButtonB = PORTA.3 : Output PORTA.3     ' ButtonBail reset 0 = button pressed
                                             
Dim ByteIn      As Byte         'Rx incoming Byte
Dim Command     As Byte         'reconstructed command ready for parsing and execution       
Dim FirstRec    As Byte         'used as first receved byte from USART decads Debug
Dim First       As Byte         'used as first receved byte from USART decads
Dim Second      As Byte         'used as first receved byte from USART units
Dim DueCar      As Byte         '0 to 254 valid command. 255=command executed

Dim InvSync     As Word         'increment every sync pulse  ___|___
Dim PrInvSync   As Word         'previous value of InvSync; used to execute only one time for InvSync period
Dim Pattern     As Word         'Received eye status
Dim N           As Byte         'generic
Dim IncCounter  As Word         'IncCounter

' Interrupt symbols                
Symbol GIE  = INTCON.7              ' Global Interrupt Enable
Symbol RBIF = INTCON.0              ' RB Port Interrupt Flag
Symbol RBIE = INTCON.3              ' RB Port Change Interrupt Enable     
Symbol INTE = INTCON.4              ' External RB0 Interrupt Enable
Symbol INTF = INTCON.1              ' External Interrupt Flage

'------------- BOOTLOADER SWITCH -----------------------------------------
DelayMS 50                      ' allow pic to Stabilyze                      
High  BootSw                    ' connect the micro to the user application like Terminal
DelayMS 100                     ' allow relays contact to stabilyze  

'--------------- INITIAL SET UP --------------------------------
High ButtonA      ' ButtonA
High ButtonB     ' Fail reset
High GRE         ' Greeen live LED
Low  BEEP        ' Sound the beeper

'********** BAT section *******************************************************
'While GIE=1 : GIE=0 : Wend         ' make sure to disable the Global interrupt

HRSOut "- file: RB0_interrupt_2550-F", 13, 10,
For N = 1 To 5
  High GRE
  High BEEP
  DelayMS 40
  Low GRE
  Low BEEP
  DelayMS 40
Next N

''****** INTERRUP INIZIALIZATION - Clear interrupt sources flags and enable ********
While GIE=1 : GIE=0 : Wend         ' make sure to disable the Global interrupt
INTF = 0                            ' Clear INT Flag
INTE = 1                            ' Enable External RB0 Interrupt
GIE=1                               ' Enable Global interrupt ( 0 disable)
ON_Interrupt Isr                 ' If interrupted go to Isr         
HRSOut "Begin:", 13, 10

GoTo Begin                          ' Jump over ISR

'****** RB0 interrupt service routine ***************************
Isr: 
  High BEEP 
  Inc InvSync
  Low BEEP                                   
  INTF = 0                             ' Clear INT Flag (be ready for the next)
  Context Restore

'****** MAIN PROGRAM HERE ***************************
Begin:
  If CTS = 1 Then
     SerIn PORTA.0\PORTA.1, 16390, [Pattern]     '38400          'is the maximum allowable speed for 877 20 MHz clock
     HRSOut HEX1 Pattern 
     High PORTA.1
  EndIf
  If _USART_BUFFER_COUNT > 0 Then
    GoSub  Receive
  EndIf
GoTo Begin

'******* RECEIVE CHARACTER ***********************************************  
Receive: 
  HRSin ByteIn                   ' Read data from the serial buffer
  HRSOut ByteIn                  ' Echo the character to the terminal
    If ByteIn = "@"  Then         'If "@" character is received, means command string
      GoSub ValidCommand              ' go to chek if is a valid command
    EndIf
    If Command <> 255 Then GoSub parse_command 
Return

'******* COMMAND SELECTION ***********************************************                                                                                
ValidCommand:
  HRSin ByteIn                   ' Read data from the serial buffer
  If ByteIn = "[" Then 
    HRSin ByteIn                   ' Read data from the serial buffer
    LookDownL ByteIn,["0123456789ABCDEF"],FirstRec     'cerca l'equal compare del carattere ricevuto e assegna il valore di posizione
    First = FirstRec * 16         'contiene la posizione nella stringa di lookup e genero le decine
    HRSOut ByteIn                  ' Display the byte received from the serial buffer
    HRSin ByteIn                   ' Read data from the serial buffer
    LookDownL ByteIn,["0123456789ABCDEF"],Second  
    DueCar =  First + Second       'genera il valore numerico ricevuto and assign to "duecar"
    'HRSOut "firstrec=", Dec firstrec, "  first=", dec first, "  second=", Dec second, "  duecar=", dec duecar, 13, 10
    HRSOut ByteIn                  ' Display the byte received from the serial buffer
    HRSOut "-"
 EndIf
  Command = DueCar                 ' a valid command should be generated ;-)
Return
'******************** PARSE the command ****************************************** 

parse_command:

' ********* press  section *******************************************************
  If DueCar = $07 Then GoSub Pre_07:          'Set Mute switch to ON   
  If DueCar = $0C Then GoSub Pre_0C:          'Press ButtonA button
  If DueCar = $0D Then GoSub Pre_0D:          'Set Sound switch to ON
  If DueCar = $11 Then GoSub Pre_11:          'Press Fail Reset button 
  
' ********* release section ******************************************************
  If DueCar = $87 Then GoSub Rel_87:          'Set Mute switch To OFF  
  If DueCar = $8C Then GoSub Rel_8C:          'Release ButtonA Button
  If DueCar = $8D Then GoSub Rel_8D:          'Set Sound switch To OFF
  If DueCar = $91 Then GoSub Rel_91:          'Release Fail Reset Button 
  
' ************ self extinguishing ********************************************************                                
  If DueCar = $9D Then GoSub Rel_9D:          'Microcontroller reset      
  If DueCar = $A6 Then GoSub Rel_A6:          'BEEP 300 mS                   
  Command = 255
Return  
'******************** EXECUTE  the command recognized *****************************
'*** press section *********************

Pre_07:                                       'Set Mute switch to ON   
  High BEEP
  HRSOut "(Pre_07)", 13, 10                                                                 
  'here the action
  HRSOut "Mute switch To ON", 13, 10
  Low BEEP
Return

Pre_0C:                                      'Press ButtonA button
  High BEEP
  HRSOut "(Pre_0C)", 13, 10   
  Low ButtonA
  HRSOut "Press ButtonA Button", 13, 10
  Low BEEP
  DelayMS 100          ' to be decided if  remain self estinguish
  High ButtonA
Return

Pre_0D:                                       'Set Sound switch to ON
  High BEEP
  HRSOut "(Pre_0D)", 13, 10   
  'here the action
  HRSOut "Sound switch To On", 13, 10
  Low BEEP
Return
                                                
Pre_11:                                       'Press Fail Reset button 
  High BEEP
  HRSOut "(Pre_11)", 13, 10           
  Low ButtonB
  HRSOut "Press ButtonB", 13, 10
  Low BEEP
  DelayMS 10        ' to be decided if remail self estinguish
  High ButtonB
Return

'*** release section *********************
Rel_87:                                       'Set Mute switch To OFF 
  High BEEP
  HRSOut "(Rel_87)", 13, 10                                                                 
  HRSOut "Mute switch To OFF", 13, 10
  Low BEEP
Return

Rel_8C:                                       'Release ButtonA Button
  High BEEP
  HRSOut "(Rel_8C)", 13, 10 
  High ButtonA  
  HRSOut "Release ButtonA", 13, 10
  Low BEEP
Return

Rel_8D:                                       'Set Sound switch To OFF
  High BEEP
  HRSOut "(Rel_8D)", 13, 10   
  'here the action
  HRSOut "Set Sound switch To OFF", 13, 10
  Low BEEP
Return

Rel_91:                                       'Release reset Button 
  High BEEP
  HRSOut "(Rel_91)", 13, 10           
  High ButtonB
  HRSOut "Release Fail Reset Button", 13, 10
  Low BEEP
Return

'************ self extinguishing ****************************  
Rel_9D:                                       'Microcontroller reset H9D
  High BEEP
  HRSOut "(Rel_9D)", 13, 10   
  HRSOut "Going to PIC reset", 13, 10
  Low BEEP
  DelayMS 200 
@GoTo 0         
    'RESET  Proton system vars ... seems a reset but not real MCLR reset
Return

Rel_A6:                                       'BEEP  
  High BEEP
  HRSOut "(RelA6)", 13, 10   
'  DelayMS 300
Sound BEEP, [100, 30]
  HRSOut "(Beep)", 13, 10 
  Low BEEP
Return
I am using the PDS at 3.2.5.5. relase.

Do you have any suggestions?

Ciao

Leo
Attached Files
File Type: zip HRsin_Tim_Les.zip (2.9 KB, 37 views)
wirecut is offline   Reply With Quote
Old 11th February 2010, 20:06   #115
galeforce9
Licensed User
 
Join Date: Sep 2002
Location: Notts
Posts: 136
galeforce9 is on a distinguished road
Default

Hi Leo

You need to edit the .inc file for the serial and find the line

' <<< Other Interrupt Conditions and Code here >>>

and place your RB0 code at this point.

Ignoring high/low ints which is another option you have just one interrupt routine. When it occurs you then test each int flag and branch accordingly running your code for that particular interrupt.

Hope that helps.

Ian
galeforce9 is offline   Reply With Quote
Old 14th February 2010, 09:32   #116
wirecut
Licensed User
 
wirecut's Avatar
 
Join Date: May 2008
Location: Milano - Italy
Posts: 160
wirecut is on a distinguished road
Default

Hi Ian,

thanks for your good suggestion.

Can I ask to you if you have a working example in order to understan how insert the other interrupt code, not exclusively for RB0?

Ciao


Leo
wirecut is offline   Reply With Quote
Old 16th February 2010, 11:05   #117
wirecut
Licensed User
 
wirecut's Avatar
 
Join Date: May 2008
Location: Milano - Italy
Posts: 160
wirecut is on a distinguished road
Default

Hi,

I'm using the last official release of PDS+ 3.2.5.5.

On the source code, Les say that his serial buffer is for "version 3.3.0.0 Onwards".

Can I have problems to use the transparent serial buffer in that condition?

Ciao

Leo
wirecut is offline   Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Font Converter FabioPedro The Lounge 7 29th May 2007 19:22
Pprint FabioPedro The Lounge 18 21st April 2007 18:09
Right2Left Alignment On a GLCD SELCUK Proton Plus Compiler v3 2 11th April 2007 07:40
Is this correct ??? glcd tbillion1 Proton Plus v2.1.5.3 General Discussion 4 19th September 2006 11:41
Pprint CALCO Proton Plus v2.1.5.3 General Discussion 2 13th July 2005 18:01


All times are GMT +1. The time now is 11:30.



Powered by vBulletin® Version 3.8.2
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Copyright © Crownhill Associates Limited 2002 - 2009