Checksum

์ฒดํฌ์ธ์€ ๋ง์…ˆ์„ ํ†ตํ•ด์„œ ์˜ค๋ฅ˜๋ฅผ ๊ฒ€์ถœํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ, 1์˜ ๋ณด์ˆ˜๋ฅผ ์ด์šฉํ•œ๋‹ค. ๋ง์…ˆ๋งŒ ์ด์šฉํ•˜๋ฏ€๋กœ ๊ต‰์žฅํžˆ ๋น ๋ฅด๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค. Sender๋Š” ๋ณด๋‚ด๊ณ ์žํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ „๋ถ€ ๋”ํ•˜๊ณ  1์˜ ๋ณด์ˆ˜ํ™”๋ฅผ ํ•˜์—ฌ Checksum์„ ๋งŒ๋“ ๋‹ค. ๋ณด๋‚ด๊ณ ์ž ํ•˜๋Š” ๋ฐ์ดํ„ฐ ๋งˆ์ง€๋ง‰์— Checksum์„ ๊ฐ™์ด ์‹ค์–ด์„œ ๋ณด๋‚ธ๋‹ค. Reciever ์ธก์—์„œ๋Š” ๋ฐ›์€ ๋ฐ์ดํ„ฐ์™€ Checksum์˜ ๊ฐ’์„ ๋”ํ•˜์—ฌ 0์ด ๋˜๋Š”์ง€ ํ™•์ธํ•œ๋‹ค. ๋”ํ–ˆ์„ ๋•Œ 0์ด ๋‚˜์˜ค์ง€ ์•Š์œผ๋ฉด ์ „์†ก ์ค‘์— ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ•œ ๊ฒƒ์ด๋‹ค. ๋˜๋Š” Reciever ์ธก์—์„œ Checksum์˜ ๊ฐ’๊ณผ Checksum์„ ์ œ์™ธํ•œ ๋ฐ›์€ ๋ฐ์ดํ„ฐ๋“ค์„ ๋‹ค ๋”ํ•œ ๊ฐ’์˜ 1์˜ ๋ณด์ˆ˜ํ™”ํ•œ ๊ฐ’์ด ๊ฐ™์€์ง€ ํ™•์ธํ•˜๋Š” ๋ฐฉ๋ฒ•๋„ ์žˆ๋‹ค.

๋ฒ„ํผ์˜ ํฌ๊ธฐ๋Š” 7๋กœ ๊ณ ์ •๋˜์–ด ์žˆ๋‹ค. ํฌ๊ธฐ๊ฐ€ ๊ณ ์ •๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— End Flag๋Š” ๋‘์ง€ ์•Š์•˜๋‹ค. ์ „์†ก๋˜๋Š” ๋ฐ์ดํ„ฐ์˜ Header๋Š” 2๊ฐœ๋กœ ๋ชจ๋‘ 0xFF์˜ ๊ฐ’์„ ๊ฐ€์ง€๋ฉฐ Checksum ๊ณ„์‚ฐ์—๋Š” ํฌํ•จํ•˜์ง€ ์•Š๋Š”๋‹ค. ๋‹ค์Œ์€ ๊ฐ„๋‹จํ•œ Checksum ๊ตฌํ˜„ ์ฝ”๋“œ์ด๋‹ค.

Sender

const DATA_LEN = 7;
HEADER_LEN = 2;
var data = [START_SYS, START_SYS, CMD1, CMD2, VAL1, VAL2, VAL3];

var checksum,
  sum = 0;

for (var i = HEADER_LEN; i < DATA_LEN - HEADER_LEN; i++) sum += data[i];

checksum = ~sum;
data.push(checksum);

Receiver

const DATA_LEN = 7;
HEADER_LEN = 2;

var sum = 0,
  i = 0,
  result;

for (i = HEADER_LEN; i < DATA_LEN - HEADER_LEN; i++) sum += recievedData[i];

sum += recievedData[i]; //์ˆ˜์‹ ๋œ checksum์„ ๋”ํ•จ
result = ~sum;

if (result == 0) console.log("NO ERROR IN TRANSMISSION");
else console.log("ERROR DETECTED");