Arduino Uno - ESP8266 ESP-01 Serial Wireless WIFI Module

OS/Arduino 2018.02.23 17:12 Posted by 파란크리스마스

출처 : GitHub - bportaluri/WiFiEsp: Arduino WiFi library for ESP8266 modules
GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.

WiFiEsp / ConnectWPA,ino

출처 : GitHub - bportaluri/WiFiEsp: Arduino WiFi library for ESP8266 modules

/*
 WiFiEsp example: ConnectWPA
 
 This example connects to an encrypted WiFi network using an ESP8266 module.
 Then it prints the  MAC address of the WiFi shield, the IP address obtained
 and other network details.

 For more details see: http://yaab-arduino.blogspot.com/p/wifiesp-example-connect.html
*/

#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "Twim";            // your network SSID (name)
char pass[] = "12345678";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

void setup()
{
  // initialize serial for debugging
  Serial.begin(115200);
  // initialize serial for ESP module
  Serial1.begin(115200);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
}

void loop()
{
  // print the network connection information every 10 seconds
  Serial.println();
  printCurrentNet();
  printWifiData();
  
  delay(10000);
}

void printWifiData()
{
  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print your MAC address
  byte mac[6];
  WiFi.macAddress(mac);
  char buf[20];
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
  Serial.print("MAC address: ");
  Serial.println(buf);
}

void printCurrentNet()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to
  byte bssid[6];
  WiFi.BSSID(bssid);
  char buf[20];
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", bssid[5], bssid[4], bssid[3], bssid[2], bssid[1], bssid[0]);
  Serial.print("BSSID: ");
  Serial.println(buf);

  // print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("Signal strength (RSSI): ");
  Serial.println(rssi);
}

arduino-ESP8266 / Complete.ino

출처 : GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.

#include <SoftwareSerial.h>

#include "ESP8266.h"

SoftwareSerial esp8266Serial = SoftwareSerial(6, 7); // RX, TX
ESP8266 wifi = ESP8266(esp8266Serial);

void setup()
{
    Serial.begin(115200);

    // ESP8266
    esp8266Serial.begin(115200);
    wifi.begin();
    wifi.setTimeout(1000);

    /****************************************/
    /******       Basic commands       ******/
    /****************************************/
    // test
    /*Serial.print("test: ");
    Serial.println(getStatus(wifi.test()));*/

    // restart
    /*Serial.print("restart: ");
    Serial.println(getStatus(wifi.restart()));*/

    // getVersion
    char version[16] = {};
    Serial.print("getVersion: ");
    Serial.print(getStatus(wifi.getVersion(version, 16)));
    Serial.print(" : ");
    Serial.println(version);

    // deepSleep
    /*Serial.print("deepSleep: ");
    Serial.println(wifi.deepSleep(5000));*/

    // setBaudrate
    /*Serial.print("setBaudrate: ");
    Serial.println(wifi.setBaudrate(9600));*/

    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // setWifiMode
    Serial.print("setWifiMode: ");
    Serial.println(getStatus(wifi.setMode(ESP8266_WIFI_ACCESSPOINT)));

    // getWifiMode
    ESP8266WifiMode mode;
    Serial.print("getWifiMode: ");
    Serial.println(getStatus(wifi.getMode(&mode)));

    // joinAP
    /*Serial.print("joinAP: ");
    Serial.println(getStatus(wifi.joinAP("ssid", "password")));*/

    // getAP
    /*char ap[32] = {};
    Serial.print("getAP: ");
    Serial.print(getStatus(wifi.getAP(ap)));
    Serial.print(" : ");
    Serial.println(ap);*/

    // quitAP
    /*Serial.print("quitAP: ");
    Serial.println(getStatus(wifi.quitAP()));*/

    // setAPConfiguration
    Serial.print("setAPConfiguration: ");
    Serial.println(getStatus(wifi.setAPConfiguration("ESP8266", "awesomelib", 10, ESP8266_ENCRYPTION_WPA_WPA2_PSK)));
    wifi.restart();

    // getAPConfiguration
    char ssid[32] = {};
    char password[63] = {};
    uint8_t channel;
    ESP8266Encryption encryption;
    Serial.print("getAPConfiguration: ");
    Serial.print(getStatus(wifi.getAPConfiguration(ssid, password, channel, encryption)));
    Serial.print(" : ");
    Serial.print(ssid);
    Serial.print(" - ");
    Serial.print(password);
    Serial.print(" - ");
    Serial.print(channel);
    Serial.print(" - ");
    Serial.println(encryption);

    // setDHCP
    Serial.print("setDHCP STA: ");
    Serial.println(getStatus(wifi.setDHCP(ESP8266_WIFI_STATION, false)));
    Serial.print("setDHCP AP: ");
    Serial.println(getStatus(wifi.setDHCP(ESP8266_WIFI_ACCESSPOINT, true)));

    // setMAC
    /*byte mac[6] = {0x11, 0x11, 0x11, 0x11, 0x11, 0x11};
    Serial.print("setMAC AP: ");
    Serial.println(getStatus(wifi.setMAC(ESP8266_WIFI_ACCESSPOINT, mac)));*/

    // getMAC
    byte mac[6] = {};
    Serial.print("getMAC STA: ");
    Serial.print(getStatus(wifi.getMAC(ESP8266_WIFI_STATION, mac)));
    Serial.print(" : ");
    for (uint8_t i = 0; i < 6; i++) {
      Serial.print(mac[i], HEX);
      if (i < 5)
        Serial.print(":");
    }
    Serial.println();
    Serial.print("getMAC AP: ");
    Serial.print(getStatus(wifi.getMAC(ESP8266_WIFI_ACCESSPOINT, mac)));
    Serial.print(" : ");
    for (uint8_t i = 0; i < 6; i++) {
      Serial.print(mac[i], HEX);
      if (i < 5)
        Serial.print(":");
    }
    Serial.println();

    // setIP
    /*IPAddress ipAP = IPAddress(10, 0, 4, 1);
    Serial.print("setIP AP: ");
    Serial.print(getStatus(wifi.setIP(ESP8266_WIFI_ACCESSPOINT, ipAP)));
    Serial.print(" : ");
    Serial.println(ipAP);*/

    // getIP
    IPAddress ip;
    Serial.print("getIP STA: ");
    Serial.print(getStatus(wifi.getIP(ESP8266_WIFI_STATION, ip)));
    Serial.print(" : ");
    Serial.println(ip);
    Serial.print("getIP AP: ");
    Serial.print(getStatus(wifi.getIP(ESP8266_WIFI_ACCESSPOINT, ip)));
    Serial.print(" : ");
    Serial.println(ip);

    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // connect
    /*Serial.print("connect: ");
    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, IPAddress(192,168,4,100), 4000)));*/

    // send
    /*Serial.print("send: ");
    Serial.println(getStatus(wifi.send("Hello World\n")));*/

    // close
    /*Serial.print("close: ");
    Serial.println(getStatus(wifi.close()));*/

    // setMultipleConnections
    Serial.print("setMultipleConnections: ");
    Serial.println(getStatus(wifi.setMultipleConnections(true)));

    // getMultipleConnections
    /*bool multipleConnections;
    Serial.print("getMultipleConnections: ");
    Serial.print(getStatus(wifi.getMultipleConnections(multipleConnections)));
    Serial.print(" : ");
    Serial.println(multipleConnections);*/

    // createServer
    Serial.print("createServer: ");
    Serial.println(getStatus(wifi.createServer(4000)));

    // deleteServer
    Serial.print("deleteServer: ");
    Serial.println(getStatus(wifi.deleteServer()));

    // setServerTimeout
    /*Serial.print("setServerTimeout: ");
    Serial.println(getStatus(wifi.setServerTimeout(10)));*/

    // getServerTimeout
    /*unsigned int timeout;
    Serial.print("getServerTimeout: ");
    Serial.print(getStatus(wifi.getServerTimeout(timeout)));
    Serial.print(" : ");
    Serial.println(timeout);*/
}

