-
Sending Byte to serial port
Hi all
I need to send a packet of type byte: 0x00, 0x01, 0x02, 0x11, 0x00, 0x00 to a device via the serial port and then I receive and store data coming from device like this: 0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00.
Someone could send me lines of code through which:
1) I create the array
2) the sending the array to serial port
3) I'll see what I'm sending
4) I get the data
I'm using Visual Studio 2010 and C + + or VC++ language.
I hope someone can help me
greetings
f
-
Re: Sending Byte to serial port
-
Re: Sending Byte to serial port
Thank you very much mr. VictorN
I'm trying to test the code: http://www.planet-source-code.com/vb...d=144&lngWId=3
I have to send the bytes via bluetooth, so I'm looking for the part that deals with the trasmission and reception of bytes in this code. I'd like to add this part in my code . Now i'm able to open serial port and to find the bluetooth device, but maybe i'm not able to send and to receive the bytes correctly. I'll show you my code (i modified a code that i have found in internet):
PHP Code:
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
// add sender name
String^ name = this->serialPort1->PortName;
// grab text and store in send buffer
String^ message = this->textBox2->Text;
//write to serial
if(this->serialPort1->IsOpen){
array<Byte>^TxBfr={0x00,0x02,0x06,0x13,0x01,0x01,0x00};
this->serialPort1->Write(TxBfr,0,7);
try{
//this->textBox1->Text=this->serialPort1->ReadLine();
this->textBox1->Text=this->serialPort1->ReadByte();
//printf("%02X",this->serialPort1->ReadByte());
//printf ("%s \n", "A string");
}
catch(TimeoutException^){
this->textBox1->Text="Timeout Exception";
}
-
Re: Sending Byte to serial port
The code that you "have found in internet" has nothing to do with Visual C++ one, nor is it a valid native C++.
It looks like a managed C++ code that is discussed in another (Managed C++/CLI) forum.
-
Re: Sending Byte to serial port
Ah ok thank you.
I'm not an expert. I prefer programming in native C + + or Visual C + +, but for now I only found that code for communication Bluethooth. Maybe I could use the code in http://www.planet-source-code.com/vb...d=144&lngWId=3
-
Re: Sending Byte to serial port
AFAIK it doesn't matter whether you use Bluethooth or infraRed or USB or some other communications. It is up to Bluethooth drivers to emulate correct serial port communications. So you can use the same code to communicate with Bluethooth port as it would be a "classic" serial port. (otherwise, it had to supply some SDK or APIs for communications with it!)
-
Re: Sending Byte to serial port
When i debug the code in http://www.planet-source-code.com/vb...d=144&lngWId=3, i see this kind of error messages:
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\devobj.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\serialui.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\setupapi.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\devobj.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\cfgmgr32.dll'
Failed in call to TransmitCommChar
Warning: throwing CSerialException for error 1
Eccezione first-chance a 0x7686c41f in SerialPort.exe: Eccezione di Microsoft C++: CSerialException nella posizione di memoria 0x002efc00..
Handle Exception, Message:Funzione non corretta.
-
Re: Sending Byte to serial port
Sorry, I cannot understand the output you have provided. Could you translate it?
Besides, your could try the more recent version of CSerialPort class from http://www.naughter.com/serialport.html
-
Re: Sending Byte to serial port
The same errors...:
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\ntdll.dll', Impossibile trovare o aprire il file PDB (trad:Impossibile trovare o aprire il file PDB=Can not find or open the PDB file)
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\kernel32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\KernelBase.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\mfc100d.dll', Simboli caricati.
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\msvcr100d.dll', Simboli caricati.
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\user32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\gdi32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\lpk.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\usp10.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\msvcrt.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\advapi32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\sechost.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\rpcrt4.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\sspicli.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\cryptbase.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\shlwapi.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\winsxs\x86_microsoft.windows.common-controls_6595b64144ccf1df_5.82.7601.17514_none_ec83dffa859149af\comctl32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\msimg32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\oleaut32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\ole32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\imm32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\msctf.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Program Files (x86)\Kaspersky Lab\Kaspersky Anti-Virus 6.0 for Windows Workstations MP4\adialhk.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Program Files (x86)\Kaspersky Lab\Kaspersky Anti-Virus 6.0 for Windows Workstations MP4\kloehk.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\uxtheme.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\dwmapi.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\mfc100ita.dll', Il file binario non è stato compilato con le informazioni di debug.
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\cfgmgr32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\cfgmgr32.dll'
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\serialui.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\setupapi.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\cfgmgr32.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': caricato 'C:\Windows\SysWOW64\devobj.dll', Impossibile trovare o aprire il file PDB
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\serialui.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\setupapi.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\devobj.dll'
'SerialPort.exe': scaricato 'C:\Windows\SysWOW64\cfgmgr32.dll'
'SerialPort.exe': scaricato 'C:\Program Files (x86)\Kaspersky Lab\Kaspersky Anti-Virus 6.0 for Windows Workstations MP4\adialhk.dll'
Il thread 'Thread Win32' (0x1138) è terminato con il codice 0 (0x0).
CSerialPort::Open, Failed to open the comms port, Error:121
Warning: throwing CSerialException for error 121
-
Re: Sending Byte to serial port
Well, I see only one "error" message. It is
Quote:
CSerialPort::Open, Failed to open the comms port, Error:121
Look at the code in the CSerialPort::Open method to understand the reason of this message.
-
Re: Sending Byte to serial port
Ok, the error changes sometimes in :
CSerialPort::TransmitChar, Failed in call to TransmitCommChar, Error:1
-
Re: Sending Byte to serial port
Where do you call this TransmitChar from?
How do you open a port? Please, show your code.
-
Re: Sending Byte to serial port
The "error" 'Impossibile trovare o aprire il file PDB' is just an information that the loaded dll doesn't have any debugging info.
-
Re: Sending Byte to serial port
Even though you may actually manage to get your C++/CLI program working with the native CSerialPort class, I'd strongly recommend against using it. The .NET framework provides the handy SerialPort class which you should use instead.
Unnecessarily combining managed and native code can considerably complicate things, which is particularly true when multithreading is involved, and that's the case in properly designed serial communication code. The complication may be so drammatic that you need to take more effort to have the managed and native parts of your program cooperate properly (the so-called interop) than to write the code that your program actually needs to do what it is supposed to do.
BTW, this is the correct forum section for C++/CLI questions: http://forums.codeguru.com/forumdisp...ed-C-and-C-CLI. Please post further questions of that kind over there.
-
Re: Sending Byte to serial port
@Eri523: Thank you very much for your reply! I'm trying to use only native C++ now.
@VictorN: I read that error when i compile only the class in http://www.naughter.com/serialport.html. Now I'm trying to find a sample code in C++ native, able to send and to receive arrays of bytes(using the class that you showed me).
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
The errors/warnings you showed are NOT the "compile" ones. They are runtime errors/warnings.
-
Re: Sending Byte to serial port
-
Re: Sending Byte to serial port
The connection between bluetooth device and PC is working.
In the code of http://www.naughter.com/serialport.html there is the app.cpp code. When it runs the port is opened and the connection is made but after some seconds appears this error:
CSerialPort::Write, Failed in call to WriteFile, Error:997
This is a part of app.cpp code:
PHP Code:
CSerialPort port2;
port2.Open(6, 9600, CSerialPort::NoParity, 8, CSerialPort::OneStopBit, CSerialPort::XonXoffFlowControl, TRUE);
CEvent event(FALSE, TRUE);
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = event;
try
{
port2.Write(pBuf, 10000, overlapped);
}
catch(CSerialException* pEx)
{
if (pEx->m_dwError == ERROR_IO_PENDING)
{
DWORD dwBytesTransferred = 0;
port2.GetOverlappedResult(overlapped, dwBytesTransferred, TRUE);
pEx->Delete();
}
else
{
DWORD dwError = pEx->m_dwError;
Instead this is the part of code od SerialPort.cpp of error message:
PHP Code:
void CSerialPort::Write(const void* lpBuf, DWORD dwCount, OVERLAPPED& overlapped, DWORD* pBytesWritten)
{
//Validate our parameters
ASSERT(IsOpen());
DWORD dwBytesWritten = 0;
BOOL bSuccess = WriteFile(m_hComm, lpBuf, dwCount, &dwBytesWritten, &overlapped);
if (!bSuccess)
{
DWORD dwLastError = GetLastError();
TRACE(_T("CSerialPort::Write, Failed in call to WriteFile, Error:%d\n"), dwLastError);
ThrowSerialException(dwLastError);
}
-
Re: Sending Byte to serial port
ERROR_IO_PENDING (error 997) just means that Write operation is not completed yet! From MSDN:
Quote:
... GetLastError function returns ERROR_IO_PENDING. This allows the calling process to continue processing while the write operation is being completed. The event specified in the OVERLAPPED structure is set to the signaled state upon completion of the write operation.
Please, read about Serial Communications in MSDN:
http://msdn.microsoft.com/en-us/library/ff802693.aspx
http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx
http://msdn.microsoft.com/en-us/libr...(v=vs.85).aspx
-
Re: Sending Byte to serial port
thank you very much Victor for your help! I'm a new programmer, but i'm improving and the communication between PC and device has been established also with C++ language. I discovered that I have problems with writefile becouse the device bluetooth use Cobs codification and now I'm trying to understand the following Cobs code:
PHP Code:
/*
* StuffData byte stuffs "length" bytes of
* data at the location pointed to by "ptr",
* writing the output to the location pointed
* to by "dst".
*/
#define FinishBlock(X) \
(*code_ptr = (X), \
code_ptr = dst++, \
code = 0x01)
void StuffData(const unsigned char *ptr,
unsigned long length, unsigned char *dst)
{
const unsigned char *end = ptr + length;
unsigned char *code_ptr = dst++;
unsigned char code = 0x01;
while (ptr < end)
{
if (*ptr == 0) FinishBlock(code);
else
{
*dst++ = *ptr;
code++;
if (code == 0xFF) FinishBlock(code);
}
ptr++;
}
FinishBlock(code);
}
this code is used to Cobs codification, but I don't understand how i can use it to codify my array of bytes.
-
Re: Sending Byte to serial port
Sorry, but I have no idea what these FinishBlock macro and StuffData function are for and where they come from... :confused:
BTW, you should use Code tags (using # toolbar button) rather than PHP or HTML ones.
Besides, your code is very bad formatted: messed indentations and more than one statement on the same line make reading/understanding this code very difficult!
-
Re: Sending Byte to serial port
-
Re: Sending Byte to serial port
Well, then try to encode your byte sequence using this code according to this comments:
Quote:
Code:
/*
* StuffData byte stuffs "length" bytes of
* data at the location pointed to by "ptr",
* writing the output to the location pointed
* to by "dst".
*/
Then send theough the port the encoded byte sequence pointed to by "dst"
-
Re: Sending Byte to serial port
Yes, but i don't understand well how i can do it.
-
Re: Sending Byte to serial port
You have to declare a destination buffer long enough to contain your encoded byte sequence, then call this StuffData function passing in your original byte array, its length and destination buffer.
Then send what destination buffer will get after this function returns to the serial port.
-
Re: Sending Byte to serial port
I have some problems...I'm a new programmer and all codes are not simple for me now. Are there some example code to understand how i can do it?
Thank you and I'm sorry.
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
I have some problems...I'm a new programmer and all codes are not simple for me now. Are there some example code to understand how i can do it?
Thank you and I'm sorry.
Well, did you read some books about progamming with C++ for Windows?
Did you try some simple sample applications like "Hello Worlds"?
Some others a little more complicated?
Note, that you cannot from the level "zero" jump to a level for programming serial port communications...
So...
-
Re: Sending Byte to serial port
I'm reading and I'm trying many applications.
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
I'm reading and I'm trying many applications.
And???
-
Re: Sending Byte to serial port
I'm improving and now i'm trying and I'd like to estabilish a connection between 2 devices also if it's not very simple for me.
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
I'm improving and now i'm trying and I'd like to estabilish a connection between 2 devices also if it's not very simple for me.
Wrong answer!
Your problem is you have no idea how to call some very simple function with very good described parameter list!
so why do you have such a problem? :confused:
-
Re: Sending Byte to serial port
This is an example of using Stuffdata.
Code:
const char text[] = "abcdefghijklmnopqrstuvwxyz";
char codify[200];
StuffData(text, (sizeof(text)/sizeof(text[0])) - 1, codify);
Quote:
Well, did you read some books about progamming with C++ for Windows?
Did you try some simple sample applications like "Hello Worlds"?
Some others a little more complicated?
Note, that you cannot from the level "zero" jump to a level for programming serial port communications...
You really, really cannot pick this up as you go along without having a very good grounding in the basics of the c++ language, which is obvious you do not have. You need to start with the very basics and progress one step at a time. You are trying to undertake the triple jump without knowing how to run.
-
Re: Sending Byte to serial port
OK thank you very much! Also if the problem is to send this packet: 0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00. Not an Array of char.
-
Re: Sending Byte to serial port
The definiton for StuffData is
Code:
void StuffData(const unsigned char *ptr, unsigned long length, unsigned char *dst)
This says that ptr is a pointer to memory containing unsigned characters and that the characters pointed to cannot be changed. An area of memory containing unsigned characters is a character array (or an array of chars). So to use StuffData the first parameter has to be a pointer to an array of chars. So before you call the function StuffData, your program has to put into a char array the characters for StuffData. You cannot get away from not using a character array! This can be either a fixed size array (as in my previous example) or it can be a dynamically allocated memory (use new). However the character array is created, once it has been you need to populate it with the characters for StuffData.
So from your example, you want to use 11 characters. So you need a character array that contains these characters set up before you call StuffData.
Code:
const unsigned char packet[] = {0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00};
unsigned char codify[200];
StuffData(packet, sizeof(packet) / sizeof(packet[0]), codify);
-
Re: Sending Byte to serial port
Ok I thank you very much.
the follow code ran with success, but I'd like to see the encoding packet. I have thought to use printf, is it correct?
Code:
int main()
{
const unsigned char text[] = {0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00};
unsigned char codify[200];
StuffData(text, (sizeof(text)/sizeof(text[0])), codify);
//printf(...);
return 0;
}
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
Ok I thank you very much.
the follow code ran with success, but I'd like to see the encoding packet. I have thought to use printf, is it correct?
I guess it would be, at least, much faster to try rather than write this post and then wait for replies! :rolleyes:
-
Re: Sending Byte to serial port
I tried before to write!!! but it doesn't work (I have errors when it compiles or i read very strange characters) and for this reason I want to know if it is correct...
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
I tried before to write!!! but it doesn't work (I have errors when it compiles or i read very strange characters)
Please, show your code together with the errors.
-
Re: Sending Byte to serial port
This code show strange characters without errors:
Quote:
int main()
{
const unsigned char text[] = {0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00};
const int p= sizeof(text);
unsigned char codify[p];
StuffData(text, (sizeof(text)/sizeof(text[0])), codify);
printf("%s", codify);
return 0;
}
-
Re: Sending Byte to serial port
Pardon...this is the code:
Code:
int main()
{
const unsigned char text[] = {0x01, 0x01, 0x01 , 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x01, 0x00};
unsigned char codify[200];
StuffData(text, (sizeof(text)/sizeof(text[0])), codify);
printf("%s", codify);
return 0;
}
-
Re: Sending Byte to serial port
Again:
Quote:
Originally Posted by
VictorN
Please, show your code together with the errors.
BTW, why do you use format specification "%s" while your buffer contains a byte sequence, not a text? :confused:
-
Re: Sending Byte to serial port
there aren't any errors with this code.
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
Bfrancesco
there aren't any errors with this code.
:confused:
Then what did your previous post mean:
Quote:
Originally Posted by
Bfrancesco
I tried before to write!!! but it doesn't work (I have errors when it compiles or i read very strange characters) and for this reason I want to know if it is correct...
:confused:
So do you have some errors (compile, link, run-time) or not?
-
Re: Sending Byte to serial port
The destination characters returned by StuffData in dst are NOT a c-style string and are NOT guaranteed to be NULL terminated. So using printf (or cout) to try to display the contents of dst is a non-starter. Have you actually looked at what StuffData does? It takes an array of char and a length and returns a codified char array where the first char is the number of bytes (including itself) followed by the chars. If the length of the bytes exceeds 255 then a new chuck is started again with the first byte as the length byte. So "qwerty" gets codified as 0x07 'q' 'w' 'e' 'r' 't' 'y'. 0x00 is treated specially and just gets translated as a new chuck of length 1. So after using StuffData, you pass dst to whatever function you use to actually send the data.
-
Re: Sending Byte to serial port
Quote:
Originally Posted by
2kaud
The destination characters returned by StuffData in dst are NOT a c-style string and are NOT guaranteed to be NULL terminated. So using printf (or cout) to try to display the contents of dst is a non-starter.
I'd say neither the initial buffer nor the destination one is "a c-style string". Both are just byte sequences with some predefined length.
And there is nothing wrong to use printf (or cout) to output their contents. Just use some proper format specification (like %X, "%08X", "%d" or similar) and do output in a loop for each element in the buffer!
-
Re: Sending Byte to serial port
Sorry, I wasn't specific. I meant not using printf("%s", dst).
-
Re: Sending Byte to serial port
Well! Thank you! This is a very good forum. I forgot to create
Quote:
a loop for each element in the buffer!
I have finished my second step with success: encoding and decoding the packet! And thanks to "printf" I have verified that all works correctly!
Now I can pass to the 3rd step.
-
Re: Sending Byte to serial port
One fast question...
I'm implementing a 16bit CCITT CRC algorithm and I have found this sample:
Code:
unsigned int crc(unsigned char data)
{
static unsigned int crc;
crc = (unsigned char)(crc >> 8) | (crc << 8);
crc = data;
crc ˆ= (unsigned char)(crc & 0xff) >> 4;
crc ˆ= (crc << 8) << 4;
crc ˆ= ((crc & 0xff) << 4) << 1;
return crc;
}
I'd like to understand how work the "^=" operator.
-
Re: Sending Byte to serial port
-
Re: Sending Byte to serial port
OK thank you. I didn't find http://msdn.microsoft.com/en-us/libr...(v=vs.80).aspx.
Why the compiler gives the follow error:
- syntax error: ';' before identifier ''^" ?