Sending structured data over serial to a PC app - best practice

Go To Last Post
36 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I have small project where I am passing structured data over serial to a PC app. The data is used to provide a visual topology of my nr24L01+ star network. My question is in regards to best practice and data integrity when passing structured data over serial.

 

As an example, I have the following struct:

 

typedef struct __attribute__ ((packed)) {

    uint8_t start_checksum;
    uint8_t end_checksum;
    uint8_t id;
    uint16_t data;
    uint16_t data2;

} nrf24_packet_t;

nrf24_packet_t pck;

 

My first two bytes of the struct are "Checksums" to check for data integrity when the data is received on the PC app:

 

 

pck.id = node_number;    // nrf24 node id
pck.data = fakeval++;    // dummy data
pck.data2 = 350;         // dummy node
  // add a check sum
pck.start_checksum = 255;
pck.end_checksum = 7;

In my project, the packet (nrf24_packet_t ) is passed from node to node until it gets the "Base Node". The Base Node will then send the data to the PC like this:

 

void receive_data(void){	

	if(nrf24_dataReady())
	{
		nrf24_flushTx();
		uint8_t payLoadsize = nrf24_getPayloadLength();
		if(payLoadsize > 32){
		     return;
		}
		uint8_t pipeNo = nrf24_getPayLoad(&pck, sizeof(nrf24_packet_t));

		memcpy(temp, &pck, sizeof  temp );
		for(uint8_t i = 0; i < sizeof(temp); i++){
			printf("%d\n", temp[i]); //tokenize each value with a \n
		}
		printf("\n\r");
		delay_s(2); // give at least 2 seconds to let the PC app handle the load
	}
}

I tokenize the bytes in the buffer with a newLine '\n' and on the PC side validate the incoming data. The incoming packet looks something like this:

 

[0]: "255" - start check sum
[1]: "7" - end check sum
[2]: "2" - node id
[3]: "12" - next 4 bytes are data
[4]: "0"
[5]: "94"
[6]: "1"
[7]: ""
[8]: "\r" 

 

As mentioned, the first 2 bytes are used to verify the packet. The below is some c# code, but is pretty straight forward used to verify the packet data:

 

private void DataReceivedHandler(object sender,  SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    try
    {
        string indata = sp.ReadExisting();
        string[] dataArray = indata.Split('\n');

        if (dataArray.Length > 5)
        {
                Packet pck = new Packet
                {
                    StartCheckSum = Convert.ToInt32(dataArray[0]),
                    EndCheckSum = Convert.ToInt32(dataArray[1]),
                    Id = Convert.ToInt32(dataArray[2]),
                    Value = Convert.ToInt32(dataArray[3]),
                };
                // verify the data here
                if (pck.StartCheckSum == 255 && pck.EndCheckSum == 7 && pck.Id > 0 && pck.Id < 252)
                {
                    RenderNodeDelegate d = new RenderNodeDelegate(renderNode);
                    this.Invoke(d, new object[] { pck.Id.ToString() });
                }

            else {

                PacketCountDelegate pd = new PacketCountDelegate(packetCountHandler);
                this.Invoke(pd, new object[] { false });
            }
        }
    }
    catch (Exception ex)
    {

        PacketCountDelegate pd = new PacketCountDelegate(packetCountHandler);
        this.Invoke(pd, new object[] { false });
    }
    sp.DiscardInBuffer(); // clear any incoming data until we update the UI
}

My questions is; is this the best approach or is there a better way to send structured data over serial and verify its integrity?

 

My approach works and the final outcome is a nice topology of my network, but perhaps there is a better way:

 

"When all else fails, read the directions"

Last Edited: Sun. Mar 25, 2018 - 02:08 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The only issues you have when passing data between non matching CPU architectures are:

 

1) byte alignment / struct packing. 32/64 bit CPUs often like "short" data like 8/16 bit to be padded out so they lie on 32/64 bit boundaries for ease of data access (the CPUs "fault" if asked to access things that straddle boundaries). AVRs are naturally 8 bit so they don't need (or use) any such padding/alignment. So you often need to say to the "big end" that it should pack things tight. Keywords often involve "packed".

 

2) endianism (my tablet just corrected that to lesbianism!). When you have anything wider that 8 bit (so uint16_t or larger) there is a question of whether the bytes are stored lowest or highest first. As it happens both PC and AVR (compilers) are naturally little endian so for transfers between those two you should be OK.

 

If you want to avoid a lot of these issues and can afford the bandwidth on the comms link then convert to ASCII, send that (a universal, human readable, byte order/packing) then convert back at the receiver then the "local" encoding does not matter.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The more ‘usual’ might be simething kike this:
Start token (not checksum)
Addr
Length
Payload(n bytes)
Crc (two bytes)

There’s Google protobufs that define a methos of encoding structured data. There’s also Firmata for Arduino. However, i’ve always just defined my own fixed structures for the data- usually cmd then optional params.
My experience suggests that it is wiser to separate the transport framing from the payload data as it makes decoding easier and simpler to expand later.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

What happens if you you lose some bytes of your packets?

Would your PC keep on trying to combine the last part of a packet with the first part of the next packet and throw the data away because it is not a valid packet?

Instead of throwing the data away, it is much better to "shift" the received data a single byte an then try to decode the packet again.

That is why a lot of packet switched networks often begin with some preamble or with a recognizable "start token" as Kartman suggest.

However, it does look like your checksum is not really a checksum, but your "checksum" is such an "start token".