void loop()
{
    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // getConnectedStations
    /*ESP8266Station stations[5];
    unsigned int stationCount;
    Serial.print("getConnectedStations: ");
    Serial.print(getStatus(wifi.getConnectedStations(stations, stationCount, 5)));
    Serial.print(" : ");
    Serial.println(stationCount);
    for (uint8_t i = 0; i < stationCount; i++) {
      Serial.print(" - ");
      Serial.print(stations[i].ip);
      Serial.print(" - ");
      for (uint8_t j = 0; j < 6; j++) {
        Serial.print(stations[i].mac[j], HEX);
        if (j < 5)
          Serial.print(":");
      }
      Serial.println();
    }
    delay(5000);*/

    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // getConnectionStatus
    /*ESP8266ConnectionStatus connectionStatus;
    ESP8266Connection connections[5];
    unsigned int connectionCount;
    Serial.print("getConnectionStatus: ");
    Serial.print(getStatus(wifi.getConnectionStatus(connectionStatus, connections, connectionCount)));
    Serial.print(" : ");
    Serial.println(connectionCount);
    for (int i = 0; i < connectionCount; i++) {
      Serial.print(" - Connection: ");
      Serial.print(connections[i].id);
      Serial.print(" - ");
      Serial.print(getProtocol(connections[i].protocol));
      Serial.print(" - ");
      Serial.print(connections[i].ip);
      Serial.print(":");
      Serial.print(connections[i].port);
      Serial.print(" - ");
      Serial.println(getRole(connections[i].role));
    }
    delay(5000);*/


    // read data
    /*unsigned int id;
    int length;
    int totalRead;
    char buffer[11] = {};

    if ((length = wifi.available()) > 0) {
      id = wifi.getId();
      totalRead = wifi.read(buffer, 10);

      if (length > 0) {
        Serial.print("Received ");
        Serial.print(totalRead);
        Serial.print("/");
        Serial.print(length);
        Serial.print(" bytes from client ");
        Serial.print(id);
        Serial.print(": ");
        Serial.println((char*)buffer);
      }
    }*/
}

String getStatus(bool status)
{
    if (status)
        return "OK";

    return "KO";
}

String getStatus(ESP8266CommandStatus status)
{
    switch (status) {
    case ESP8266_COMMAND_INVALID:
        return "INVALID";
        break;

    case ESP8266_COMMAND_TIMEOUT:
        return "TIMEOUT";
        break;

    case ESP8266_COMMAND_OK:
        return "OK";
        break;

    case ESP8266_COMMAND_NO_CHANGE:
        return "NO CHANGE";
        break;

    case ESP8266_COMMAND_ERROR:
        return "ERROR";
        break;

    case ESP8266_COMMAND_NO_LINK:
        return "NO LINK";
        break;

    case ESP8266_COMMAND_TOO_LONG:
        return "TOO LONG";
        break;

    case ESP8266_COMMAND_FAIL:
        return "FAIL";
        break;

    default:
        return "UNKNOWN COMMAND STATUS";
        break;
    }
}

String getRole(ESP8266Role role)
{
    switch (role) {
    case ESP8266_ROLE_CLIENT:
        return "CLIENT";
        break;

    case ESP8266_ROLE_SERVER:
        return "SERVER";
        break;

    default:
        return "UNKNOWN ROLE";
        break;
    }
}

String getProtocol(ESP8266Protocol protocol)
{
    switch (protocol) {
    case ESP8266_PROTOCOL_TCP:
        return "TCP";
        break;

    case ESP8266_PROTOCOL_UDP:
        return "UDP";
        break;

    default:
        return "UNKNOWN PROTOCOL";
        break;
    }
}

arduino-ESP8266 / HttpRequest.ino

출처 : GitHub - Diaoul/arduino-ESP8266: An Arduino library to manage the ESP8266.
Serial WiFi 모듈 (ESP8266) 활용편 | Hard Copy Arduino

#include <SoftwareSerial.h>

#include "ESP8266.h"

#define SSID "xxxxxxxx"
#define PASS "xxxxxxxx"
#define DST_IP "220.181.111.85" //baidu.com

SoftwareSerial esp8266Serial = SoftwareSerial(6, 7); // RX, TX
ESP8266 wifi = ESP8266(esp8266Serial);

void setup()
{
    Serial.begin(115200);

    // ESP8266
    esp8266Serial.begin(115200);
    wifi.begin();
    wifi.setTimeout(1000);

    /****************************************/
    /******       Basic commands       ******/
    /****************************************/
    // test
    Serial.print("test: ");
    Serial.println(getStatus(wifi.test()));

    // restart
    Serial.print("restart: ");
    Serial.println(getStatus(wifi.restart()));

    // getVersion
    char version[16] = {};
    Serial.print("getVersion: ");
    Serial.print(getStatus(wifi.getVersion(version, 16)));
    Serial.print(" : ");
    Serial.println(version);


    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/
    // joinAP
    Serial.print("joinAP: ");
    Serial.println(getStatus(wifi.joinAP(SSID, PASS)));


    /****************************************/
    /******       TCP/IP commands      ******/
    /****************************************/
    // connect
    Serial.print("connect: ");
    Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, DST_IP, 80)));

    // send
    Serial.print("send: ");
    Serial.println(getStatus(wifi.send("GET / HTTP/1.0\r\n\r\n")));

}

void loop()
{
    /****************************************/
    /******        WiFi commands       ******/
    /****************************************/

    // read data
    unsigned int id;
    int length;
    int totalRead;
    char buffer[300] = {};

    if ((length = wifi.available()) > 0) {
      id = wifi.getId();
      totalRead = wifi.read(buffer, 300);

      if (length > 0) {
        Serial.print("Received ");
        Serial.print(totalRead);
        Serial.print("/");
        Serial.print(length);
        Serial.print(" bytes from client ");
        //Serial.print("from client ");
        Serial.print(id);
        Serial.print(": ");
        Serial.println((char*)buffer);
      }
    }
}

