Простой последовательный протокол связи точка-точка

Если это приглашение Anaconda, и вы в этом уверены, щелкните правой кнопкой мыши по нему, выберите свойства и измените комментарий на «Anaconda Prompt».

enter image description here

55
задан 11 revs, 2 users 100% 6 May 2009 в 08:19
поделиться

10 ответов

I would use HDLC. I have had good luck with it in the past. I would for a point to point serial just use the Asynchronous framing and forget about all of the other control stuff as it would probably be overkill.

In addition to using HDLC for the framing of the packet. I format my packet like the following. This is how options are passed using 802.11

U8 cmd;
U8 len;
u8 payload[len];

The total size of each command packet is len +2

You then define commands like

#define TRIGGER_SENSOR 0x01
#define SENSOR_RESPONSE 0x02

The other advantage is that you can add new commands and if you design your parser correctly to ignore undefined commands then you will have some backwards compatibility.

So putting it all together the packet would look like the following.

 // total packet length minus flags len+4
 U8 sflag;   //0x7e start of packet end of packet flag from HDLC
 U8 cmd;     //tells the other side what to do.
 U8 len;     // payload length
 U8 payload[len];  // could be zero len
 U16 crc;
 U8 eflag;   //end of frame flag

The system will then monitor the serial stream for the flag 0x7e and when it is there you check the length to see if it is pklen >= 4 and pklen=len+4 and that the crc is valid. Note do not rely on just crc for small packets you will get a lot of false positives also check length. If the length or crc does not match just reset the length and crc and start with decoding the new frame. If it is a match then copy the packet to a new buffer and pass it to your command processing function. Always reset length and crc when a flag is received.

For your command processing function grab the cmd and len and then use a switch to handle each type of command. I also require that a certain events send a response so the system behaves like a remote procedure call that is event driven.

So for example the sensor device can have a timer or respond to a command to take a reading. It then would format a packet and send it to the PC and the PC would respond that it received the packet. If not then the sensor device could resend on a timeout.

Also when you are doing a network transfer you should design it as a network stack like the OSI modle as Foredecker points don't forget about the physical layer stuff. My post with the HDLC is the data link layer and the RPC and command handling is the Application Layer.

38
ответ дан 7 November 2019 в 07:27
поделиться

RS232 protocols are tricky. The suggestion to use HDLC, is a good one, but its not the entire solution. There are other things you need to decide:

  • How will the baud rate between the two devices be determined? Autobuad? Predefined, or set explicate?
  • Will you do flow control in software or hardware or both? Note, if you use hardware flow control then you must make sure, that the cables are built correctly.
  • Speaking of cables, this is a huge pain with RS233. Depending on the device, you may need to use a straight through cable, or a cross over cable, or a variant.
  • Using a software based flow control mechanism can be effective as it allows the most simple cable to be used - just three wired (TX, RX, and common).
  • Do you pick a 7 or 8 bit word?
  • HW parity or software error checking.

I suggest you go with 8 data bits, no hardware parity, 1 stop bit, and use software based flow control. You should use autobaud if your hardware supports it. If not, then autobaud is devilishly difficult to do in software.

10
ответ дан 7 November 2019 в 07:27
поделиться

Here's an alternative protocol:

u8  Sync          // A constant value which always marks the start of a packet
u16 Length        // Number of bytes in payload
u8  Data[Length]  // The payload
u16 Crc           // CRC

Use RS232/UART, as the PC (serial port) and the processor (UART) can already handle that with minimum fuss (just need a MAX232 chip or similar to do the level shifting).

And using RS232/UART, you don't have to worry about master/slave if it's not relevant. Flow control is available if necessary.

Suggested PC software: either write your own, or Docklight for simple monitoring and control (evaluation version is free).

For greater error checking, simplest is parity checking, or if you need something more powerful, maybe convolutional coding.

In any case, whatever you do: keep it simple!

EDIT: Using RS232 with a PC is even easier than it used to be, as you can now get USB to RS232/TTL converters. One end goes into your PC's USB socket, and appears as a normal serial port; the other comes out to 5 V or 3.3 V signals that can be connected directly to your processor, with no level-shifting required.

We've used TTL-232R-3V3 from FDTI Chip, which works perfectly for this kind of application.

3
ответ дан 7 November 2019 в 07:27
поделиться