Your 2 "checksum" bytes seem to be the static values 255 and 7.

                if (pck.StartCheckSum == 255 && pck.EndCheckSum == 7 && pck.Id > 0 && pck.Id < 252)

The Checksum field is usually a calculated value based on a CRC algorithm and is calculated from the actual data in the packet.

The sender calculates the CRC and appends it to the packet. The receiver makes the same calculation and compares it's result with the CRC stored in the packet.

If they match the receiver can be pretty confident that the integrity of the data is ok.

You can find some CRC algorithms for AVR's in: <util/crc.h>

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paulvdh wrote:
The Checksum field is usually a calculated value based on a CRC algorithm and is calculated from the actual data in the packet.

Thanks for the help. So in my case, a Checksum field wont work because by AVR must create the CRC Checksum and my PC must re-calculate the checksum and verify it. Correct me if I am wrong, the AVRs CRC algorithms must be known by my PC app to verify?

 

 

"When all else fails, read the directions"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Google "Serialisation" (or "Serialization")

 

https://en.wikipedia.org/wiki/Serialization

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Correct me if I am wrong, the AVRs CRC algorithms must be known by my PC app

That is true of any use of checksum, CRC, SHA, MD5, etc - both ends must implement the identical algorithm for the verification check to be valid. In the case of checksums it's generally easy as it's just a case of adding up the values and both ends probably do that in a very similar way (though it's true an "int" at one end might not be the same thing as an "int" at the other end - which is why things like uint8_t, in32_t, etc are preferred as they ARE the same). But once you move up to CRCs there is a question of the "polynomial" used. A CRC works by cyclically feeding some of the bits of the last value back round into the next value and the "polynomial" says which of the bits should take part in this. So once you reach CRC you have to be certain that both ends are implementing the same polynomial. To give you an idea AVR-LibC comes with this:

 

http://nongnu.org/avr-libc/user-...

 

On the whole, while those are all 8 or 16 bit CRC (and the width of the CRC is another consideration!) they implement:

 

x^16 + x^15 + x^2 + 1 (0xa001)

x^8 + x^2 + x + 1 (0xE0)

x^16 + x^12 + x^5 + 1 (0x8408)

x^8 + x^5 + x^4 + 1 (0x8C)

x^16 + x^12 + x^5 + 1 (0x1021)

 

So the polynomials differ for each one - in fact that, and the "initial value" (can be 0x00/0xFf for 8bit or 0x0000/0xFFFF for 16 bit) are what makes these routines different.

 

So if you chose to use _crc_ccitt_update() foe example you would need to ensure that the other end also implemented x^16 + x^12 + x^5 + 1 (0x8408) and that it used an initial value of 0xFFFF

As you'll read here:

 

https://en.wikipedia.org/wiki/Cy...

 

Some polynomials are "standardized". You are more likely to find existing library code for standardized ones than some randomly picked polynomial.

Last Edited: Tue. Mar 27, 2018 - 11:49 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Everything you could ever want to know - and more - about CRCs:

 

http://www.repairfaq.org/filipg/LINK/F_crc_v3.html

 

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If standarized ways of sending your structured date is a high priority to you, then my advise is to look into "protocol buffers":

 

https://duckduckgo.com/html?q=protocol+buffers

https://en.wikipedia.org/wiki/Protocol_Buffers

 

For quite some time I have used a packet based network (UART + RS485 driver) to exchange data between AVR's and a PC.

Recently I wanted to add ARM Cortex-m3 processors to that network, and that was a bit of a problem because I used the CRC algorithms in <util/crc.h> and the CRC I used was written in ASM for AVR's and is not portable to another architecture.

I also was a bit curious about the qualtity of "arduino" and toying with "platformio" so I decided to to some CRC tests for comparison.

It is mostly some different implementations of the same algorithm (They calculate the same CRC value), but have different code sizes and execution speed.

I've attached both the AVR and the ARM project here, they share much of the same code.

 

Edit:

First intention of attached files was for my own benchmarks.

Because of posting here I've translated Dutch notes to English.

The older files are previous versions of the same project.

Attachment(s): 

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If standarized ways of sending your structured date is a high priority to you, then my advise is to look into "protocol buffers":

Mentioned in #3.

"Experience is what enables you to recognise a mistake the second time you make it."

"Good judgement comes from experience.  Experience comes from bad judgement."

"Wisdom is always wont to arrive late, and to be a little approximate on first possession."

"When you hear hoofbeats, think horses, not unicorns."

"Fast.  Cheap.  Good.  Pick two."

"We see a lot of arses on handlebars around here." - [J Ekdahl]

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I've done some work with protobuf's and I've done some work with Python's struct.pack. The latter is not quite the "universal solution" that the Google solution offers but I just found it an easier thing to work with. Of course that will depend on whether Python is involved in what you are doing too. The Python system uses '<' or '>' to denote endianism. (in protobufs the endianism on the wire is fixed (thing it's PC little endian) then it's up to the sender/receiver to re-order if their architecture demands it. (but that's "hidden inside").

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

joeymorin wrote:
Mentioned in #3.
Oops. The Wikipedia link has some links to more standard formats.

But the focus here seems to go in the CRC direction. With the info in this thread OP has enough links to background and examples to experiment with for several days...

Standards

https://xkcd.com/927/

I really hope that chargers are going to standarize on USB-C.

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

Last Edited: Tue. Mar 27, 2018 - 11:28 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paulvdh wrote:
I've attached both the AVR and the ARM project here, they share much of the same code.

 

Thanks - I'll need to brush up on my Dutch :)

 

All good advice. Thanks.

"When all else fails, read the directions"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paulvdh wrote:
I really hope that chargers are going to standarize on USB-C.
I thought they had already standardized on USB mini A-B for years (a decade(*) or more)?

 

(standardized, that is, unless your name is Apple - but why would want to give your customers access to a $1-$2 "standard" charger when you can have $50 off them ? ;-)

 

EDIT: (*) OK, 9 years... https://en.wikipedia.org/wiki/Co...

Last Edited: Wed. Mar 28, 2018 - 08:39 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You can send it as binary and then do marshal it into a struct in C#. The main issue really is not so much the data as encapsulating the transmission so you know when the start and end are.

 

There are two common ways to do that. You can do it out of band with the RS232 control lines like RTS and CTS. Just be aware that they are not synchronous when using USB to serial converters, so you need to set them and then wait a millisecond or two.

 

The other way is to use in-band signalling, like a start of packet pattern. Something like a short sequence of 0x55 or 0xFF/0x00 bytes is common. I like 0x00 because it produces a nice long low period on the bus, which tends to reset the UART's state machine and is also ideal for measuring if you want to auto-baud or filter line noise. You can probably set your scope to trigger on it with a bit of effort too.

 

One other technique I quite like is gaps between packets. They only need to be 1.5 characters or more if your UART has a buffer and you can keep it filled. The only problem is that PCs have a hard time detecting that reliably, where as on MCUs it's usually very easy.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

clawson wrote:
If you want to avoid a lot of these issues and can afford the bandwidth on the comms link then convert to ASCII, send that (a universal, human readable, byte order/packing) then convert back at the receiver then the "local" encoding does not matter.

A common way of doing this is JSON.

 

https://www.json.org/

 

Example (form Wikipedia):

{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 27,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": null
}

Clearly a lot more verbose than a binary format ... 

 

https://auth0.com/blog/beating-json-performance-with-protobuf/

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

awneil wrote:
A common way of doing this is JSON.

I would think JSON is not intended for small processors (MCU) with limited memory. As a full time web developer, I love JSON. It plays nice with c# and javascript, making it easy to send complex data structures between servers and clients. I think JSON is too verbose for AVR and even ARM (like the SAMD21) and would require a lot of memory to parse.

 

 

"When all else fails, read the directions"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There’s json parsers that feed you a stream of tokens rather than create a structure in ram. Arduino has examples of these. So, yes, you can do json on an AVR with, say, 2k of ram.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

There’s also BSON which is a bit like protobufs

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If Universal Windows Platform (UWP) and C#, UWP has an InputStream object class with an endian property and methods to convert the stream into some common objects.

If UWP on Windows 10 then Windows 10 has a USB serial API to get an InputStream.

 

https://docs.microsoft.com/en-us/uwp/api/windows.storage.streams.datareader#properties-

via

https://docs.microsoft.com/en-us/uwp/api/windows.devices.serialcommunication.serialdevice.inputstream#remarks

Microsoft Windows USB Core Team Blog

What is new with Serial in Windows 10

by George Roussos [Microsoft]

July 29, 2015

https://blogs.msdn.microsoft.com/usbcoreblog/2015/07/29/what-is-new-with-serial-in-windows-10/

...

 

2.   A Windows Runtime API for communication with Serial devices

Windows 10 includes the Windows.Devices.SerialCommunication universal API designed for these three scenarios:

  1. USB Peripherals like Arduinos – including as a USB Accessory on new Phones and Tablets
  2. Peripherally connected USB to RS-232 Adapters
  3. UARTs inside embedded  systems like MinnowBoard Max or Raspberry Pi v2 running Windows IoT SKU

...

 

"Dare to be naïve." - Buckminster Fuller

Last Edited: Thu. Mar 29, 2018 - 03:07 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

PhillyNJ wrote:
Thanks - I'll need to brush up on my Dutch :)
  I'm sorry for that. I just added an English translation to the #9 post.

https://www.avrfreaks.net/sites/default/files/forum_attachments/2018-03-29_arduino_crc_english.zip

 

I tend to write comment for all my projects in english, but the CRC stuff was a little benchmark as a test and supposed to be integrated into a more formal project and therefore I did not bother to make my own notes in English, which is slightly more demanding for my brain.

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

gchapman wrote:
If Universal Windows Platform (UWP) and C#,
Ah, yes, very universal for windows only?

 

Anyone willing to decypher this:

(including the links to other documents not posted here).

I spend about 2 minutes scanning for obvious (C) statements but did not see any, so it might not be as bad as I initially thought.

But I also did not see the source code for en/de-coding that format. (Might have also overlooked it. I'm not very patient when it comes to microsoft).

And that won't ever change before they pay me back the hours I lost because of their deliberate FUD.

https://docs.microsoft.com/en-us/legal/termsofuse

  •  

docs.microsoft.com - Terms of use

Acceptance of Terms

The services that Microsoft provides are subject to the following Terms of Use ("TOU"). Microsoft reserves the right to update the TOU at any time without notice to you. The most current version of the TOU can be reviewed by clicking on the "Terms of Use" hypertext link located at the bottom of our Web pages.

Top of Page

Description of Service

Through its network these Web properties, Microsoft provides you with access to a variety of resources, including documentation, developer tools, download areas, communication forums and product information (collectively "Services"). The Services, including any updates, enhancements, new features, and/or the addition of any new Web properties, are subject to the TOU.

Top of Page

Personal and Non-Commercial Use Limitation

Unless otherwise specified, the Services are for your personal and non-commercial use. You may not transfer or sell any information, software, products or services obtained from the Services without prior written consent from Microsoft.

Top of Page

Privacy and Protection of Personal Information

See the Privacy Statement disclosures relating to the collection and use of your information.

Top of Page

Notice Specific to Software Available on this Website

Any software that is made available to download from the Services ("Software") is the copyrighted work of Microsoft and/or its suppliers. Use of the Software is governed by the terms of the end user license agreement, if any, which accompanies or is included with the Software ("License Agreement"). An end user will be unable to install any Software that is accompanied by or includes a License Agreement, unless he or she first agrees to the License Agreement terms. Third party scripts or code, linked to or referenced from this website, are licensed to you by the third parties that own such code, not by Microsoft.

The Software is made available for download solely for use by end users according to the License Agreement. Any reproduction or redistribution of the Software not in accordance with the License Agreement is expressly prohibited by law, and may result in severe civil and criminal penalties. Violators will be prosecuted to the maximum extent possible.

WITHOUT LIMITING THE FOREGOING, COPYING OR REPRODUCTION OF THE SOFTWARE TO ANY OTHER SERVER OR LOCATION FOR FURTHER REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PROHIBITED, UNLESS SUCH REPRODUCTION OR REDISTRIBUTION IS EXPRESSLY PERMITTED BY THE LICENSE AGREEMENT ACCOMPANYING SUCH SOFTWARE.

THE SOFTWARE IS WARRANTED, IF AT ALL, ONLY ACCORDING TO THE TERMS OF THE LICENSE AGREEMENT. EXCEPT AS WARRANTED IN THE LICENSE AGREEMENT, MICROSOFT CORPORATION HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS WITH REGARD TO THE SOFTWARE, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. FOR YOUR CONVENIENCE, MICROSOFT MAY MAKE AVAILABLE AS PART OF THE SERVICES OR IN ITS SOFTWARE PRODUCTS, TOOLS AND UTILITIES FOR USE AND/OR DOWNLOAD. MICROSOFT DOES NOT MAKE ANY ASSURANCES WITH REGARD TO THE ACCURACY OF THE RESULTS OR OUTPUT THAT DERIVES FROM SUCH USE OF ANY SUCH TOOLS AND UTILITIES. PLEASE RESPECT THE INTELLECTUAL PROPERTY RIGHTS OF OTHERS WHEN USING THE TOOLS AND UTILITIES MADE AVAILABLE ON THE SERVICES OR IN MICROSOFT SOFTWARE PRODUCTS.

RESTRICTED RIGHTS LEGEND. Any Software which is downloaded from the Services for or on behalf of the United States of America, its agencies and/or instrumentalities ("U.S. Government"), is provided with Restricted Rights. Use, duplication, or disclosure by the U.S. Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and (2) of the Commercial Computer Software - Restricted Rights at 48 CFR 52.227-19, as applicable. Manufacturer is Microsoft Corporation, One Microsoft Way, Redmond, WA 98052-6399.

Top of Page

Notice Specific to Documents Available on this Website

Certain documentation may be subject to explicit license terms separate from the terms contained here. To the extent the terms conflict, the explicit license terms control.

MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED AS PART OF THE SERVICES FOR ANY PURPOSE. ALL SUCH DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES.

THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED ON THE SERVICES COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME.

Top of Page

Notices Regarding Software, Documents, and Services Available on this Website

IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF SOFTWARE, DOCUMENTS, PROVISION OF OR FAILURE TO PROVIDE SERVICES, OR INFORMATION AVAILABLE FROM THE SERVICES.

Top of Page

Member Account, Password, and Security

If any of the Services requires you to open an account, you must complete the registration process by providing us with current, complete and accurate information as prompted by the applicable registration form. You also will choose a password and a user name. You are entirely responsible for maintaining the confidentiality of your password and account. Furthermore, you are entirely responsible for any and all activities that occur under your account. You agree to notify Microsoft immediately of any unauthorized use of your account or any other breach of security. Microsoft will not be liable for any loss that you may incur as a result of someone else using your password or account, either with or without your knowledge. However, you could be held liable for losses incurred by Microsoft or another party due to someone else using your account or password. You may not use anyone else's account at any time, without the permission of the account holder.

Top of Page

No Unlawful or Prohibited Use

As a condition of your use of the Services, you will not use the Services for any purpose that is unlawful or prohibited by these terms, conditions, and notices. You may not use the Services in any manner that could damage, disable, overburden, or impair any Microsoft server, or the network(s) connected to any Microsoft server, or interfere with any other party's use and enjoyment of any Services. You may not attempt to gain unauthorized access to any Services, other accounts, computer systems or networks connected to any Microsoft server or to any of the Services, through hacking, password mining or any other means. You may not obtain or attempt to obtain any materials or information through any means not intentionally made available through the Services.

Top of Page

Use of Services

The Services may contain e-mail services, bulletin board services, chat areas, news groups, forums, communities, personal web pages, calendars, photo albums, file cabinets and/or other message or communication facilities designed to enable you to communicate with others (each a "Communication Service" and collectively "Communication Services"). You agree to use the Communication Services only to post, send and receive messages and material that are proper and, when applicable, related to the particular Communication Service. By way of example, and not as a limitation, you agree that when using the Communication Services, you will not:

  • Use the Communication Services in connection with surveys, contests, pyramid schemes, chain letters, junk email, spamming or any duplicative or unsolicited messages (commercial or otherwise).
  • Defame, abuse, harass, stalk, threaten or otherwise violate the legal rights (such as rights of privacy and publicity) of others.
  • Publish, post, upload, distribute or disseminate any inappropriate, profane, defamatory, obscene, indecent or unlawful topic, name, material or information.
  • Upload, or otherwise make available, files that contain images, photographs, software or other material protected by intellectual property laws, including, by way of example, and not as limitation, copyright or trademark laws (or by rights of privacy or publicity) unless you own or control the rights thereto or have received all necessary consent to do the same.
  • Use any material or information, including images or photographs, which are made available through the Services in any manner that infringes any copyright, trademark, patent, trade secret, or other proprietary right of any party.
  • Upload files that contain viruses, Trojan horses, worms, time bombs, cancelbots, corrupted files, or any other similar software or programs that may damage the operation of another's computer or property of another.
  • Advertise or offer to sell or buy any goods or services for any business purpose, unless such Communication Services specifically allows such messages.
  • Download any file posted by another user of a Communication Service that you know, or reasonably should know, cannot be legally reproduced, displayed, performed, and/or distributed in such manner.
  • Falsify or delete any copyright management information, such as author attributions, legal or other proper notices or proprietary designations or labels of the origin or source of software or other material contained in a file that is uploaded.
  • Restrict or inhibit any other user from using and enjoying the Communication Services.
  • Violate any code of conduct or other guidelines which may be applicable for any particular Communication Service.
  • Harvest or otherwise collect information about others, including e-mail addresses.
  • Violate any applicable laws or regulations.
  • Create a false identity for the purpose of misleading others.
  • Use, download or otherwise copy, or provide (whether or not for a fee) to a person or entity any directory of users of the Services or other user or usage information or any portion thereof.

Microsoft has no obligation to monitor the Communication Services. However, Microsoft reserves the right to review materials posted to the Communication Services and to remove any materials in its sole discretion. Microsoft reserves the right to terminate your access to any or all of the Communication Services at any time, without notice, for any reason whatsoever.

Microsoft reserves the right at all times to disclose any information as Microsoft deems necessary to satisfy any applicable law, regulation, legal process or governmental request, or to edit, refuse to post or to remove any information or materials, in whole or in part, in Microsoft's sole discretion.

Always use caution when giving out any personally identifiable information about yourself or your children in any Communication Services. Microsoft does not control or endorse the content, messages or information found in any Communication Services and, therefore, Microsoft specifically disclaims any liability with regard to the Communication Services and any actions resulting from your participation in any Communication Services. Managers and hosts are not authorized Microsoft spokespersons, and their views do not necessarily reflect those of Microsoft.

Materials uploaded to the Communication Services may be subject to posted limitations on usage, reproduction and/or dissemination; you are responsible for adhering to such limitations if you download the materials.

The videos and eBooks might be in English only. Also, if you click the links, you may be redirected to a U.S. website whose content is in English.

Top of Page

Materials Provided to Microsoft or Posted at any Microsoft Website

Microsoft does not claim ownership of the materials you provide to Microsoft (including feedback and suggestions) or post, upload, input or submit to any Services or its associated services for review by the general public, or by the members of any public or private community, (each a "Submission" and collectively "Submissions"). However, by posting, uploading, inputting, providing or submitting ("Posting") your Submission you are granting Microsoft, its affiliated companies and necessary sublicensees permission to use your Submission in connection with the operation of their Internet businesses (including, without limitation, all Microsoft Services), including, without limitation, the license rights to: copy, distribute, transmit, publicly display, publicly perform, reproduce, edit, translate and reformat your Submission; to publish your name in connection with your Submission; and the right to sublicense such rights to any supplier of the Services.

No compensation will be paid with respect to the use of your Submission, as provided herein. Microsoft is under no obligation to post or use any Submission you may provide and Microsoft may remove any Submission at any time in its sole discretion.

By Posting a Submission you warrant and represent that you own or otherwise control all of the rights to your Submission as described in these Terms of Use including, without limitation, all the rights necessary for you to provide, post, upload, input or submit the Submissions.

In addition to the warranty and representation set forth above, by Posting a Submission that contain images, photographs, pictures or that are otherwise graphical in whole or in part ("Images"), you warrant and represent that (a) you are the copyright owner of such Images, or that the copyright owner of such Images has granted you permission to use such Images or any content and/or images contained in such Images consistent with the manner and purpose of your use and as otherwise permitted by these Terms of Use and the Services, (b) you have the rights necessary to grant the licenses and sublicenses described in these Terms of Use, and (c) that each person depicted in such Images, if any, has provided consent to the use of the Images as set forth in these Terms of Use, including, by way of example, and not as a limitation, the distribution, public display and reproduction of such Images. By Posting Images, you are granting (a) to all members of your private community (for each such Images available to members of such private community), and/or (b) to the general public (for each such Images available anywhere on the Services, other than a private community), permission to use your Images in connection with the use, as permitted by these Terms of Use, of any of the Services, (including, by way of example, and not as a limitation, making prints and gift items which include such Images), and including, without limitation, a non-exclusive, world-wide, royalty-free license to: copy, distribute, transmit, publicly display, publicly perform, reproduce, edit, translate and reformat your Images without having your name attached to such Images, and the right to sublicense such rights to any supplier of the Services. The licenses granted in the preceding sentences for a Images will terminate at the time you completely remove such Images from the Services, provided that, such termination shall not affect any licenses granted in connection with such Images prior to the time you completely remove such Images. No compensation will be paid with respect to the use of your Images.

Top of Page

Notices and Procedure for Making Claims of Copyright Infringement

Pursuant to Title 17, United States Code, Section 512(c)(2), notifications of claimed copyright infringement should be sent to Service Provider's Designated Agent. ALL INQUIRIES NOT RELEVANT TO THE FOLLOWING PROCEDURE WILL NOT RECEIVE A RESPONSE.

See Notice and Procedure for Making Claims of Copyright Infringement.

Top of Page

Links to Third-Party Sites

THE LINKS IN THIS AREA WILL LET YOU LEAVE MICROSOFT'S SITE. THE LINKED SITES ARE NOT UNDER THE CONTROL OF MICROSOFT AND MICROSOFT IS NOT RESPONSIBLE FOR THE CONTENTS OF ANY LINKED SITE OR ANY LINK CONTAINED IN A LINKED SITE, OR ANY CHANGES OR UPDATES TO SUCH SITES. MICROSOFT IS NOT RESPONSIBLE FOR WEBCASTING OR ANY OTHER FORM OF TRANSMISSION RECEIVED FROM ANY LINKED SITE. MICROSOFT IS PROVIDING THESE LINKS TO YOU ONLY AS A CONVENIENCE, AND THE INCLUSION OF ANY LINK DOES NOT IMPLY ENDORSEMENT BY MICROSOFT OF THE SITE.

Top of Page

Unsolicited Idea Submission Policy

MICROSOFT OR ANY OF ITS EMPLOYEES DO NOT ACCEPT OR CONSIDER UNSOLICITED IDEAS, INCLUDING IDEAS FOR NEW ADVERTISING CAMPAIGNS, NEW PROMOTIONS, NEW PRODUCTS OR TECHNOLOGIES, PROCESSES, MATERIALS, MARKETING PLANS OR NEW PRODUCT NAMES. PLEASE DO NOT SEND ANY ORIGINAL CREATIVE ARTWORK, SAMPLES, DEMOS, OR OTHER WORKS. THE SOLE PURPOSE OF THIS POLICY IS TO AVOID POTENTIAL MISUNDERSTANDINGS OR DISPUTES WHEN MICROSOFT'S PRODUCTS OR MARKETING STRATEGIES MIGHT SEEM SIMILAR TO IDEAS SUBMITTED TO MICROSOFT. SO, PLEASE DO NOT SEND YOUR UNSOLICITED IDEAS TO MICROSOFT OR ANYONE AT MICROSOFT. IF, DESPITE OUR REQUEST THAT YOU NOT SEND US YOUR IDEAS AND MATERIALS, YOU STILL SEND THEM, PLEASE UNDERSTAND THAT MICROSOFT MAKES NO ASSURANCES THAT YOUR IDEAS AND MATERIALS WILL BE TREATED AS CONFIDENTIAL OR PROPRIETARY.

Top of Page

Doing magic with a USD 7 Logic Analyser: https://www.avrfreaks.net/comment/2421756#comment-2421756

Bunch of old projects with AVR's: http://www.hoevendesign.com

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

PhillyNJ wrote:
I would think JSON is not intended for small processors (MCU) with limited memory. As a full time web developer, I love JSON.
A terminal server can use JSON with WebSocket to serve WebSockets that encapsulate the streams to and from a small MCU.

Then, a web browser can implement the image in your post #1.

https://github.com/chilipeppr/serial-port-json-server

Serial Port JSON Server is a websocket server for your serial devices. It compiles to a binary for Windows, Mac, Linux, Raspberry Pi, or BeagleBone Black that lets you communicate with your serial port from a web application. This enables web apps to be written that can communicate with your local serial device such as an Arduino, CNC controller…http://chilipeppr.com

...

Its current release (1.95) does not have a macOS build though there are instructions :

https://github.com/johnlauer/serial-port-json-server#how-to-build

I couldn't locate it in Homebrew.

 


https://www.websocket.org/about.html

http://formulae.brew.sh/

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Paulvdh wrote:
Ah, yes, very universal for windows only?
For Microsoft products only (Windows, Windows IoT, Windows Mobile, Surface Hub, HoloLens (virtual reality), Xbox)

Microsoft Docs​

UWP app developer

Intro to the Universal Windows Platform

https://docs.microsoft.com/en-us/windows/uwp/get-started/universal-application-platform-guide

 

"Dare to be naïve." - Buckminster Fuller

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

PhillyNJ wrote:
I would think JSON is not intended for small processors (MCU) with limited memory.

It is, as I said, pretty verbose.

 

You can, of course, mitigate this by removing all the whitespace and using short identifiers.

 

But it's not at all difficult to generate - it's just a matter of (s)printf into the "template".

 

 

I think JSON is too verbose for AVR and even ARM (like the SAMD21)

Not necessarily - see above.

 

I have sent JSON via SMS from a SAMD21-class processor - the SMS was the more limiting factor than the processor!

 

EDIT: and, of course, if the processor only has a small amount of memory, then it won't have a lot of complex data to send anyhow!

 

would require a lot of memory to parse.

Again, not necessarily.

 

For receiving, a small microcontroller would only need to accept a very specific JSON format - you wouldn't have to implement a complete, universal parser.

 

 

 

Top Tips:

  1. How to properly post source code - see: https://www.avrfreaks.net/comment... - also how to properly include images/pictures
  2. "Garbage" characters on a serial terminal are (almost?) invariably due to wrong baud rate - see: https://learn.sparkfun.com/tutorials/serial-communication
  3. Wrong baud rate is usually due to not running at the speed you thought; check by blinking a LED to see if you get the speed you expected
  4. Difference between a crystal, and a crystal oscillatorhttps://www.avrfreaks.net/comment...
  5. When your question is resolved, mark the solution: https://www.avrfreaks.net/comment...
  6. Beginner's "Getting Started" tips: https://www.avrfreaks.net/comment...
Last Edited: Thu. Mar 29, 2018 - 07:26 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hi all, i see this is an old thread but can you PhillyNJ please help me, 

i have a personal project, and i use one ATmega32u4 and i want to send 8 variables compiled in one struct, 

 

 typedef struct {
  char btstart;
  float bt1; 
  float bt2; 
  float bt3;
  float bt4;
  float bt5;
  float bt6;  
  char btend;
  } PayloadBT;
  PayloadBT payloadBT;  

and i send the struct using: 

serial_writeAnything(0, payloadBT);

template <class T> long int serial_writeAnything(int ee, T& valuebt)
{
  Serial.write('/');
  Serial.write((char *)&valuebt, sizeof(valuebt));
  delay(10);
}

 

i have trouble making an c# app to receive over serial com port the above struct: I know i request much but can anyone give me an c# example how to read the float values?

 

kind regards all

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You might be better off sending the data as json or comma delimited strings. This avoids the ‘endian’ problem you face.

Alternately, if you have the data as a byte array, you can write code to re-arrange the byte order but this means your app might not work on other cpu architectures. There should be plenty of examples on the web for c#. Googling network byte order c# might yield something.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

hunt333r wrote:

typedef struct {
  char btstart;
  float bt1; 
  float bt2; 
  float bt3;
  float bt4;
  float bt5;
  float bt6;  
  char btend;
  } PayloadBT;
  PayloadBT payloadBT;  

You've created an alignment issue here which can be mitigated with struct packing.

To illustrate using the offsetof macro in <stddef.h> (C# must have something similar to handle C_structs)

On AVR: offsetof(PayloadBT, bt1) = 1

On PC:  offsetof(PayloadBT, bt1) = 4

 You could also re-arrange the struct to avoid the problem:

 typedef struct {
  char btstart;
  char reserved[3];
  float bt1; 
  float bt2; 
  float bt3;
  float bt4;
  float bt5;
  float bt6;  
  char btend;
  } PayloadBT;
  PayloadBT payloadBT;

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Do you have a working example... Demo, small thing in order to know where to put offsetof(PayloadBT, bt1) = 1. From a small working example I can learn allot.
Kind regards for your response

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The natural alignment in an AVR is byte wise packing. The micro is 8 bit so it is natural for data elements to simply be placed on the next byte boundary. The issue you face is not on the AVR but on a PC or any other 32bit+ receiver. 32 bit micros like to do memory fetches on 32 bit aligned boundaries. While something like ARM can do half or quarter word fetches to pick things up on 16 or 8 bit boundaries they tend to default to 4 byte/32 bit alignment.

 

So in an AVR:

typedef struct {
  char btstart;
  float bt1; 

this struct might be located at 0x137 and so bstart will be at that address and bt1 at the very next byte so it is at 0x138. But in a 32bit micro it wouldn't even place the whole structure at 0x137 in the first place. It would likely round that up to the nearest address so 0x138 then, while "bstart" is just an 8 bit element it would effectively be treated as 32bit with 24 bits unused. So it would occupy 0x138..0x13B (and depending on whether big or little endian either 0x138 or 0x13B would hod the active 8 bits). After that bt1 would be placed at 0x13C..0x13F

 

Your best bet is to try and persuade the "wide" device to act "narrow". It'll depend on the receiving software but there may be some form of packed(1) or align(1) or something you can use to over-rule its natural alignment.

 

But this is why people use "protocols" for getting data from one end to another. Things like JSON or XML or Protobufs or Python struct.pack or whatever because in these the data transport is always identical and it's then up to the sender/receiver to prepare or decode the data in the right format so that everyone can read and understand/interpret it in the same way. 

 

It's a bit too "hit and miss" to just rely on struct{} that are packed/aligned in some way or another (and then there's endianism to also be considered on top of that!)

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Since you are in arduino land it seems, just do something simple like this-

 

https://godbolt.org/z/gE9nFM

 

or make the floats an array-

https://godbolt.org/z/JRqGUY

 

You get the newlines as 'frame' delimiters, you get commas as field separators. Your c# code can easily parse the frames and fields and convert the values from ascii to whatever you want. There are plenty of places that tell you how to do things in c#, and the first thing to do would be to just see if you can print out the incoming frames. Then move on to parsing the frames by the comma, and so on.

 

 

 

 

Last Edited: Mon. Dec 2, 2019 - 07:57 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

As you're sending stuff over a radio link, it's fairly common to pack things tightly in pure binary to reduce the number of transmitted packets. When I did a radio link I found it was really important to not spillover into a second packet which could have been received before the first or even not at all.

 

You requested an example in #29 but I no longer think you need to worry about that, on the AVR side there is no padding.

 

I looked over your C# DataReceivedHandler and became confused. Are your reading binary data into a string type, then splitting on '\n' ? C# strings probably can contain zeros but what happens if your binary data contains 0x0d ?

 

I found this page which demonstrates various methods of parsing binary data (mostly as streams however, but I'm sure you can work around that)

 

https://www.codeproject.com/Articles/10750/Fast-Binary-File-Reading-with-C (#)

 

Last Edited: Mon. Dec 2, 2019 - 08:15 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi all, and thank you for all your support,

Sorry i was not so specific at the beginning,

I have a home project, i have this configuration 

Sensor > arduino  ATmega32u4>send struct > Bluetooth module >>>>>> >Bluetooth module> arduino ATmega32u4> receive struct > Pc app C# (must be C#)

 

Struct sent from one arduino to the other works well my problem is how to receive the struct in C# app,  (the biggest problem is my lack of experience with C#, and i have Visual studio , visual studio code ...) 

If i send multiple values separately i can receive them with no problem but i want to send them as a package (struct),here the issue appears how i receive it

 

The arduino code bare bone is similar with the one you all give me  (Thank you again)

Typedef struct {
  char Bt1start;
  float Bt2a;
  float Bt3a;
  float Bt4a;
  float Bt5a;
  float Bt6a;
  float Bt7a; 
  char Bt8end;
  } Payload;
  Payload payload; 

void setup() {
  Serial.begin(9600);

  }

void loop() {
  payload.Bt1start='#';
  payload.Bt2a=2.22;
  payload.Bt3a=3.33;
  payload.Bta=4.44;
  payload.Bt5a=5.55;
  payload.Bt6a=6.66;
  payload.Bt7a=7.77;
  payload.Bt8end='&';
}

template <class T> long int _writeAnything(int ee, T& valuebt)
{
  Serial.write('/');
  Serial.write((byte *) &valuebt, sizeof(valuebt));
}

payload.Bt1start='#';  payload.Bt8end='&';  are for testing if the payload was received correct 

Serial.write('/'); is to know when is ready to receive the payload

 

Now the C# app 

 

namespace ConsoleApp1
{
    class Program
    {
        public struct PayloadSerial
        {
            public char Bt1start;
            public float Bt2b;
            public float Bt3b;
            public float Bt4b;
            public float Bt5b;
            public float Bt6b;
            public float Bt7b;
            public char Bt8tend;
        }



        static SerialPort _serialPort;
        static char rc;
 


        public static unsafe void Main()
        {
            _serialPort = new SerialPort();
            _serialPort.PortName = "COM7";//Set your board COM
            _serialPort.BaudRate = 9600;
            //_serialPort.DataBits = 8;
            //_serialPort.Parity = Parity.None;
            //_serialPort.StopBits = StopBits.One;
            //_serialPort.Handshake = Handshake.None;
            _serialPort.DtrEnable = true;
            _serialPort.RtsEnable = true;
            _serialPort.Open();

           
            PayloadSerial payloadSerial;
            while (true)
            {
     
                char someText = (char)_serialPort.ReadChar();
                rc = someText;
                if (rc == '/')
                {

                    byte* p = (byte*)&payloadSerial;
                         int i;
                         for (i = 0; i < 26; i++)
                         {
                             *p++ = (byte)_serialPort.ReadByte();
                         }
                    //-------------------
                    //  if (payloadSerial.1start == '#' && payloadSerial.8end == '&') {

                     Console.WriteLine(payloadSerial.Bt2b);
                     Console.WriteLine(payloadSerial.Bt3b);
                     Console.WriteLine(payloadSerial.Bt4b);
                     Console.WriteLine(payloadSerial.Bt1tstart);
                     Console.WriteLine(payloadSerial.Bt8tend);
                     Console.WriteLine(payloadSerial.Bt5b);
                     Console.WriteLine(payloadSerial.Bt6b);
                     Console.WriteLine(payloadSerial.Bt7b);
                         Console.WriteLine(" ");
                         Console.WriteLine(" ");
                    Thread.Sleep(50);

                 }
            }

        }

    }
}

Please give me one example for the C# app something small how to shift the bits because if i find examples on internet and i try to put the in imy app i have issues of compile. For example i tried to use this "offsetof" but the examples over internet are more complex 

Kind regards

 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You have to tell the C# to pack the struct. Only you know how to do this.

 

Alternatively just receive the data as an anonymous byte block and decode the fields by splitting it.

 

Or use an agnostic transport format.

Last Edited: Wed. Dec 4, 2019 - 09:42 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I found this:

 

https://docs.microsoft.com/en-us...

 

There's also float conversion and byte reversal as well.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm spitting in the wind I know, but if you use ascii chars you do not have to worry about the data looking like the start/end delimiters. You end up with no need for start/end delimiters as a newline separates messages, and the comma is the field separator. You also then have no need to figure out data order and all the rest, and can also view these messages anywhere in the transmission chain and see whats going on in plain sight.

 

//sample message- 6 floats
string message = "1.1,2.2,3.3,4.4,5.5,6.6\n";
//from serial port instead
//string message = _serialPort.ReadLine();

 

//remove the line ending
message = message.Trim();

 

var fvalues = message.Split(',');
if( fvalues.Length == 6 ){ //if got 6 values, is ok
    foreach (var v in fvalues){
        Console.WriteLine(v); //the original ascii
        double d = double.Parse(v); //converted to double
        float f = float.Parse(v); //or converted to float
        Console.WriteLine(d); //back to ascii
        Console.WriteLine(f); //back to ascii
    }
}

 

 

can try at-

https://dotnet.microsoft.com/pla...

 

 

Last Edited: Wed. Dec 4, 2019 - 04:17 PM