String getStatus(bool status)
{
    if (status)
        return "OK";

    return "KO";
}

Arduino Uno - IR Remote

OS/Arduino 2017.12.30 10:58 Posted by 파란크리스마스

출처 : IR Remote Control Car | How To Make Remote Control Car Using Arduino - MaxPhi
z3t0/Arduino-IRremote: Infrared remote library for Arduino: send and receive infrared signals with multiple protocols

IR Remote 라이브러리

Arduion IDE가 설치된 폴더의 libraries 폴더에서 소스 다운로드

C:\arduino-1.6.5-r5\libraries>git clone https://github.com/z3t0/Arduino-IRremote.git
Cloning into 'Arduino-IRremote'...
remote: Counting objects: 1664, done.
remote: Total 1664 (delta 0), reused 0 (delta 0), pack-reused 1664 eceiving objects: 100% (1664/1664), 972.01 KiB | 419.Receiving objects: 100% (1664/1664), 1.08 MiB | 445.00 KiB/s, done.

Resolving deltas: 100% (916/916), done.

적외선 센서 배선

적외선 센서 소스

/* IRremote: 
IRrecvDemo - demonstrates receiving IR codes with IRrecv 
An IR detector/demodulator must be connected to the input RECV_PIN. 
Version 0.1 July, 2009
Copyright 2009 Ken Shirriff * http://arcfn.com 
*/

#include <IRremote.h>

int RECV_PIN = 12;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);                 
     
    irrecv.resume(); // Receive the next value
  }
}

적외선 센서 연동 RC CAR 배선

적외선 센서 연동 RC CAR 소스

#include <IRremote.h>
#include <Ultrasonic.h>
#include <SoftwareSerial.h>

int IR_RECV_PIN = 12;
int rc_car_mode = 2;

IRrecv irrecv(IR_RECV_PIN);
SoftwareSerial btSerial(9, 8); //Connect HC-06. Use your (TX, RX) settings
Ultrasonic ultrasonic(10,11); // (Trig PIN,Echo PIN)

//모터A 컨트롤
int enA = 6;
int IN1 = 7;
int IN2 = 5;
  
//모터B 컨트롤
int enB = 3;
int IN3 = 4;
int IN4 = 2;

decode_results ir_results;
String receiveStr=""; //받는 문자열
String olfReceiveStr=""; //받는 문자열
#define MOTER_SPEED 255 // MAX 255

void setup()  
{
  irrecv.enableIRIn(); // Start the receiver
  
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  
  Serial.begin(9600);
  Serial.println("Hello!");

  btSerial.begin(9600);  // set the data rate for the BT port
}

void loop()
{
  analogWrite(enA, MOTER_SPEED);
  analogWrite(enB, MOTER_SPEED);
  
  int value = ultrasonic.Ranging(CM);
  Serial.print(value); // CM or INC
  Serial.print(" cm / " );

  boolean is_forward = true;
  if (value <= 15) {
    is_forward = false;
  }

  if (rc_car_mode > 2) {
    rc_car_mode = 1;
  }

  switch (rc_car_mode) {
    case 1:
      loop_bluetooth(is_forward);
      break;
    case 2:  
      loop_irrecv(is_forward);
      break;
  }
  Serial.print("\n");
}

void loop_irrecv(boolean is_forward) {
  receiveStr = "";
  if (irrecv.decode(&ir_results)) {
    Serial.print(ir_results.value, HEX);            
    switch(ir_results.value)
    {
      case 0xFF629D:
        Serial.print(" / ch"); // ch
        receiveStr = "C"; 
        break;
      case 0xFF18E7:  
        Serial.print(" / Forward"); // Button 2  
        receiveStr = "F"; 
        break;
      case 0xFF10EF:
        Serial.print(" / Left"); // Button 4
        receiveStr = "L"; 
        break;
      case 0xFF38C7:
        Serial.print(" / Stop"); // Button 5
        receiveStr = "S"; 
        break;
      case 0xFF5AA5:
        Serial.print(" / Right"); // Button 6
        receiveStr = "R"; 
        break;
      case 0xFF4AB5:  
        Serial.print(" / Back"); // Button 8  
        receiveStr = "B"; 
        break;
    }  
    irrecv.resume(); // Receive the next value
    
    loop_moter_command(is_forward, receiveStr);
  }
}

void loop_bluetooth(boolean is_forward) {
  // put your main code here, to run repeatedly:
  receiveStr="";
  while(btSerial.available())  //mySerial에 전송된 값이 있으면
  {
    char myChar = (char)btSerial.read();  //mySerial int 값을 char 형식으로 변환
    receiveStr+=myChar;   //수신되는 문자를 receiveStr에 모두 붙임 (1바이트씩 전송되는 것을 연결)
    delay(5);           //수신 문자열 끊김 방지
  }
 
  loop_moter_command(is_forward, receiveStr);
}

void loop_moter_command(boolean is_forward, String receiveStr) {
  if (receiveStr.length() > 0) {
    Serial.print(receiveStr);
    if (receiveStr == "C") {
      rc_car_mode++;
    } else if (receiveStr == "F") {
      if (is_forward) {
        bothMotorStart(); // 전진
      } else {
        stopAllMotor();
      }      
    } else if (receiveStr == "S") {
      stopAllMotor();
    } else if (receiveStr == "R") {
      turnRight(); // 오른쪽으로 턴
    } else if (receiveStr == "L") {
      turnLeft(); // 왼쪽으로 턴
    } else if (receiveStr == "B") {
      bothMotorBack(); // 후진
    }
    olfReceiveStr = receiveStr;
  } else if (!is_forward && olfReceiveStr == "F") {
    stopAllMotor();
  }
}

//모터A,B 정회전
void bothMotorStart()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}

//모터A,B 역회전
void bothMotorBack()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A,B Stop
void stopAllMotor()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B 정회전
void turnLeft()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 정회전, 모터B 역회전
void turnRight()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}

Arduino Uno - HC-SR04 / RC CAR 충돌 방지

OS/Arduino 2017.12.29 23:25 Posted by 파란크리스마스

출처 : 블루투스 HC-06 슬레이브 모듈 아두이노 소스 + 안드로이드 앱 소스 | Hard Copy Arduino

HC-SR04 센서 배선

HC-SR04 센서 소스

#include <Ultrasonic.h>
 
Ultrasonic ultrasonic(10,11); // (Trig PIN,Echo PIN)
 
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}
 
void loop() {
  // put your main code here, to run repeatedly:
  Serial.print(ultrasonic.Ranging(CM)); // CM or INC
  Serial.println(" cm" );
  delay(100);
}

HC-SR04 센서 연동 RC CAR 배선

HC-SR04 센서 연동 RC CAR 소스

