728x90

아두이노의 Serial.write() 함수는  Serial 포트에 하나의 바이트 또는 그 이상의 바이트를 전송하는데 사용합니다. 주로 데이터 통신을 구현할 때 사용되며 Serial.print() 함수와 구분되어 사용합니다.

Serial.write() 함수는 숫자를 전송할 때 숫자 있는 그대로 전송합니다. 이는 숫자를 ASCII 코드로 변환하여 전송하는 Serial.print() 함수와 구분되며 일부 매개변수 입력에도 차이가 있습니다.

 

Serial.write()

 

Serial.write(val);
Serial.write(str);
Serial.write(buf, len);

매개변수(Parameters)
val : 1 바이트 데이터(0x00 ~ 0xFF)
str : 문자열(ex ‘A’, “Hello”)
buf : byte형 배열에 저장된 데이터, len 만큼 바이트 전송

반환값(Return)
size_t: write() : 전송한 byte 수

 

 

byte buff[10] = { 64, 'A', 0x42, 67, 68, 69, 70, 71, 72, 73};
 
void setup() {
  Serial.begin(115200);
}
 
void loop() {
  Serial.write(64);
  Serial.write("abc");
  Serial.write(buff, 5);
  Serial.println(" ");
  delay(1000);
}

위 예제를 아두이노 보드에 업로드하고 시리얼 모니터로 실행 결과를 보면 “@abc$ABCD” 이 반복적으로 출력될 것입니다.

하나씩 살펴보면

시리얼 모니터에서 수신된 <64>를 ASCII 값으로 판단하고 이에 해당하는 문자 ‘@’을 출력합니다. 문자열은 그대로 출력하여 “abc”가 이어서 출력되고 byte형 배열 중 5개의 데이터는 숫자는 ASCII 문자로, 문자는 문자로 출력합니다.

<64> → ‘@’
“abc” → “abc”
<36> → ‘$’
‘A’ → ‘A’
<0x42> → ‘B’
<67> → ‘C’
<68> → ‘D’

 

참고

아두이노 시리얼 모니터는 수신된 데이터를 ASCII 코드의 문자로 변화하여 출력합니다.  raw 데이터를 확인하기 위해서는 헥사(16진수) 값 등을 확인할 수 있는 별도의 시리얼 모니터 프로그램을 사용하셔야 합니다.

'홍익인간 프로젝트 > Arduino C' 카테고리의 다른 글

LiquidCrystal and Adafruit SSD1306(SSH1102) Collison  (0) 2021.03.19
delayMicroseconds()  (0) 2021.03.11
pulseIn() Function  (0) 2021.01.22
pinMode() Function  (0) 2021.01.22
What's means F() function ?  (0) 2021.01.14
728x90

노마드코더의 강의를 다시 들으려고 하면서 repository를 새로 만들게 되었다.
공부한 내용을 올리려고 하고 최초 커밋을 했는데
yarn.lock 파일에 보안취약문제가 있다고 alert를 받았다.

serialize-javascript 파일을 수정하는 작업을 진행했다. version을 2.1.1로 수정하고 다시 git에 커밋/푸쉬를 진행했는데도 alert가 사라지지 않았다.
결국, 저 위에 초록색 버튼 Create automated security update 버튼을 누르니 해당 alert가 사라졌다.
아마도 자동으로 github 에서 문제를 해결해주는 무언가를 내가 켰겠지..

2020. 1.28 내용 수정

2020년 1월 28일 !
새로운 공부내용을 repository에 올려서 넣으니 또 똑같은 문제가 발생했다!!
이번에는 serialize-javascript 를 직접 업그레이드 해보기로했다.
아래 사이트를 참고해서,
2.1.1 버전이었던 걸 업그레이드해서 2.1.2로 업그레이드 했고 !
해당 alert가 바로 사라지진 않았지만, 깃에서 준 조언대로 내가 행했기때문에
이게 더 정확한 방법같다

npm i serialize-javascript

참고사이트 : https://www.npmjs.com/package/serialize-javascript

automated security update 란?

