# Serial comms PIC to PC

#### fyee

Joined Mar 7, 2010
16
my project also something like this, but I'm using weight sensor,so my output from PIC will be weight. And, I need to announce the weight by using VB program.
Is it for the same concept for my project? I want to save my output from PIC in PC but then I don't know how to.
Can anyone tell me how to do?

#### beenthere

Joined Apr 20, 2004
15,819

Accepting a serial input to a PC is pretty simple, and clearly explained in the VB literature.

You can get better help if you give significant details about the PIC you are using, the language you are coding in, and the problem you are having. You can also visit the Microchip site and find many programming examples.

#### Harrington

Joined Dec 19, 2009
85
Not quite as easy as you think !! First you have to know how to use serial routines and that depends on what language you are using Secondly,you have think about whether you going to use asynchronous or synchronous communications or you could use SPI interface to PC this depends entirely on your programming skills IE can you progam In C Assembler or can you program in VB and Pic Basic or are you going to use something like Picc Lite

If your going to use assembler then you need to understand Bit Banging
Suggest Mike Pedro's page very good explanations on there

To start with i would suggest that you use a parallel port instead rather than RS232 straight away I'm assuming that you are using external AD converter via PORT A and Port B used as Output in this instance

If you do it this way then you wont need to worry about MScomm32 but instead use InputOUT 32.DLL which you simply drop into your Windows\ System32 folder

You then need to take into consideration that what the pic sends out is binary and you need to convert that into byte MSB LSB You need a max232 in between the pic device and the PC so that you can have level shift and then you also need to decide on protocol for Rs232 what handshaking will you use bits stop bits odd even parity

Looks easy It takes quite a while to even understand how to do this

So here is a snippet of code I wrote for operating 8 relays from a pic with a return signal back to the Vb program telling me that the pic has received the byte and that relays are in operation in other words the byte has been transferred to Port B

Language used PIC Basic Pro

This example uses MScomm32
Make sure you put the MSCOMM32.OCX in the Windows / System 32 Directory
'****************************************************************
'* Name : SerialReciever.BAS *
'* Author : [MD Harrington 55 Rushet Road London BR5 2PS] *
'* Notice : Copyright (c) 2009 [MD Harrington] *
'* Date : 15/08/2009 *
'* Version : 1.0 *
'* Notes : RS 232 data received via max232 for pic 84A *
'* : *
'****************************************************************
Device 16F84A

Config XT_OSC , WDT_OFF , PWRTE_OFF, CP_OFF

Declare XTAL 4
Symbol RS_IN PORTA.0 ' makes porta.0 input to pc Recieve data pin 2 dtype on pc socket
Symbol RS_OUT PORTA.1 ' makes porta.1 output to pc transmit data pin 3 dtype On pc socket
Symbol T_9600 9600 ' 8-bit no parity inverted
Symbol XON 17 ' flow control allows transmitt
Symbol XOFF 19 ' flow control stops transmit

Declare RSIN_PIN RS_IN 'TX data from pc arrives to this pin via max232
Declare RSIN_MODE TRUE 'Mode is inverted data because we are using a max232 the data is inverted when it arrives
Declare RSOUT_PIN RS_OUT 'Our transmission PIN for serial data
Declare RSOUT_MODE TRUE ' defaults to INVERTED for use without MAX232
Declare SERIAL_BAUD 4800
Declare RSIN_TIMEOUT 3000

Dim TX_Start As Byte
Dim TX_Stop As Byte
Dim endln As Byte
Dim rcbuffer As Byte
Dim oldVal As Byte
Dim newVal As Byte
Dim rx_Flag As Bit

init: ALL_DIGITAL = TRUE 'set ports to all digital

' setup the ports on the pic device

'initialise XON_XOFF protocol

TX_Start = XON
TX_Stop = XOFF
endln = 13
rx_Flag = 0 'rx_Flag for detecting fisrttime reception of commands

DelayMS 255 ' give pic time to settle down and max232 to stabilise total delay 510 ms apprx 1/2 minute