#include <Ultrasonic.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(9, 8); //Connect HC-06. Use your (TX, RX) settings
Ultrasonic ultrasonic(10,11); // (Trig PIN,Echo PIN)

//모터A 컨트롤
int enA = 6;
int IN1 = 7;
int IN2 = 5;
  
//모터B 컨트롤
int enB = 3;
int IN3 = 4;
int IN4 = 2;

String receiveStr=""; //받는 문자열
String olfReceiveStr=""; //받는 문자열
#define MOTER_SPEED 255 // MAX 255

void setup()  
{
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  
  Serial.begin(9600);
  Serial.println("Hello!");

  btSerial.begin(9600);  // set the data rate for the BT port
}

void loop()
{
  analogWrite(enA, MOTER_SPEED);
  analogWrite(enB, MOTER_SPEED);
  
  int value = ultrasonic.Ranging(CM);
  Serial.print(value); // CM or INC
  Serial.print(" cm / " );

  if (value <= 15) {
    //stopAllMotor();
    loop_bluetooth(false);
  } else {
    loop_bluetooth(true);
    //loop_line_tracer();
  }

  Serial.print("\n");
}

void loop_bluetooth(boolean is_forward) {
  // put your main code here, to run repeatedly:
  receiveStr="";
  while(btSerial.available())  //mySerial에 전송된 값이 있으면
  {
    char myChar = (char)btSerial.read();  //mySerial int 값을 char 형식으로 변환
    receiveStr+=myChar;   //수신되는 문자를 receiveStr에 모두 붙임 (1바이트씩 전송되는 것을 연결)
    delay(5);           //수신 문자열 끊김 방지
  }
 
  if (receiveStr.length() > 0) {
    Serial.print(receiveStr);
    if (receiveStr == "F") {
      if (is_forward) {
        bothMotorStart(); // 전진
      } else {
        stopAllMotor();
      }      
    } else if (receiveStr == "S") {
      stopAllMotor();
    } else if (receiveStr == "R") {
      turnRight(); // 오른쪽으로 턴
    } else if (receiveStr == "L") {
      turnLeft(); // 왼쪽으로 턴
    } else if (receiveStr == "B") {
      bothMotorBack(); // 후진
    }
    olfReceiveStr = receiveStr;
  } else if (!is_forward && olfReceiveStr == "F") {
    stopAllMotor();
  }
}

//모터A,B 정회전
void bothMotorStart()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}

//모터A,B 역회전
void bothMotorBack()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A,B Stop
void stopAllMotor()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B 정회전
void turnLeft()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 정회전, 모터B 역회전
void turnRight()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}

Arduino Uno - HC-06 / 블루투스 연동 RC CAR

OS/Arduino 2017.12.29 21:25 Posted by 파란크리스마스

출처 : 블루투스 HC-06 슬레이브 모듈 아두이노 소스 + 안드로이드 앱 소스 | Hard Copy Arduino

HC-06 배선

HC-06 제어 소스

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(9, 8); //Connect HC-06. Use your (TX, RX) settings

void setup()  
{
  Serial.begin(9600);
  Serial.println("Hello!");

  BTSerial.begin(9600);  // set the data rate for the BT port
}

void loop()
{
  // BT –> Data –> Serial
  if (BTSerial.available()) {
    Serial.write(BTSerial.read());
  }
  // Serial –> Data –> BT
  if (Serial.available()) {
    BTSerial.write(Serial.read());
  }
}

블루투스(HC-06) 연동 RC CAR 배선

블루투스(HC-06) 연동 RC CAR 소스

#include <SoftwareSerial.h>

SoftwareSerial btSerial(9, 8); //Connect HC-06. Use your (TX, RX) settings

//모터A 컨트롤
int enA = 6;
int IN1 = 7;
int IN2 = 5;
  
//모터B 컨트롤
int enB = 3;
int IN3 = 4;
int IN4 = 2;

String receiveStr=""; //받는 문자열
#define MOTER_SPEED 255 // MAX 255

void setup()  
{
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  
  Serial.begin(9600);
  Serial.println("Hello!");

  btSerial.begin(9600);  // set the data rate for the BT port
}

void loop()
{
  analogWrite(enA, MOTER_SPEED);
  analogWrite(enB, MOTER_SPEED);
  
  // put your main code here, to run repeatedly:
  receiveStr="";
  while(btSerial.available())  //mySerial에 전송된 값이 있으면
  {
    char myChar = (char)btSerial.read();  //mySerial int 값을 char 형식으로 변환
    receiveStr+=myChar;   //수신되는 문자를 receiveStr에 모두 붙임 (1바이트씩 전송되는 것을 연결)
    delay(5);           //수신 문자열 끊김 방지
  }
 
  if (receiveStr.length() > 0) {
    Serial.println(receiveStr);
    if (receiveStr == "F") {
      bothMotorStart(); // 전진
    } else if (receiveStr == "S") {
      stopAllMotor();
    } else if (receiveStr == "R") {
      turnRight(); // 오른쪽으로 턴
    } else if (receiveStr == "L") {
      turnLeft(); // 왼쪽으로 턴
    } else if (receiveStr == "B") {
      bothMotorBack(); // 후진
    }
  }
}


//모터A,B 정회전
void bothMotorStart()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}

//모터A,B 역회전
void bothMotorBack()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A,B Stop
void stopAllMotor()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B 정회전
void turnLeft()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 정회전, 모터B 역회전
void turnRight()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}

Arduino Uno - L298N

OS/Arduino 2017.12.24 02:44 Posted by 파란크리스마스

출처 : Tutorial - L298N Dual Motor Controller Module 2A and Arduino - Tronixlabs Australia

배선

L298N 스펙

  1. DC motor 1 "+" or stepper motor A+
  2. DC motor 1 "-" or stepper motor A-
  3. 12V jumper - remove this if using a supply voltage greater than 12V DC. This enables power to the onboard 5V regulator
  4. Connect your motor supply voltage here, maximum of 35V DC. Remove 12V jumper if >12V DC
  5. GND
  6. 5V output if 12V jumper in place, ideal for powering your Arduino (etc)
  7. DC motor 1 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  8. IN1
  9. IN2
  10. IN3
  11. IN4
  12. DC motor 2 enable jumper. Leave this in place when using a stepper motor. Connect to PWM output for DC motor speed control.
  13. DC motor 2 "+" or stepper motor B+
  14. DC motor 2 "-" or stepper motor B-

L298N 제어 소스

//모터A 컨트롤
int enA = 6;
int IN1 = 7;
int IN2 = 5;
  
//모터B 컨트롤
int enB = 3;
int IN3 = 4;
int IN4 = 2;
 
#define MOTER_SPEED 255 // MAX 255
  
void setup() {
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
}
  
