아두이노와 Processing

와이파이 Processing 코딩에 의해 weMos 보드 조도센서 저항값 변화 그래프 관찰

coding art 2018. 4. 3. 17:03
728x90

이 한권의 책으로 아두이노 엘렉트로닉스 코딩에서 시작하여 와이파이 코딩을 넘어 흥미로운 앱인벤터 코딩으로 넘어가보자. 특별한 컴퓨터 과학의 지식이 없어도 누구든지 코딩의 세계로 초대 받을 수 있습니다. 교보문고에서 판매 중입니다.


__________________________________________________________________________________________________________________________________

본문 시작


weMos 보드는 아두이노 우노보드와 동일한 핀 배치를 가진다. 단 아두이노 우노 보드가 아날로그 측정 핀을 A0∼A5까지 6개를 제공하는 반면에 ESP8266 ESP-12E 와이파이 칩을 사용하는 weMos 보드는 1개의 아날로그 핀 A0를 가진다.
아두이노 우노 보드에 설치된 빵판의 조도센서 및 LED 배선을 분리하여 weMos 보드로 옮겨 보자. 아두이노 편집기에서 보드를 WeMos D1 으로 선택한다.


weMos 보드로 옮긴 다음의 사진을 참조하자.



아두이노 우노 보드에서 사용했던 코드를 컴파일 업로딩하여 실행시켜 보자. 시리얼 모니터에서 거의 비슷한 출력 결과를 볼 수 있을 것이다. weMos 보드에서  3.0 K옴 안팎의 조도 센서의 저항값이 출력되므로 10배로 확대한 값을 무선 와이파이가 설치된 PC의 Processing 코드로 전송하기로 하자.

weMos 보드에서 sine 함수값을 전송했던 Webserver_weMos_Processing_sine_01 코드를 수정해 사용하기로 한다.
weMos 보드에서 와이파이 데이터 전송을 위한 코딩이다. Processing 코드로부터 “GET/ HTTP/1.1” request 메시지를 받으면 아날로그 채널 A0에서 1K옴 저항(측정 값 815옴)에 가해진 전압 값을 읽어 전류를 계산한다. weMos 보드의 전원 전압 즉 arduVolt 값은 측정 값을 사용하고 1K옴에서의 전압 강하 값을 제하여 조도 센서에 걸린 전압을 계산한다.
앞서 계산된 전류와 조도센서 전압 값을 사용하여 조도 센서의 순간 저항 값을 계산한다.  흐린 날 실내에서 손 그림자를 사용하여 LED on OFF 가 가능한 값이 6K옴 안팎이다. 하지만 전송된 값을 받아 보는 Processing 코드에서 이 저항 값을 그리기 위해서는10배 곱하여 10∼100 사이로 데이터 값을 조정할 필요가 있다. 따라서 K옴 계산 식에서 아예100.0 으로 나누도록 한다.









그림은 흐린 날 실내 창가에서 손 그림자로 조도 센서를 막아 본 사례이다.







Webserver_weMos_Processing_01


#include <ESP8266WiFi.h>

 const char* ssid = "android1234";//무선 공유기 id로 수정
 const char* password = "dddddddddd";//무선 공유기 비빌번호

 String s;
 String strVolt;
 
 int measurePin = 0; //Connect variable resistor to A0 pin
 float arduVolt = 4.9; //아두이노 전압 실측치
 float r = 815; //1K옴 실측치
 int ledPin = D2;
 
 WiFiServer server(80);

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

  // prepare GPIO2
   pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, LOW);
    
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 

  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
 
  // Match the request

  int val;
  if (req.indexOf("GET / HTTP/1.0") != -1)  {
    val = 1;
    int analogV = analogRead(A0);//0-1023
    float V = arduVolt*analogV/(1023.0);//1K옴 저항 전압 환산
    float i = V/r;//1K옴 저항 전류 계산, 암페어
    float cdsV = arduVolt-V;//조도센서 전압 계산
    float cdsR = cdsV/i;//조도센서 저항 계산
    float cdsRk=cdsR/100.0; //K옴으로 환산 후 10배로 곱하기
    Serial.println(cdsRk,1);//시리얼 모니터 출력
    if( cdsR>6000) { // 6K옴 이하면 on
       digitalWrite(ledPin,HIGH);//어두우면 on
     }
    else {
        digitalWrite(ledPin, LOW);//밝으면 OFF
     }

  char buf[12];
  strVolt = dtostrf(cdsRk, 4, 0, buf);
  }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  client.flush();

// Prepare the response
  s = "";
  s += strVolt;
  s +="\n\r";
//  Serial.print(s);
  client.print(s);
  delay(50);

  Serial.println("Client disonnected");

}//끝

HTTPClient_weMos


// Graph Decoration //
int xPos = 1;         // horizontal position of the graph

String xLabel = "Time";
String yLabel = "CDs Resistance";
String Heading = "Real Time Data";
PFont font;

//Variables to draw a continuous line.
int lastxPos=1;
int lastheight=0;

import processing.net.*;

Client c;
String data;

void setup() {
 
  size(600, 400);
  background(50);
  fill(200); 
 
  stroke(127,34,255);     //stroke color
  strokeWeight(4);        //stroke wider
  Axis_center();
  stroke(127,34,0);     //stroke color
  strokeWeight(1); 
  Axis_ON_OFF();
  font = createFont("Arial",12);
  textAlign(CENTER);
  textFont(font);
  Labels();
 
  c = new Client(this, "192.168.0.11", 80);
  c.write("GET / HTTP/1.0\r\n");
  delay(50);
}

void draw() {

  if (c.available() > 0) { // If there's incoming data from the client...
    data = c.readString(); // ...then grab it and print it
    println(data);//    c.clear();
  }
 
  if (data != null) {
//    data = trim(data);                // trim off whitespaces.
    float inByte = float(data);           // convert to a number.
    inByte = map(inByte, 0, 300, 0, height); //map to the screen height.

    //Drawing a line from Last inByte to the new one.
    stroke(127,34,255);     //stroke color
    strokeWeight(4);        //stroke wider
    line(lastxPos, lastheight, xPos, height - inByte);
    lastxPos= xPos;
    lastheight= int(height-inByte);

    // at the edge of the window, go back to the beginning:
    if (xPos >= width) {
      xPos = 0;
      lastxPos= 0;
      background(0);  //Clear the screen.
    }
    else {
      // increment the horizontal position:
      xPos++;
    }
  }
 
  c = new Client(this, "192.168.0.11", 80);
  c.write("GET / HTTP/1.0\r\n");
  delay(1000);
 
 
}


void Axis_center()  {
// center line plot
  line(0,200,600,200);
  }
void Axis_ON_OFF()  {
// center line plot
  line(0,320,600,320);
  }
 
void Labels(){

 textFont(font,18);
 fill(180);
 rotate(radians(-90));
 text(yLabel,-200,20);
 textFont(font,16);
 
 textFont(font,18);
 rotate(radians(90));
 text(xLabel,300,380);
 textFont(font,24);
 fill(250);
 text(Heading,300,50);

}