repository에 의존성 관리의 취약점에 대한 alert를 받게 됬을 때, 해당 repository에 security update를 able로 해두면, Github에서 자동으로 의존성 취약점을 가진 파일들을 업그레이드하는 PR을 repository에 생성한다. 만약 내가 선택해서 의존성 파일을 업그레이드하고, PR을 생성하려면 해당 기능을 disable하게 만들면 된다. Automated security request가 오면 빠르게 리뷰를 하고, merge를 해야한다.

이 문제를 해결하려고 하다가 serialize가 무엇인가에 대해서 문득 궁금해졌다.

serialize란 무엇인가?

서로 다른 언어나 형태를 가지고 있는 것들을 서로 이해할 수 있도록 형태를 잡아서 묶어주는 것을 Serialization이라고 함.(예를 들어, DB와 프로그래밍 언어형태가 다른데 서로 알아들을 수 있는 형태로 묶어주는 것을 말함)

  • JS에서 JSON.stringify() 함수를 호출하는 것과 비슷한 역할을 함(객체를 json 으로 만드는 것과 비슷)
  • serialization은 생각보다 많이 쓰인다.

위의 방법 외에 다른 해결방법을 찾다가, .gitignore에 yarn.lock 파일을 넣으면 해결이 된다는 글을 찾게 되었고, gitignore과 yarn.lock에 대해서 알아보았다.
결론을 말하자면 yarn.lock 파일은 gitignore에 넣지 않고, git에서 관리할 수 있게끔 commit을 하는 것이 좋다.

.gitignore 파일이란?

git 버전관리에서 제외(github에 업로드하지않을 파일 목록)할 파일 목록을 지정하는 파일
.gitignore이 파일명이며, 해당 파일 목록에 들어가는 대표적인 것은 node_modules 가 있음.
node_modules 정보는 이미 package.json에 명시가 되어있기때문에
언제든 쉽게 모듈을 설치할 수 있어서 github에 굳이 올리지않아도 되어, gitignore 파일에 넣는다.
그리고 node_modules는 크기가 크다! 그래서 git에 안올려도되면 안올리는 게 좋음!

.gitignore 파일 설정법

리액트 CRA를 하고 git을 연결하면 자연스럽게 .gitignore 파일이 생김
.gitignore 파일안에 무시할 대상 경로만 넣어주면 됨!
요렇게 파일 안에다가 경로표시하고, 이름을 적으면 된다!

yarn이란?

자바스크립트 패키지 매니저로서, npm과 가장 많이 쓰이는 manager.
yarn을 사용해서 프로젝트에 새로운 패키지를 설치하면, yarn.lock이 자동으로 생성된다.

Yarn.lock이란?

Yarn 패키지 매니저의 패키지 잠금파일!

잠금파일이 왜 필요할까?

설치가 필요한 패키지들이 package.json 파일에 등록되어있으면, 해당 파일을 통해 모두가 npm이나 yarn 설치 명령어로 모든 패키지를 버전에 맞게 설치할 수 있음.
그러나, 설치하는 시점에 따라 패키지버전이 달라짐
(왜? package.json에는 특정버전으로 지정되어있는 것이 아니라, SemVer 규칙에 따라 범위로 지정되어있음)
서로 다른 패키지를 설치해서 사용하면 개발자 간의 혼선이 생길 수 있기때문에, 패키지 잠금파일이 생김!
<yarn.lock>

# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. # yarn lockfile v1 "@babel/code-frame@7.5.5", "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.5.5": version "7.5.5" resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.5.5.tgz#bc0782f6d69f7b7d49531219699b988f669a8f9d" integrity sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw== dependencies: "@babel/highlight" "^7.0.0" "@babel/core@7.7.4", "@babel/core@^7.1.0", "@babel/core@^7.4.5": version "7.7.4" resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.7.4.tgz#37e864532200cb6b50ee9a4045f5f817840166ab" integrity sha512-+bYbx56j4nYBmpsWtnPUsKW3NdnYxbqyfrP2w9wILBuHzdfIKz9prieZK0DFPyIzkjYVUe4QkusGL07r5pXznQ== dependencies: "@babel/code-frame" "^7.5.5" "@babel/generator" "^7.7.4" "@babel/helpers" "^7.7.4" "@babel/parser" "^7.7.4" "@babel/template" "^7.7.4" "@babel/traverse" "^7.7.4" "@babel/types" "^7.7.4" //일부만 발췌

  • 참고 : NPM(Node Packaged Mananger의 약자)
    NPM을 실행하면, package-lock.json이 생성됨

<package-lock.json>

{ "name": "movie-app-2019", "version": "0.1.0", "lockfileVersion": 1, "requires": true, "dependencies": { "@babel/code-frame": { "version": "7.5.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", "requires": { "@babel/highlight": "^7.0.0" } }, "@babel/core": { "version": "7.7.4", "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.7.4.tgz", "integrity": "sha512-+bYbx56j4nYBmpsWtnPUsKW3NdnYxbqyfrP2w9wILBuHzdfIKz9prieZK0DFPyIzkjYVUe4QkusGL07r5pXznQ==", "requires": { "@babel/code-frame": "^7.5.5", "@babel/generator": "^7.7.4", "@babel/helpers": "^7.7.4", "@babel/parser": "^7.7.4", "@babel/template": "^7.7.4", "@babel/traverse": "^7.7.4", "@babel/types": "^7.7.4", "convert-source-map": "^1.7.0", "debug": "^4.1.0", "json5": "^2.1.0", "lodash": "^4.17.13", "resolve": "^1.3.2", "semver": "^5.4.1", "source-map": "^0.5.0" }, "dependencies": { "debug": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "requires": { "ms": "^2.1.1" } }, "semver": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" }, "source-map": { "version": "0.5.7", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz", "integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=" } } }, } //일부만 발췌

yarn.lock 파일을 gitignore에 넣어도될까?

답은 NO!

yarn.lock 파일은 설치시점이 달라도 일관된 패키지 버전을 유지할 수 있게 하기때문에 git 저장소에 올려서 관리되어야 함!!

다음번에는 npm에 대해서도 공부를 해보도록 해야겠다!

참고자료: git hub , 'https://www.daleseo.com/js-package-locks/'

 

 

--

yarn.lock 을 통해서 패키지 파일을 관리하게 되는데, yarn.lock 파일에서 core file 이 업데이트 된 경우에, 해당 파일의 내용을 바꾸지 않으면 Pull Request 시에 Version Collison 이 발생한다.

 

따라서 git fecth 를 통해 해당 내용을 업데이트 해줬다.

 

728x90

The String object's charAt() method returns a new string consisting of the single UTF-16 code unit located at the specified offset into the string.

 

Syntax

let character = str.charAt(index)

Parameters

indexAn integer between 0 and str.length - 1. If the index cannot be converted to the integer or no index is provided, the default is 0, so the first character of str is returned.

Return value

A string representing the character (exactly one UTF-16 code unit) at the specified index. If index is out of range, charAt() returns an empty string.

Description

Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character—in a string called stringName—is stringName.length - 1. If the index you supply is out of this range, JavaScript returns an empty string.

If no index is provided to charAt(), the default is 0.

Examples

Displaying characters at different locations in a string

The following example displays characters at different locations in the string "Brave new world":

var anyString = 'Brave new world';
console.log("The character at index 0   is '" + anyString.charAt()   + "'");
// No index was provided, used 0 as default

console.log("The character at index 0   is '" + anyString.charAt(0)   + "'");
console.log("The character at index 1   is '" + anyString.charAt(1)   + "'");
console.log("The character at index 2   is '" + anyString.charAt(2)   + "'");
console.log("The character at index 3   is '" + anyString.charAt(3)   + "'");
console.log("The character at index 4   is '" + anyString.charAt(4)   + "'");
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");

These lines display the following:

 

The character at index 0   is 'B'

The character at index 0   is 'B'
The character at index 1   is 'r'
The character at index 2   is 'a'
The character at index 3   is 'v'
The character at index 4   is 'e'
The character at index 999 is ''

 

 