void loop() {
  analogWrite(enA, MOTER_SPEED);
  analogWrite(enB, MOTER_SPEED);

  /*
  digitalWrite(enA,HIGH);
  digitalWrite(enB,HIGH);
  */
  bothMotorStart(); // 전진
  delay(3000);
  turnLeft(); // 왼쪽으로 턴
  delay(3000);
  turnRight(); // 오른쪽으로 턴
  delay(3000);
  motorA_Rotation(); // 왼쪽만 정방향
  delay(3000);
  motorB_Rotation(); // 오른쪽만 정방향
  delay(3000);
  motorA_Reverse(); // 왼쪽만 역방향
  delay(3000);
  motorB_Reverse(); // 오른쪽만 역방향
  delay(3000);
  stopAllMotor(); // 정지
  delay(3000);
}
  
//모터A,B 정회전
void bothMotorStart()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A,B Stop
void stopAllMotor()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B 정회전
void turnLeft()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 정회전, 모터B 역회전
void turnRight()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
  
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
  
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
  
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}

WeMos - D1

OS/Arduino 2017.12.10 00:43 Posted by 파란크리스마스

출처 : 아두이노 WeMos 환경 셋팅 및 기본예제 | 프로젝트 | 메이크위드
CodeBlog: ESP8266, WeMos D1 R1, D1 R2 and D1 Mini pins

아두이노 IDE에 보드 추가하기

COM 포트가 추가된 것을 확인

메뉴 [파일] -> [환경설정] 선택

[환경설정]창에서 Additional Board Manager URLs 항목 설정

보드관련 정보가 있는 URL를 http://arduino.esp8266.com/stable/package_esp8266com_index.json 붙여넣기

메뉴 [도구] -> [보드] -> [Boards Manager...] 선택

[Boards Manager] 창에서 esp8266 검색하고, [Install] 버튼 석택

메뉴 [도구]에서 보드와 포트 선택

LED 켜기

// LED가 연결된 PIN번호
int led = D15;

// 초기화
void setup() { 
  pinMode(led, OUTPUT); 
}

// 무한 반복
void loop() {
  digitalWrite(led, HIGH); // LED 켜기
  delay(1000); // 1초 대기
  digitalWrite(led, LOW); // LED 끄기
  delay(1000); // 1초 대기
}

PWM 예제

아두이노에서는 analogWrite 함수를 통해서 이러한 PWM 출력을 제공하는데, analogWrite 함수의 인자 범위는 아두이노 우노 R3의 경우 0~255까지의 정수를 사용하지만, D1의 경우 0~1023까지의 정수를 사용한다.

// LED가 연결된 PIN번호
int ledPin = D6;
 
// 초기화
void setup() {
  // 출력 모드 설정
  pinMode(ledPin, OUTPUT);   // sets the pin as output
}
 
// 무한 반복
void loop() {
  // 25 단위로 반복 / PWM 번위 0~1023
  for(int angle = 0; angle < 1023; angle=angle+5) {
    // PWM 출력
    analogWrite(ledPin, angle);
    delay(15);
  }
}

SG90 서브모터 제어

[Arduino|아두이노] 서보모터(SG90) 구동하는 방법 (Tower Pro, Micro Servo, B10K, 가변저항) - 젠트의 프로그래밍 세상

#include <Servo.h> 

Servo servo;
 
int servoPin = D3;
int angle = 0; // servo position in degrees 

// 초기화
void setup() { 
  servo.attach(servoPin);
} 

// 무한 반복
void loop() { 
  // rotate from 0 to 180degrees
  for(angle = 0; angle < 180; angle++) { 
    servo.write(angle); 
    delay(15); 
  } 
}

RC Car - L298N Dual H-Bridge

Reference · ESP8266 Arduino Core

//모터A 컨트롤
int enA = D3;
int IN1=D4;
int IN2=D5;
 
//모터B 컨트롤
int enB = D10;
int IN3=D8;
int IN4=D9;

#define MOTER_SPEED 1023 // MAX 1023
 
void setup() {
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
}
 
void loop() {
  
  analogWrite(enA, MOTER_SPEED);
  analogWrite(enB, MOTER_SPEED);
  
  /*
  digitalWrite(enA,HIGH);
  digitalWrite(enB,HIGH);
  */
  bothMotorStart(); // 전진
  delay(3000);
  turnLeft(); // 왼쪽으로 턴
  delay(3000);
  turnRight(); // 오른쪽으로 턴
  delay(3000);
  motorA_Rotation(); // 오른쪽만 정방향
  delay(3000);
  motorB_Rotation(); // 왼쪽만 정방향
  delay(3000);
  motorA_Reverse(); // 오른쪽만 역방향
  delay(3000);
  motorB_Reverse(); // 왼쪽만 역방향
  delay(3000);
  stopAllMotor(); // 정지
  delay(3000);
}
 
//모터A,B 정회전
void bothMotorStart()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
 
//모터A,B Stop
void stopAllMotor()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
 
//모터A 역회전, 모터B 정회전
void turnLeft()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
 
//모터A 정회전, 모터B 역회전
void turnRight()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}
 
//모터A 정회전, 모터B Stop
void motorA_Rotation()
{
    digitalWrite(IN1,HIGH);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
 
//모터A Stop, 모터B 정회전
void motorB_Rotation()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,HIGH);
    digitalWrite(IN4,LOW);
}
 
//모터A 역회전, 모터B Stop
void motorA_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,HIGH);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,LOW);
}
 
//모터A Stop, 모터B 역회전
void motorB_Reverse()
{
    digitalWrite(IN1,LOW);
    digitalWrite(IN2,LOW);
    digitalWrite(IN3,LOW);
    digitalWrite(IN4,HIGH);
}


rc_car (Keyes L298P - 모터드라이버 쉴드)

OS/Arduino 2017.10.04 03:49 Posted by 파란크리스마스

출처 : 모터드라이버 쉴드 L298P를 이용하는 방법[아두이노 강좌] : 네이버 블로그

#include <SoftwareSerial.h> //시리얼 통신 라이브러리 호출

// Bluetooth 관련  
int blueRx=2;   //Rx (받는핀 설정)
int blueTx=3;   //Tx (보내는핀 설정)
SoftwareSerial btSerial(blueTx, blueRx);  //시리얼 통신을 위한 객체선언
String myString=""; //받는 문자열

int E1 = 10;      // 1번(A) 모터 Enable
int E2 = 11;      // 2번(B) 모터 Enable
int M1 = 12;      // 1번(A) 모터 PWM  
int M2 = 13;      // 2번(B) 모터 PWM

#define MOTER_SPEED 255
int value;
 
void setup() {
  pinMode(M1, OUTPUT);      // 출력핀 설정
  pinMode(M2, OUTPUT);
  Serial.begin(9600);
  btSerial.begin(9600); //블루투스 시리얼 개방
}
 
void loop() 
{
  // put your main code here, to run repeatedly:
  myString="";
  while(btSerial.available())  //mySerial에 전송된 값이 있으면
  {
    char myChar = (char)btSerial.read();  //mySerial int 값을 char 형식으로 변환
    myString+=myChar;   //수신되는 문자를 myString에 모두 붙임 (1바이트씩 전송되는 것을 연결)
    delay(5);           //수신 문자열 끊김 방지
  }

  if (myString.length() > 0) {
    Serial.println(myString);
    if (myString == "F") {
      motor_forward();
    } else if (myString == "S") {
      motor_stop();
    } else if (myString == "R") {
      motor_right();
    } else if (myString == "L") {
      motor_left();
    } else if (myString == "B") {
      motor_backwards();
    }
  }
}

void motor_stop() {
  digitalWrite(M1, HIGH);
  digitalWrite(M2, HIGH);
  analogWrite(E1, 0);
  analogWrite(E2, 0);
}

void motor_backwards() {
  motor_backwards(MOTER_SPEED);
}

void motor_backwards(int speed) {
  digitalWrite(M1, HIGH);
  digitalWrite(M2, HIGH);
  analogWrite(E1, speed);
  analogWrite(E2, speed);
}

void motor_forward() {
  motor_forward(MOTER_SPEED);
}

void motor_forward(int speed) {
  digitalWrite(M1, LOW);
  digitalWrite(M2, LOW);
  analogWrite(E1, speed);
  analogWrite(E2, speed);
}

void motor_right() {
  motor_right(MOTER_SPEED);
}

void motor_right(int speed) {
  digitalWrite(M1, HIGH);
  digitalWrite(M2, LOW);
  analogWrite(E1, speed);
  analogWrite(E2, speed);
}

void motor_left() {
  motor_left(MOTER_SPEED);
}

void motor_left(int speed) {
  digitalWrite(M1, LOW);
  digitalWrite(M2, HIGH);
  analogWrite(E1, speed);
  analogWrite(E2, speed);
}

MeArm - 원격 제어 1

OS/Arduino 2017.10.03 02:53 Posted by 파란크리스마스

MeArm - 원격 제어 1

출처 : 실습4. 아두이노 (Arduino)로 가변저항의 저항 값 읽기 : 네이버 블로그 | 메이키스트

MeArm을 원격 제어 하기 위해서 만들기 시작했는데, 아직 하나의 아두이노에서 제어만 가능한 상태입니다.

Raspberry PI를 이용해서 제어 명령을 녹화 했다가 다시 재생하고, 블루투스로 원역으로 제어 하는 부분을 구현 예정인데, 완료되면 다시 글 올리도록 하겠습니다.

최초 아두이노 소스

#include<Servo.h> 

Servo myservo1; 
Servo myservo2;
Servo myservo3; 
int servoPin1 = 10; 
int servoPin2 = 3; 
int servoPin3 = 5; 
int pos = 0; 

int analogPin1 = A1;     // potentiometer wiper (middle terminal) connected to analog pin 3
int analogPin2 = A2;
int analogPin3 = A3; // outside leads to ground and +5V
int val1 = 0;           // variable to store the value read
int val1_offset_p = 10;
int val1_p_max = 180;
int val1_offset_s = 0;
int val1_ratio = 5.6266;
long temp1_old = 0;
int val2 = 0;           // variable to store the value read
int val2_offset_p = 90;
int val2_p_max = 170;
int val2_offset_s = 60;
int val2_ratio = 6.3636;
long temp2_old = 0;
int val3 = 0;           // variable to store the value read
int val3_offset_p = 100;
int val3_p_max = 180;
int val3_offset_s = 30;
int val3_ratio = 6;
long temp3_old = 0;

void setup()
{
  Serial.begin(9600);          //  setup serial
  myservo1.attach(servoPin1); 
  myservo2.attach(servoPin2); 
  myservo3.attach(servoPin3); 
}

void loop()
{
  val1 = analogRead(analogPin1);    // read the input pin
  val2 = analogRead(analogPin2);    // read the input pin
  val3 = analogRead(analogPin3);    // read the input pin
  Serial.print(val1);             // debug value
  Serial.print(", ");             // debug value
  Serial.print(val2);             // debug value
  Serial.print(", ");             // debug value
  Serial.print(val3);             // debug value
  

  // 오른쪽 0 / 왼쪽 180
  // 오른쪽 1023 / 왼쪽 10
  // 1023-10 / 180 = 5.6266
  long temp1 = val1_p_max + val1_offset_s - ((val1 - val1_offset_p) / val1_ratio);
  if (temp1 < val1_offset_s) {
    temp1 = val1_offset_s;
  }
  if (temp1 > val1_p_max) {
    temp1 = val1_p_max;
  }
  Serial.print(", ");             // debug value
  Serial.print(temp1_old);             // debug value

  // 뒤 170 / 앞 : 60
  // 뒤 90 / 왼쪽 790
  // 790-90 / 170-60 = 6.3636  
  long temp2 = val2_p_max - ((val2 - val2_offset_p) / val2_ratio);
  if (temp2 < val2_offset_s) {
    temp2 = val2_offset_s;
  }
  if (temp2 > val2_p_max) {
    temp2 = val2_p_max;
  }

  
  Serial.print(", ");             // debug value
  Serial.print(temp2_old);             // debug value

  
  
  // 뒤 30 / 앞 : 180
  // 뒤 1000 / 앞 100
  // 1000-100 / 180-30 = 6 
  long temp3 = val3_p_max - ((val3 - val3_offset_p) / val3_ratio);
  if (temp3 < val3_offset_s) {
    temp3 = val3_offset_s;
  }
  if (temp3 > val3_p_max) {
    temp3 = val3_p_max;
  }

  Serial.print(", ");             // debug value
  Serial.print(temp3_old);             // debug value

  if (temp1_old - 25 < temp1  &&  temp1_old + 25 ) {
    myservo1.write(temp1); 
    temp1_old = temp1;  
  }

  if (temp2_old - 25 < temp2  &&  temp2_old + 25 ) {
    myservo2.write(temp2); 
    temp2_old = temp2;  
  }

  if (temp3_old - 25 < temp3  &&  temp3_old + 25 ) {
    myservo3.write(temp3); 
    temp3_old = temp3;  
  }
  
  Serial.print("\n");             // debug value
  delay(25);
}

개선된 소스 - 첫 번째

#include<Servo.h> 

Servo myservo[3];  
int servoPin[] = { 10, 3, 5 }; 

#define ARRAY_LENGTH 3
#define val1_offset_s 0
#define val1_p_max 1
#define val1_offset_p 2
#define val1_ratio 3

int analogPin[] = { A1, A2, A3 }; // outside leads to ground and +5V
double val1_offset[3][4] = {
  { 10, 180, 0, 5.6266 }, 
  { 90, 170, 60, 6.3636},
  { 100, 180, 30, 6} 
};
int val[3];           // variable to store the value read
double temp[] = { 0, 0, 0 };
double temp_old[] = { 0, 0, 0 };
int chcek_int = 3;

void setup() {
  Serial.begin(9600);          //  setup serial
  for (int i=0; i<ARRAY_LENGTH; i++) {
    myservo[i].attach(servoPin[i]);
  }
  //myservo[0].attach(servoPin[0]);
}

void loop() {
  for (int i=0; i<ARRAY_LENGTH; i++) {
    val[i] = analogRead(analogPin[i]);    // read the input pin
    Serial.print(i);
    Serial.print("=");
    Serial.print(val[i]);             // debug value
    Serial.print(",");             // debug value
  }
  Serial.print("|");             // debug value

  // 오른쪽 0 / 왼쪽 180
  // 오른쪽 1023 / 왼쪽 10
  // 1023-10 / 180 = 5.6266
  temp[0] = val1_offset[0][val1_p_max] + val1_offset[0][val1_offset_s] - ((val[0] - val1_offset[0][val1_offset_p]) / val1_offset[0][val1_ratio]);
  
  // 뒤 170 / 앞 : 60
  // 뒤 90 / 왼쪽 790
  // 790-90 / 170-60 = 6.3636 
  temp[1] = val1_offset[1][val1_p_max] - ((val[1] - val1_offset[1][val1_offset_p]) / val1_offset[1][val1_ratio]);
   
  // 뒤 30 / 앞 : 180
  // 뒤 1000 / 앞 100
  // 1000-100 / 180-30 = 6
  temp[2] = val1_offset[2][val1_p_max] - ((val[2] - val1_offset[2][val1_offset_p]) / val1_offset[2][val1_ratio]);

  for (int i=0; i<ARRAY_LENGTH; i++) {
    if (temp[i] < val1_offset[i][val1_offset_s]) {
      temp[i] = val1_offset[i][val1_offset_s];
    }
    if (temp[i] > val1_offset[i][val1_p_max]) {
      temp[i] = val1_offset[i][val1_p_max];
    }
    
    Serial.print(temp_old[i]);             // debug value
    Serial.print("/ ");             // debug value
  }
  
  for (int i=0; i<ARRAY_LENGTH; i++) {
    if (temp_old[i] - chcek_int > temp[i] || temp[i] > temp_old[i] + chcek_int ) {
      myservo[i].write(temp[i]); 
      temp_old[i] = temp[i];  
      Serial.print(", ");             // debug value
      Serial.print("servo");
      Serial.print(i);
      Serial.print(" set");             // debug value
    }
  }
  
  Serial.print("\n");             // debug value
  delay(25);
}

개선된 소스 - 두 번째

#include<Servo.h> 

Servo myservo[3];  
int servoPin[] = { 10, 3, 5 }; 

#define ARRAY_LENGTH 3
#define resi_s 0
#define resi_e 1
#define servo_s 2
#define servo_e 3
#define arm_ratio 4

int analogPin[] = { A1, A2, A3 }; // outside leads to ground and +5V
double cvalue[3][5] = {
  {  50, 1023,   0, 180, 5.6266 }, 
  {  90,  790,  60, 170, 6.3636 },
  { 100, 1000,  30, 180, 6 } 
};
int val[3];           // variable to store the value read
double temp[] = { 0, 0, 0 };
double temp_old[] = { 0, 0, 0 };
int chcek_int = 3;

void setup() {
  Serial.begin(9600);          //  setup serial
  for (int i=0; i<ARRAY_LENGTH; i++) {
    myservo[i].attach(servoPin[i]);

    // 790-90 / 170-60 = 6.3636 
    cvalue[i][arm_ratio] = (cvalue[i][resi_e] - cvalue[i][resi_s])
      / (cvalue[i][servo_e] - cvalue[i][servo_s]); 
  }
}

void loop() {
  for (int i=0; i<ARRAY_LENGTH; i++) {
    val[i] = analogRead(analogPin[i]);    // read the input pin
    Serial.print(i);
    Serial.print("=");
    Serial.print(val[i]);             // debug value
    Serial.print(",");             // debug value
  }
  Serial.print("|");             // debug value

  // 오른쪽 0 / 왼쪽 180
  // 오른쪽 1023 / 왼쪽 10
  // 1023-10 / 180 = 5.6266
  temp[0] = cvalue[0][servo_e] + cvalue[0][servo_s] - ((val[0] - cvalue[0][resi_s]) / cvalue[0][arm_ratio]);
  
  // 뒤 170 / 앞 : 60
  // 뒤 90 / 왼쪽 790
  // 790-90 / 170-60 = 6.3636 
  temp[1] = cvalue[1][servo_e] - ((val[1] - cvalue[1][resi_s]) / cvalue[1][arm_ratio]);
   
  // 뒤 30 / 앞 : 180
  // 뒤 1000 / 앞 100
  // 1000-100 / 180-30 = 6
  temp[2] = cvalue[2][servo_e] - ((val[2] - cvalue[2][servo_s]) / cvalue[2][arm_ratio]);

  for (int i=0; i<ARRAY_LENGTH; i++) {
    if (temp[i] < cvalue[i][servo_s]) {
      temp[i] = cvalue[i][servo_s];
    }
    if (temp[i] > cvalue[i][servo_e]) {
      temp[i] = cvalue[i][servo_e];
    }
    
    Serial.print(temp_old[i]);             // debug value
    Serial.print("/ ");             // debug value
  }
  
  for (int i=0; i<ARRAY_LENGTH; i++) {
    if (temp_old[i] - chcek_int > temp[i] || temp[i] > temp_old[i] + chcek_int ) {
      myservo[i].write(temp[i]); 
      temp_old[i] = temp[i];  
    }
  }
  
  Serial.print("\n");             // debug value
  delay(25);
}

실행

Arduino - 버저, 피에조 스피커(Piezo Buzzer)

OS/Arduino 2017.09.16 18:30 Posted by 파란크리스마스

출처 : All I want to do is BEEP! to show that the program - Arduino Forum
버저, 피에조 스피커로 음악 연주 (슈퍼마리오 배경음악) | Hard Copy Arduino

Arduino - 버저, 피에조 스피커(Piezo Buzzer)

Spec.

전압 : 5V
직경 : 12mm
핀길이 : 6.5mm
높이 : 8.5mm

배선

BEEP음 출력 소스

#define SPKR 2 //this is the digital pin that you plugged the red       wire into

void setup()
{
   pinMode(SPKR, OUTPUT); //set the speaker as output
}

void loop() //do this over and over
{
   digitalWrite(SPKR, HIGH); //turn the speaker on
   delay(500);                     //wait for half a second
   digitalWrite(SPKR, LOW); //turn the speaker off
   delay(500);                    //wait for half a second
}

피에조 스피커로 음악 연주 (슈퍼마리오 배경음악)

출처 : 버저, 피에조 스피커로 음악 연주 (슈퍼마리오 배경음악) | Hard Copy Arduino

pitches.h(링크) 파일은 아두이노 사이트에서 받을 수 있습니다.

#include "pitches.h"
 
#define melodyPin 2
 
unsigned long prevPlayTime = 0;
unsigned long playDuration = 0;
int currentMelody = 0;
 
//Mario main theme melody
int melodySize = 55;
int melody[] = {
  NOTE_E7, NOTE_E7, 0, NOTE_E7, 0, NOTE_C7, NOTE_E7, 0, NOTE_G7, 0, 0,  0, NOTE_G6, 0, 0, 0, 
  NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, 
  NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0,NOTE_C7, NOTE_D7, NOTE_B6, 0, 0,
  NOTE_C7, 0, 0, NOTE_G6, 0, 0, NOTE_E6, 0, 0, NOTE_A6, 0, NOTE_B6, 0, NOTE_AS6, NOTE_A6, 0, 
  NOTE_G6, NOTE_E7, NOTE_G7, NOTE_A7, 0, NOTE_F7, NOTE_G7, 0, NOTE_E7, 0,NOTE_C7, NOTE_D7, NOTE_B6, 0, 0
};

//Mario main them tempo
int tempo[] = {
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 
  9, 9, 9, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  9, 9, 9, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
};

void sing() {
    if(millis() < prevPlayTime + playDuration) {
        // music is playing. do nothing
        return;
    }
    // stop the tone playing:
    noTone(8);
    
    if(currentMelody >= melodySize)
        currentMelody = 0;
    // to calculate the note duration, take one second
    // divided by the note type.
    //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
    int noteDuration = 1000/tempo[currentMelody];
 
    tone(melodyPin, melody[currentMelody], noteDuration);
    prevPlayTime = millis();
    playDuration = noteDuration * 1.30;
    
    currentMelody++;
}

void setup() {
  pinMode(melodyPin, OUTPUT);
}

void loop() {
  // play music
  sing();
}


Arduino - 서브모터(SG-90)

OS/Arduino 2017.09.16 03:35 Posted by 파란크리스마스

출처 : 5 pcs Flame Sensor Module Fire Detection Module Infrared Receiver Module For DIY Electronic Car Wavelength 760nm-1100nm - Aliexpress.com

Arduino - 서브모터(SG-90)

설명

크기 : 21.5mm X 11.8mm X 22.7mm
무게 : 9g
속도 : 0.12 초 / 60도 (4.8V)
1.2 스톨 토크 - 1.4 kg / cm (4.8V)
작동 온도 : -30도에서 +60도
작동 전압 : 4.8V-6V

인터페이스 설명 (선)

다크 그레이 : GND
레드 : VCC의 4.8-7.2V
오렌지 라인 : 펄스 입력

배선

서브모터(SG-90) 제어 소스

#include <Servo.h>

Servo servo;

int servoPin = 9;
int angle = 0; // servo position in degrees 

void setup()  { 
  servo.attach(servoPin);
} 

void loop() { 
  for(angle = 0; angle < 180; angle++)  { 
    servo.write(angle); 
    delay(15); 
  } 
}

서브모터(SG-90) 제어 실행


Arduino - 불꽃 감지 센서 (SZH-EK086, 파장 760nm-1100nm)

OS/Arduino 2017.09.16 01:31 Posted by 파란크리스마스

출처 : 5 pcs Flame Sensor Module Fire Detection Module Infrared Receiver Module For DIY Electronic Car Wavelength 760nm-1100nm - Aliexpress.com

Arduino - 불꽃 감지 센서

소개

이 민감한 불꽃, 동안 또한 감지 일반적인. 보통 사용 화재 경보. , 디지털 출력 인터페이스 직접 연결된 마이크로 IO. 멀리서 유지 불꽃, 높은 온도 손상 센서 모듈. 

설명

1. 검출 불꽃 또는 광원 의 파장 범위 760nm ~ 1100nm
2. 감지 각도 약 60도, 불꽃 스펙트럼 측정
3. 정확도 조정
4. 작동 전압 3.3V 또는 5V 
5. 출력 - 아날로그 전압 출력, 디지털 스위치 출력 (0 1)
6. PCB 크기: 3cm * 1.6cm
7. Chip LM393

인터페이스 설명 (선)

1. VCC -- 3.3 볼트 5 볼트 전압
2. GND -- GND
3. DO -- 보드 디지털 출력 인터페이스 (0 1)
4. AO -- 보드 아날로그 출력 인터페이스

배선

불꽃 감지 센서 측정 소스

int ledPin = 2;
int inputPin = A0;
int val = 0;    //센서출력값 저장 변수

void setup() {
  pinMode(ledPin, OUTPUT);   //LED 출력설정
  pinMode(inputPin, INPUT);    //불꽃센서 입력설정
  Serial.begin(9600);     //시리얼모니터 설정
}

void loop() {
  val = analogRead(inputPin);  //불꽃센서에서 값을 읽어옴
  Serial.println(val);     //불꽃센서 입력값 시리얼모니터로 출력
  if(val < 150)           //불꽃센서 입력값이 150이하이면 LED실행, 환경에 따라 적절한 값으로 조절필요
  {
    digitalWrite(ledPin,HIGH);  // LED 켜기
  }else{
    digitalWrite(ledPin,LOW);   // LED 끄기
  }
  delay(500);
}

Arduino - 온습도센서(DHT-11)

OS/Arduino 2017.09.13 00:49 Posted by 파란크리스마스

출처 : 1PCS DHT11 DHT 11 Digital Temperature and Humidity Temperature sensor with Cable for Arduino-in Integrated Circuits from Electronic Components & Supplies on Aliexpress.com

Arduino - 온습도센서(DHT-11)

사양

습도 측정 범위 : 20 % ~ 90 % RH
습도 측정 오차 : 5 % RH ±
측정 온도 범위 : 0 ~ 60 ° C
온도 측정 오차 : ± 2 ° C
작동 전압 : DC 5V
크기 : 약. 30x13x8mm (L *의 W의 * H)

온습도센서 라이브러리 추가

온습도센서 라이브러리 다운로드

라이브러리 다운로드

다운로드 받은 라이브러리 추가

소스에 라이브러리 추가

편집창에 추가된 라이브러리 확인

배선

온습도센서(DHT-11) 측정 소스

#include <dht11.h>

int DHT11PIN = A0;            //Signal 이 연결된 아두이노의 핀번호

dht11 DHT11;
 
void setup()
{
  Serial.begin(9600);  //시리얼 통신속도 설정
}
 
void loop()
{
  int chk = DHT11.read(DHT11PIN);
 
  Serial.print("Temp: ");
  Serial.print((float)DHT11.temperature);
  Serial.print(" C ");
  
  Serial.print("/ RelF: ");
  Serial.print((float)DHT11.humidity);
  Serial.print(" %");

  Serial.println();
  
  delay(2000);
}

실행결과 (시리얼 모니터)



 

티스토리 툴바