Wednesday, August 4, 2010

PIC to Windows Interface - (Hexapod Part 5)

The full source code can be found here.

One of the tasks I wanted to achieve fairly early in the piece was the communication between the PC and the PIC. This is fairly simple with any of the PICs that have a USART built in. In fact its trivial. Just configure the port and send a byte. Once its sent, send the next byte.

The following code initialises the USART to asynchronous mode, 9.6kbps
movlw B'10100100' ;initialize USART
movwf TXSTA ;8-bit, Async, High Speed
movlw .25
movwf SPBRG ;9.6kbaud @ 4MHz

movlw B'10010000' ;bit7 = SPEN, bit4 = RX Enable
movwf RCSTA

Sending the data is then simply load the byte into the TX register and wait for it to be sent

SendPositions:

;continuously send servo positions to PC

btfss SEND_STATUS, 0    ;wait until the interrupt changes something
goto $-2
BCF SEND_STATUS, 0      ;reset the 'something changed' flag

movlw "A" ;A means the next 3 bytes are servo positions
movwf TXREG ;next line
btfss TXSTA,TRMT ;wait for data TX
goto $-2

movf SERVO0POS, w ;move data into TXREG
movwf TXREG ;next line
btfss TXSTA,TRMT ;wait for data TX
goto $-2

movf SERVO1POS, w
movwf TXREG ;next line
btfss TXSTA,TRMT ;wait for data TX
goto $-2

movf SERVO2POS, w
movwf TXREG ;next line
btfss TXSTA,TRMT ;wait for data TX
goto $-2

goto SendPositions

The above code sends the ServoPosition packet to the PC. The servo position packet is identified by the first byte being an 'A'. This is just a character I chose at random, 'A' seems like a good place to start. When the software on the PC sees an 'A' it knows the next 3 bytes will be the positions of the 3 servo connected to the PIC.

The PC software, written in C#, opens the serial port and listens to all bytes coming in. These bytes are fed into a packet factory that looks for the 'A' character. When this character is seen it records the next 3 bytes and then creates a "ServoPosition" packet. This packet is then sent, via an event to anything that is listening, in this case a windows form.


The form outputs the data in two forms, a graphical form and a textual form. The software on the PIC current decrements the servos positions each time the interrupt runs so the servos are constantly moving through their full range. The next step is to set the PIC up to receive data from the PC and allow the user to move the scroll bars to position the servos.

No comments:

Post a Comment