Вы не указываете, как именно ведет себя микроконтроллер, но будет ли все, что передано с микроконтроллера, прямым ответом на команду с ПК? Если да, то кажется, что вы можете использовать какой-нибудь протокол master / slave (это, как правило, самое простое решение). Если обе стороны могут инициировать связь, вам нужен более общий протокол канального уровня. HDLC является классическим протоколом для этого. Хотя полный протокол, вероятно, является излишним для ваших нужд, вы можете, например, по крайней мере использовать тот же формат кадра. Вы также можете взглянуть на PPP , чтобы узнать, есть ли что-то полезное.

0
ответ дан 7 November 2019 в 07:27
поделиться

My suggestion is modbus. Это эффективный и простой стандартный протокол для связи с устройствами, имеющими датчики и параметры (например, ПЛК). Вы можете получить спецификации на http://www.modbus.org . Он существует с 1979 года и набирает популярность, у вас не будет проблем с поиском примеров и библиотек.

5
ответ дан 7 November 2019 в 07:27
поделиться

может быть, этот вопрос может быть совершенно глупым, но кто-нибудь рассматривал возможность использования одного из протоколов X / Y / Z MODEM ?

Основное преимущество использования одного из указанных выше Протоколы - это большая доступность готовых к использованию реализаций в различных средах программирования.

0
ответ дан 7 November 2019 в 07:27
поделиться

My only suggestion is if you need noise-resistant you might want to use full-duplex RS-422/485. You can use an IC similar to this on the AVR side, then an RS-232->RS-422 converter on the PC side like the 485PTBR here. If you can find or make a shielded cable (two twisted shielded pairs) then you'll have even more protection. And all of this is invisible to the micro and PC - no software changes.

Whatever you do make sure that you are using a full-duplex system and make sure the read/write enable lines are asserted on the IC.

2
ответ дан 7 November 2019 в 07:27
поделиться

Что касается проверок на четность (поскольку они здесь встречаются несколько раз):

Они в основном бесполезны. Если вас беспокоит, что один бит может быть изменен по ошибке, то весьма вероятно, что второй бит также может измениться, и вы получите ложное срабатывание при проверке четности.

Используйте что-нибудь легкое, например CRC16, с поиском table - его можно вычислить по мере получения каждого байта и, по сути, это просто XOR. Предложение Стива Мельникоффа отлично подходит для небольших микропрограмм.

Я бы также предложил передавать удобочитаемые данные, а не необработанные двоичные данные (если производительность не является вашим главным приоритетом). Это сделает отладку и файлы журнала намного более приятными.

2
ответ дан 7 November 2019 в 07:27
поделиться

There are some good answers in here, here are some useful pointers:

Even if your packets are not time-separated, the sync byte is an essential way of reducing the number of places you need to attempt to construct a packet from. Your devices will often have to deal with a bunch of junk data (i.e the end of a packet in flight when they turned on, or result of a hardware collision). Without a sync byte you will have to try to make a packet out of every byte you receive. The sync byte means that only 1/255 bytes of random noise could be the first byte of your packet. Also FANTASTIC when you want to snoop on your protocol.

Having an address on your packets or even just a bit saying master / slave or pc / device is useful when you look at the packets via a snoop tool of some type or another. You might do this by having a different sync byte for the PC than the DEVICE. Also, this will mean a device will not respond to its own echo.

You might want to look into error correction (such as Hamming). You package 8 bit of data into a 12 bit protected byte. Any one of those 12 bits can be flipped en-route and the original 8 bits retrieved. Useful for data storage (used on CDs) or where the device can't re-send easily (satellite links, one-way rf).

Packet numbers make life easier. A packet sent carries a number, responses carry the same number an a flag saying "response". This means that packets that never arrived (sync corrupted say) are easily detected by the sender and in full-duplex mode with a slow link, two commands can be sent before the first response is received. This also makes protocol analysis easier (A third party can understand which packets were received with no knowledge of the underlying protocol)

Having a single master is an awesome simplification. That said, in a full-duplex environment it does not matter much at all. Suffice to say you should always do it unless you are trying to save power or you are doing something event driven at the device end (input state changed, sample ready).

8
ответ дан 7 November 2019 в 07:27
поделиться

SLIP и UDP. Шутки в сторону.

Все ПК и подобные устройства говорят на нем.

Есть хорошая книга и примеры из TCP Lean

Джереми Бентам тайно получил PIC, выполняющий работающий TCP / IP. AVR ничем не хуже PIC, верно?

Я бы порекомендовал UDP, это чертовски просто.

-2
ответ дан 7 November 2019 в 07:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: