Zum Inhalt springen
View in the app

A better way to browse. Learn more.

Fachinformatiker.de

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Probleme mit CRC16

Empfohlene Antworten

Veröffentlicht

Hallo zusammen,

ich möchte mit einem Gerät über ModBus kommuinizieren.

Laut Datenblatt wird hier als Prüfsumme ein CRC16-Code erwartet.

Da steht "X16+X15+X2+ 1". Das deute ich als ein Generatorpolynom 0xC003, oder?

Aber alles was ich bisher berechnet habe, scheint nicht zu stimmen.

Kann mir hier jemand mit nem Code weiterhelfen?

  • Autor

Also ich habe hier nach Wikipedia diesen Code zusammengebaut:


		ulong	ShiftReg;


		private ushort GenerateChecksum(byte[] buf, UInt16 polynom)

		{

			uint	bits	= (uint)buf.Length*8;


			ShiftReg	= 0x0000;


			while(bits > 0)

			{

					// letztes bit = 1				nächstes bit = 1

				if(((ShiftReg & 0x10000) != 0) != ((buf[0] & 0x80) != 0))

				{

					ShiftReg = (ulong)((ShiftReg << 1) ^ 0x18005);

				}

				else

				{

					ShiftReg = (ulong)(ShiftReg << 1);

				}

				ShiftArray(ref buf, 1);

				bits--;

			}


			return (ushort)ShiftReg;

		}

Aber leider liefert der ein falsches Ergebnis.

Kann den mal jemand angucken bzgl. Richtigkeit??

  • Autor
Ja, das hat mich auch verwirrt.

Das scheint aber ein Standardpolynom zu sein:

Habe jetzt herausgefunden, wie das zustandekommt.

Das Bit 16 entfällt einfach und dafür werden High und Low-Byte miteinander getauscht. Somit kommt als Polynom 0xA001 raus.

Ich hab hier jetzt auch ne Routine dazu. Allerdings berechnet diese nur immer das eine Byte richtig.

Kannst du dir das mal anschauen?


			crc16	= 0x00;


			for(int i=0; i<buf.Length; ++i)

				crc16	= calcCRC16r(crc16, buf[i], 0xA001);



uint calcCRC16r(uint crc, uint c, uint mask)

{

  byte i;

  for(i=0;i<8;i++)

  {

    if(((crc ^ c) & 1) != 0) { crc=(crc>>1)^mask; }

    else crc>>=1;

    c>>=1;

  }

  return (crc);

}

Archiv

Dieses Thema wurde archiviert und kann nicht mehr beantwortet werden.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.