' bits 4 = input, 3 = output, 2 = input, 1 = output, 0 = input,
' binary equivalent = 0001 0101

PORTA = 0 ' clear porta

TRISB = $00 ' make all pins on portb output PORTB = 0 ' ensure no output on portB oldVal =$00
PORTB = oldVal

RXBegin: rcbuffer = $00 RSIn {to_Timeout}, rcbuffer 'test for first time reception and set flag to 1 Select Case rx_Flag Case 0 newVal = rcbuffer 'put this into newVal PORTB = newVal ' place this on portB to operate relays oldVal = PORTB rx_Flag = 1 ' finished testing for firstime reception Case 1 newVal = rcbuffer ' assign newVal to rcbuffer newVal = oldVal ^ newVal 'logically XOR the two together PORTB = newVal oldVal = PORTB End Select TXBegin: DelayUS 255 RSOut BIN oldVal 'transmitt the result back to the main DCE so that this can be processed DelayUS 50 GoTo RXBegin 'start process again to_Timeout: GoTo RXBegin Thats a simple example remember that the RSIN blocks untill byte recieved ** Important i would think in your project case ** Any Other questions feel free to leave me a note #### Harrington Joined Dec 19, 2009 85 To Follow for you here is part of the VB code You could also use Java up to you but I think you will find this difficult to start with Also if you use your brains here you could also give your project the edge by writing a server implementation and a client implementation such that after receiving your temperature readings you can then send this via server TCPIP socket back to client just a nice little extra edge on other people but that's obviously your choice Pay attention to important comments here Dim rcbuffer() As Byte ' The important Byte Array ' set the properties of mscomm1 With MSComm1 .CommPort = 1 .Handshaking = comXOnXoff .Settings = "4800,n,8,1" .RTSEnable = True .InputMode = comInputModeBinary ' very important this if you get this wrong you get garbage back .InputLen = 0 .InBufferSize = 1 '2 single byte .OutBufferSize = 1 ' limit this to one byte .NullDiscard = True .RThreshold = 1 End With @ Deal with MsComm events mentioned in VB forums Bear in mind this for a relay board not temperature however the principle is more or less the same Take note that I use a byte array which has no dimensions "Interesting point here took me hours to find this out as well !! Private Sub MSComm1_OnComm() Dim buffer As String ' holds our binary number returned from the relay board Select Case MSComm1.CommEvent Case comEvReceive rcbuffer() = MSComm1.Input 'populates the array with byte returned from the relay board Remember Its serial data so its bit shifted in hence the array grows in size Important as is setting the Input buffer size on MScom control CTS RTS LINES and events come into play here Not to difficult but also not easy !! For I = 0 To UBound(rcbuffer) ' convert this to a string will hold bin representation of byte recbuffer = recbuffer & Chr$(CDec(rcbuffer(I)))

Next I

' after we get the value back from portb on the relay board we then toggle
' the led to on or off state

toggleLeds lastPressedIndex, recbuffer ' this function is not here for you to see but you can work out what I'm doing

recbuffer = "" ' reset the buffer to null so that we don't mix up characters

Case comEvCTS
MsgBox "CTS Status = " & MSComm1.CDHolding

Case comEvDSR

MsgBox "DSR Status = " & MSComm1.DSRHolding

Case comEvRing

MsgBox "Ring Status = " & "Ring Detected"

End Select

End Sub

PS *********** Hope this helps you **************

Last edited:

#### Harrington

Joined Dec 19, 2009
85
Nearly forgot Id better show you how to send data as well via MSCOMM32

Public Function sendData(ByVal swNumber As Integer)

If MSComm1.PortOpen = False Then
MSComm1.PortOpen = True
End If

If MSComm1.PortOpen = True Then 'ensure the port is open

TxBuffer(0) = swNumber ' We Only use the first element here
MSComm1.Output = TxBuffer() ' Note!! you send the whole array i ' in one go This is where you think you have to cycle through the array to do this NOT THE CASE MSCOMM32 does this for you !!

Also drove me nuts trying to work out why i couldnt get this to 'work as well i think about two days pulling my hair out over this and i 'haven't got much left either lol !!

End If

End Function

So that should now get you more or less on your way or at least started in the right direction

#### fyee

Joined Mar 7, 2010
16

Accepting a serial input to a PC is pretty simple, and clearly explained in the VB literature.

You can get better help if you give significant details about the PIC you are using, the language you are coding in, and the problem you are having. You can also visit the Microchip site and find many programming examples.
Thanks for moving the thread for me.

The PIC I'm using is 16F877A,writing in C language. The output I got from PIC is actually in bit value from 0 to 1023. The problem I'm facing now is, I want to get the bit value from PIC to PC so that I can use it in VB. Let say, if VB gets the signal of 1010 which is equal to 2Kgs, it will announce 2Kgs itself.
I'm using a laptop which doesn't have a serial port, so how am I converting it to USB port? and I heard my friend said it might be different if the data send to USB.

I'm not so familiar with all the programmings, so really need helps from all the experts here.

Thanks so much.

#### fyee

Joined Mar 7, 2010
16
So here is a snippet of code I wrote for operating 8 relays from a pic with a return signal back to the Vb program telling me that the pic has received the byte and that relays are in operation in other words the byte has been transferred to Port B

Language used PIC Basic Pro

This example uses MScomm32

Thats a simple example remember that the RSIN blocks untill byte recieved ** Important i would think in your project case **

Any Other questions feel free to leave me a note
Is this C Assembly or C language?
I'm using C language for the weighing sensor. And, I want to add the program for the communication from PIC to PC,so how do I add?

Last edited:

#### fyee

Joined Mar 7, 2010
16
This is the 10 bits value that you collected from your ADC. You will Tx it to your PC with two bytes. First will contain the low byte (of the 10 bits) and the second will contain the high byte. Once these two bytes are in the PC you will recombine them [(high byte * 256) + low byte] and you will apply all the maths necessary to convert the ADC reading into weigth.
I don't really understand this.

Yea I got a converter for the 232.

#### Markd77

Joined Sep 7, 2009
2,806
The AD converter has a range of 0-1023 which is too big to be stored in an 8 bit register (maximum 255) or sent over serial as a single byte (also 8 bit).

I've got a USB-rs232 converter and using it is no different to using a built in serial port. The only minor difficulty is figuring out which COM# it is.

#### fyee

Joined Mar 7, 2010
16
I've got a USB-rs232 converter and using it is no different to using a built in serial port. The only minor difficulty is figuring out which COM# it is.
I've no problem in figuring out which COM# it is as I used the converter for PLC too.
I'm really sucked in PIC micro-controller and C programming ,so I really need someone to guide me and teach me how to include the program for the serial communication in PIC16F877A.

#### Boo

Joined Oct 27, 2009
40
PIC side: As previously discused. Measure ADC -> Send out both bytes Via Rs232 to the max232
Max232: Takes 5V signals and converts them to +-12V
RS232 to usb: Creates a virtual COM port on your computer and accepts the rs232 data from the max232
VB program: Just drag a serial COM onto your form, and after the driver is installed for the previous step, select that one. Make sure you are using the same baud rate etc.
Do byte low + (byte high *256) = int then convert appropriately.

In a few days this will all make sense, before trying to do all of this, simply send 1 byte to your PC repeatedly and try to make it appear on a text box or message box.

Good luck

P.s. here's some inspiration :

http://electrobird.net/PIC Projects/2d Accelerometer.html

#### Harrington

Joined Dec 19, 2009
85
Ive been doing some research for you because I'm also looking at this myself for another project that I want to build

After lots of reading and maybe one or two steps further I came across this for you which might help

Good explanations here for you if you want to understand more with regards to USB comm and Usb to serial conversion

Looking at what you have written you must have a fair knowledge of C so it will hopefully make some sense to you
Best place to start is with the USB1.1 standard

http://www.usb.org/developers/docs/