Getting whole characters

The following provides a means of ensuring that going through a string loop always provides a whole character, even if the string contains characters that are not in the Basic Multi-lingual Plane.

var str = 'A \uD87E\uDC04 Z'; // We could also use a non-BMP character directly
for (var i = 0, chr; i < str.length; i++) {
  if ((chr = getWholeChar(str, i)) === false) {
    continue;
  }
  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning a variable to represent the
  // individual character

  console.log(chr);
}

function getWholeChar(str, i) {
  var code = str.charCodeAt(i);

  if (Number.isNaN(code)) {
    return ''; // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return str.charAt(i);
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate';
    }
    var next = str.charCodeAt(i + 1);
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate';
      }
      return str.charAt(i) + str.charAt(i + 1);
  }
  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate';
  }
  var prev = str.charCodeAt(i - 1);

  // (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate';
  }
  // We can pass over low surrogates now as the second component
  // in a pair which we have already processed
  return false;
}

In an ECMAScript 2016 environment which allows destructured assignment, the following is a more succinct and somewhat more flexible alternative in that it does increment for an incrementing variable automatically (if the character warrants it in being a surrogate pair).

let str = 'A\uD87E\uDC04Z'  // We could also use a non-BMP character directly
for (let i = 0, chr; i < str.length; i++) {
  [chr, i] = getWholeCharAndI(str, i)

  // Adapt this line at the top of each loop, passing in the whole string and
  // the current iteration and returning an array with the individual character
  // and 'i' value (only changed if a surrogate pair)

  console.log(chr)
}

function getWholeCharAndI(str, i) {
  let code = str.charCodeAt(i)

  if (Number.isNaN(code)) {
    return ''  // Position not found
  }
  if (code < 0xD800 || code > 0xDFFF) {
    return [str.charAt(i), i]  // Normal character, keeping 'i' the same
  }

  // High surrogate (could change last hex to 0xDB7F to treat high private
  // surrogates as single characters)
  if (0xD800 <= code && code <= 0xDBFF) {
    if (str.length <= (i + 1)) {
      throw 'High surrogate without following low surrogate'
    }
    let next = str.charCodeAt(i + 1)
      if (0xDC00 > next || next > 0xDFFF) {
        throw 'High surrogate without following low surrogate'
      }
      return [str.charAt(i) + str.charAt(i + 1), i + 1]
  }

  // Low surrogate (0xDC00 <= code && code <= 0xDFFF)
  if (i === 0) {
    throw 'Low surrogate without preceding high surrogate'
  }

  let prev = str.charCodeAt(i - 1)

  // (could change last hex to 0xDB7F to treat high private surrogates
  // as single characters)
  if (0xD800 > prev || prev > 0xDBFF) {
    throw 'Low surrogate without preceding high surrogate'
  }

  // Return the next character instead (and increment)
  return [str.charAt(i + 1), i + 1]
}

Fixing charAt() to support non-Basic-Multilingual-Plane (BMP) characters

While the previous example may be more useful for programs that must support non-BMP characters (since it does not require the caller to know where any non-BMP character might appear), in the event that one does wish, in choosing a character by index, to treat the surrogate pairs within a string as the single characters they represent, one can use the following:

function fixedCharAt(str, idx) {
  let ret = ''
  str += ''
  let end = str.length

  let surrogatePairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
  while ((surrogatePairs.exec(str)) != null) {
    let lastIdx = surrogatePairs.lastIndex
    if (lastIdx - 2 < idx) {
      idx++
    } else {
      break
    }
  }

  if (idx >= end || idx < 0) {
    return ''
  }

  ret += str.charAt(idx)

  if (/[\uD800-\uDBFF]/.test(ret) && /[\uDC00-\uDFFF]/.test(str.charAt(idx + 1))) {
    // Go one further, since one of the "characters" is part of a surrogate pair
    ret += str.charAt(idx + 1)
  }
  return ret
}
728x90

