Click here to Skip to main content
16,007,885 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
my project give back an error about using serialPort1.Read:

byte[] buff={0}; 
serialPort1.Read(buff, 10, 10); 


it's in "button_click" event, when i pressed on button, give back an error and display "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."
what does it mean?
Posted

You should write
serialPort1.Read(buff, 0, 10);
 
Share this answer
 
Comments
mohsenvasefi 22-Oct-13 4:16am    
i wrote it, but it gave back error again! could you tell me the difference between first Int32 and second in serialPort1.Read(byte[] buffer, Int32, Int32)?
Well, what did you expect? Are there at least 10 bytes in the serial port buffer waiting for you? Is the array you are loading them into big enough for 20 bytes? Because that is what you are asking for "Give me 10 bytes, and but them in this one byte buffer, starting from the eleventh byte location"

Try this:
C#
byte[] buff= new byte[20];
serialPort1.Read(buff, 10, 10);
But instead, please don't use "magic numbers" - use constants, or check the serial port length to ensure there are at least as many bytes as you need first. Then use that size to allocate your buffer, remembering to add on whatever you need for the output offset.
 
Share this answer
 
Comments
mohsenvasefi 22-Oct-13 3:43am    
well, i have 10 bytes on serial port line, and wants to read these bytes. what is the first Int32 in serialPort1.Read(byte[] buffer, Int32, Int32)? and second Int32?
OriginalGriff 22-Oct-13 4:28am    
If you aren't sure about anything like this, then there are two easy ways to find out:
1) Google for the class and method: "SerialPort.Read" - the top result is usually the MSDN documentation which describes the parameters.
http://msdn.microsoft.com/en-us/library/ms143549.aspx
2) Put your cursor on the first int32 value in VS, and press CTRL+SHIFT+SPACE.
Intellisense will popup a brief summary. (This is one of the reasons why you should always provide XML comments for all your methods - if you do, Intellisense will do the same for them, too)
In this case, the first number is the "offset" into the output byte array (ie, the number of locations to skip - if you specify an offset of one, then the data from the serial port will not overwrite the first byte in the existing array). The second number if the number of bytes to read from the serial port into the supplied array.
mohsenvasefi 22-Oct-13 4:52am    
excellent!
thanks a lot
OriginalGriff 22-Oct-13 4:56am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900