Or there is an alternative to this and that is JUSB or Java USB although Ive not tested this with windows the reports dont seem to give very good write ups however If you don't try you never find out I guess so Im going to have a play tonight see how far I can get with this http://jusb.sourceforge.net/

Good luck with this

Or you could start here
http://www.beyondlogic.org/usbnutshell/usb6.htm#SetupPacket

http://www.beyondlogic.org/usbnutshell/usb7.htm#PIC16F876Example

Also you can get a usb to serial flat pack IC and driver form this site

http://www.ftdichip.com/

Diagrams for pic to FTDI Interface you can find here

http://www.ianstedman.co.uk/Projects/PIC_USB_Interface/PIC_USB_SchematicV2.png

Here are some details for you hope this helps you further could be a very good excersise and prove very interesting if you want to learn how to write your own driver files for USB for windows

Last edited:

#### fyee

Joined Mar 7, 2010
16
So means, that will be different if I write my program for serial communication then I connect the serial port to USB-to-serial converter? since in the end it will go to USB port.

#### retched

Joined Dec 5, 2009
5,208
No, you will go from the serial from the chip to usb. Then usb right into your PC.

Basically you will be making your device speak USB That way, you need no converters in the outside world. If you wanted to take your device to a friends house, you wouldn't need to install a RS232 to USB cable and driver to their computer, try to find the com port and all that jazz.

You would simply plug the usb cable in to your device and into the computer. done.

#### Harrington

Joined Dec 19, 2009
85
That's correct, Retched is right re straight into the USB using FT245BM available from ftdichip.com or one of their distributors

I would ask them at the same time whether they can provide you with an active X object to use with VB
That's if they have written one hmm another story i guess If they have Best way forward here easy approach is drop them an email and check if they do so as to find out first before you rush into that choice as well

Or its C# I'm afraid which is Ahhh yes another language that you will have to learn Nothings easy is it !!

If only it were m Anyway here is a link for this as well should you wish to read this I would read as much as you can and research this before you jump down the route of USB

http://www.vsj.co.uk/articles/display.asp?id=600
http://www.codeproject.com/KB/cs/USB_HID.aspx

I have also checked into the java USB and after much reading last night and today You can tell Im unemployed and no one has any work for me !! Grrrrr and I recompiled and tested this as well Just to see if I could find a nice solution for you

It does work but their are quite a few annotations that the driver package for XP reports

So its not the ideal answer but you will be able to change the PID and ID in the registry , "Oh Golly that's regedit etc etc as well I now have to learn " , Uhm Well Yes you will have to do this as well !!

All so that you can read and write to the USB , marvelous isnt it all this Hi tech stuff

Yes it works but consider a more stable driver which has been tested and approved otherwise its back ton writing your own driver after reading 10 meg of material regards how USB works

You do however have to compile the DLL using Visual studio 2005

Also you must recompile the Driver file and you may also want to rewrite some of the Java Native Methods for other functions that the DLL provides

This means that you would also have to understand how to use JNI calls and and recreate the necessary C++ implementation files using the javac -jni switch

In other words Its understanding Java classes and Native method calls how to lots and lots of learning here too never mind just simply rewriting your own drivers dll's and being able to test them so that you end up with a stable version

Quite a lot to take in for a small project of this size

Still worth learning as this will prove to be no end of use to you when writing your own dll's so that you can interact with other functions you may wish to implement in your VB program

A massive learning curve We are now looking at time scales of well This could take you at least 6 months to a year just to try to learn how to communicate with USB

Not as easy as you think because you have to locate which USB device you are after in order to reset power up and then read or write too

Good news is yes it works but its not exactly the most stable of drivers bear that in mind

One3 last point should you decide the C# route then it means you must also have the dot net packages installed on your machine and Oh yes everybody else as well that's

Dotnet version 1.1 then 2.1 and the 3 plus of course Microsoft's fabulous one billion updates