오늘은 JavaScript의 형변환에 대해서 알아보겠습니다. 하는 법이 있다는 것은 알고있는데 머리에 다 담고 살기는 너무 어려운 것 같습니다. 그러니 공부방에 정리해 놓아야 겠습니다.

 

 

일단 먼저 자바스크립트에서 변수를 선언하는 것부터 알아보겠습니다.

 

var 변수 = 10;

 

위에서 선언한 내용은 변수를 숫자 10으로 선언하는 것입니다.

 

var 변수 = "10";

 

얼핏보면 같은 것으로 생각 할수도 있지만 언어를 공부하신 분이라면 다들 눈치 채셨을 겁니다. 이번엔 변수를 문자열 10으로 선언하는 것입니다.

 

기존의 Java 같은 경우는 int 변수, String 변수 등 해당하는 형으로 선언하는 것이 맞지만 자바스크립트는 조금 다릅니다. 일단 모든 변수를 var로 선언 가능합니다.

 

- 문자형을 숫자형으로 변환하기

 

var 변수 = parseInt(문자);    //문자를 정수형 숫자로 변환해줌

var 변수 = parseFloat(문자);     //문자를 실수형 숫자로 변환해줌

var 변수 = Nember(문자);    //문자를 정수&실수형 숫자로 변환해줌

 

예제)

var x = "999";    //문자형 999

var y = "99.99";    //문자형 99.99

var a = parseInt(x);    //숫자형 정수 999

var b = parseInt(y);    //숫자형 정수 99

var a = parseFloat(x);    //숫자형 실수 999

var b = parseFloat(y);    //숫자형 실수 99.99

var a = Number(x);    //숫자형 정수 999

var b = Number(y);    //숫자형 실수 99.99

 

var x = "a999";    //문자형 a999

var y = "a99.99";    //문자형 a99.99

var a = parseInt(x);    //숫자형 NaN

var b = ParseInt(y);    //숫자형 NaN

var a = parseFloat(x);    //숫자형 NaN

var b = parseFloat(y);    //숫자형 NaN

var a = Number(x);    //숫자형 NaN

var b = Number(y);    //숫자형 NaN

 

※ 문자열 맨앞에 문자로 시작하면 형변환을 해도 값을 인식하지 못한다.

 

var x = "999a9";    //문자열 999a9

var y = "99.9a9";    //문자열 99.9a9

var a = parseInt(x);    //숫자형 999

var b = parseInt(y);    //숫자형 99

var a = parseFloat(x);    //숫자형 999

var b = parseFloat(y);    //숫자형 99.9

var a = Number(x);    //숫자형 NaN

var b = Number(y);    //숫자형 NaN

 

- 숫자형을 문자형으로 변환하기

 

 

var 변수 = String(숫자);    //숫자를 문자로 변환해줌

var 변수 = 숫자.toString(진법);    //숫자를 문자로 변환해줌 - 변환하면서 진법을 바꿀 수 있음

var 변수 = 숫자.toFixed(소수자리수);    //숫자를 문자로 변환해줌 - 실수형의 소수점 자리를 지정할 수 있음

var 변수 = 숫자 + "문자열";    //숫자와 문자열을 한 문자열로 더해줌

 

var x = 123;    //숫자형 123

var a = String(x);    //문자형 123

var a = x.toString();    //문자형 123

var a = x.toString(2);    //문자형 1111011(2진법)

var a = x.toString(16);    //문자형 7b(16진법)

var a = x.toFixed();    //문자형 123

var a = x.toFixed(1);    //문자형 123.0

 

var y = 99.999;    //숫자형 99.999

var a = x.toFixed();    //문자형 99

var a = x.toFixed(1);    //문자형 99.9

var a = x.toFixed(3);    //문자형 99.999

var a = x.toFixed(4);    //문자형 99.9990

 

확률을 표현해줄 때 유용하다.

 

var z = 9;    //숫자형 9

var a = a + "ElNino Torres";    //문자형 9ElNino Torres

 

이정도만 알고 있어도 자바스크립트를 사용하는데 편리할 듯 싶습니다. 추후에 기회가 되면 다른 메소드들도 알아보도록 해야겠습니다.

+ Recent posts