We don't exactly know either Still not to worry I'm sure this will eventually be a successful project maybe in a years time You have to laugh at this really don't you really don't you otherwise you are going to be sitting their crying your eyes out after spending loads of time patience and headaches creating this wonderful temperature read out story via your pic only to find
that you have yet another 2 years studying to do before I can even get this to work

Last edited:

#### symqwerty

Joined Feb 22, 2010
31
my project also something like this, but I'm using weight sensor,so my output from PIC will be weight. And, I need to announce the weight by using VB program.
Is it for the same concept for my project? I want to save my output from PIC in PC but then I don't know how to.
Can anyone tell me how to do?
What type of VB you use?VB6 or VB.NET? I will recommend you to use VB.NET.

I think it's better to let the PIC to do the ADC and then pass the raw data to your PC. Next, PC will do the math before display the 'weight'.

Since you use 10-bit ADC, the result will be placed in 2 register, ADRESH and ADRESL (if not mistaken). Then, you can sent the result via uart to PC. Then, to combine these 2 value to form 1 single value, you need to 'shift' the bits to the left or mathematically like this; tmp = (ADRESH x 256) + ADRESL. By now, "tmp" will have the correct decimal value.

#### symqwerty

Joined Feb 22, 2010
31
You can buy usb to rs232 cable converter or FTD232R IC. The cable converter will emulate or appear as VIRTUAL com port, so just treat it as rs232 port ( no knowledge of USB is needed.)

but if you buy FTD232R IC, you have 2 options, either to use VCP or DLL. But for starter, you can use VCP or Virtual Com Port as a driver. same case as above. If you want more flexibility or features from the chip, you should learn to use the DLL (FTD2XX.dll). furthermore, no knowledge of USB is needed.

#### fyee

Joined Mar 7, 2010
16
What type of VB you use?VB6 or VB.NET? I will recommend you to use VB.NET.
I've VB6 and VB2008 Express Edition.

Since you use 10-bit ADC, the result will be placed in 2 register, ADRESH and ADRESL (if not mistaken). Then, you can sent the result via uart to PC. Then, to combine these 2 value to form 1 single value, you need to 'shift' the bits to the left or mathematically like this; tmp = (ADRESH x 256) + ADRESL. By now, "tmp" will have the correct decimal value.
how do I write this in my program? btw,I'm writing in C language by using MicroC Pro for PIC.

You can buy usb to rs232 cable converter or FTD232R IC. The cable converter will emulate or appear as VIRTUAL com port, so just treat it as rs232 port ( no knowledge of USB is needed.)
I'm using USB to RS232 cable converter.

Explanation in programming is needed. I don't really know how to start the program. Pardon me for being a programming noobie.

thanks so much.

#### symqwerty

Joined Feb 22, 2010
31
OK...lets do like this..

PIC side :
You must learn how to use UART. Remember that UART will transfer byte by byte. So, since you have 2 register with byte size, ADRESH and ADRESL, you have to transfer it one by one. That's why i recommend you to do the calculation in PC instead of PIC..

MikroC have built-in function for UART..
Rich (BB code):
USART_Init(9600);   // baud rate 9600kbps
delay_ms(20);        // relax

TRISA=0x0F;          // set port A as input

//I'm using old version of MikroC and most of the time, i prefer to use my own code instead of built-in function.
the rest of the code..

Rich (BB code):
// You can use ADC_READ(pin_no) for this purpose

ADCON0.f2=1;                     // set GO - start conversion
ST:
if(ADCON0.f2==1) goto ST;     //wait until flag bit cleared
// microC also have pre-defined fn for ADC but i dont want to use it here.

Usart_Write(ADRESL);          // [7:0]
PC side :
PC will process data transmitted by PIC. Just create new VB project, then add "Serial Port" component to your form. Next, set the properties( baudrate, handshaking, com no. and etc).

Then, using the data received, use formula as discussed before.

Rich (BB code):
'open serial port

If SerialPort1.IsOpen() Then
SerialPort1.close()       ' close 1st and reopen again
Else
SerialPort1.Open()
MsgBox("open")
End If

' use event-based method or polling method to get data from serial prot