728x90

출처

소스

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DHT.h>

const char *ssid = "iptime";
const char *password = "password";
IPAddress ip(192, 168, 0, 122); // 임시 IP 주소 설정
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);
#define DHTPIN 4          // DHT 센서의 핀 번호
#define DHTTYPE DHT11     // DHT11 센서 사용

DHT dht(DHTPIN, DHTTYPE);

ESP8266WebServer server(80);

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

  dht.begin();
  WiFi.config(ip, gateway, subnet); // 임시 IP 설정
 
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP()); // WiFi의 로컬 IP 주소 출력
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("Connected to WiFi");
 
  server.on("/", handleRoot);
  server.begin();
}

void loop() {
  server.handleClient();
}

void handleRoot() {
  float temperature = dht.readTemperature(); // 온도 값을 읽음

  String html = "<html><body>";
  html += "<h1>web server</h1>";
  html += "<p>now temp: " + String(temperature) + "C</p>";
  html += "</body></html>";

  server.send(200, "text/html", html); // 클라이언트에 응답 전송
}
728x90
728x90

출처

Arduino IDE 설치

다운로드 주소 : https://www.arduino.cc/en/Main/Software

Arduino IDE에 M5Stack 보드 추가

arduino-esp32 다운로드

Github 저장소(espressif / arduino-esp32)에서 arduino-esp32-1.0.1.zip 파일 다운로드

arduino-esp32 설치

다운로드 받은 파일 arduino-esp32-1.0.1.zip을 [Arduino IDE 설치경로]/hardware/espressif/esp32에 압축 해제

get.exe 실행 파일을 관리자 권한으로 실행

[Arduino IDE 설치경로]/hardware/espressif/esp32/tools 디렉토리에서 get.exe 실행 파일을 관리자 권한으로 실행 실행

Arduino IDE를 실행하고, 메뉴[툴] > [보드] > [M5Stack-Core-ESP32] 선택

메뉴[툴] > [포트] > [COM13] 포트선택

M5Stack 라이브러리 설치

메뉴[툴] > [라이브러리 관리] 선택

M5Stack 라이브러리 설치

[HelloWorld] 예제 선택

예제 실행

예제 실행 결과




https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_dev_index.json
https://github.com/Xinyuan-LilyGO/TTGO_TWatch_Library


728x90
728x90

출처

파일 다운로드

HUSKYLENS 펌웨어 업그레이드에 필요한 파일을 다운로드합니다. https://github.com/HuskyLens/HUSKYLENSUploader/ 사이트에서 방문해서 "Download ZIP"을 클릭합니다.

CP2101 용 드라이버 설치

USKYLENS는 USB로 시리얼 통신용 CP2101 (USB to UART Bridge) 칩을 사용하고 있어 CP2101 용 드라이버를 설치해야 합니다. ZIP파일 압축을 풀고 해당 윈도우 버전의 driver 폴더에서 설치 프로그램을 실행합니다. Windows10 용 64 비트 설치 (CP210xVCPInstaller_x64.exe)입니다.

업그레이드 실시

HUSKYLENS를 USB 케이블로 PC와 연결하고 펌웨어 업데이트용 소프트웨어 (K-Flash.exe)를 실행합니다

Device 선택

K-Flash.exe를 실행하면 HUSKYLENS에 탑재 된 CP2101과 자동으로 연결됩니다.. CP2101과 연결이 올바르게 인식하면 Device 란의 콤보박스에 "Silicon Labs CP210x USB to UART Bridge"을 찾아서 선택합니다. 콤보박스 목록에 "Silicon Labs CP210x USB to UART Bridge"가 없으면 HUSKYLENS와 USB연결을 확인하시기 바랍니다.

펌웨어 파일 선택

Firmware 란의 오른쪽에있는 [...]버튼을 클릭하여 펌웨어 (HUSKYLENSWithModelVx.x.xStable.kfpkg)을 선택합니다. 선택 후 Firmware 란에 파일 이름이 표시되어 있는지 확인합니다.

펌웨어 업데이트 실행

'Open terminal after flash "의 체크를 해제합니다.
"Flash"를 클릭하여 펌웨어 쓰기 시작합니다.

펌웨어 업데이트 진행

펌웨어 쓰기가 완료 될 때까지 기다립니다. 업데이트는 약 5분의 시간이 걸립니다. 저장 중 HUSKYLENS의 디스플레이는 꺼지고, 업데이트가 완료될때까지 HUSKYLENS와 USB 연결을 분리하시면 안됩니다.

펌웨어 업데이트 완료

펌웨어 업데이트가 완료되면 아래와 같이 완료 메시지가 표시되고 HUSKYLENS가 다시 시작합니다. "OK"를 클릭 한 후 K-Flash.exe를 종료합니다.

펌웨어 업데이트 확인

펌웨어 업그레이드된 HUSKYLENS에서 펌웨어 버전을 확인하려면 "General Settings"를 선택한 후, 메뉴를 오른쪽으로 이동합니다. "Version x.x.xStable '처럼 버전이 표시되므로 업데이트된 펌웨어 버전과 일치하는지 확인 하실수 있습니다.

728x90
728x90

출처

Arduino : 2.4인치 터치 스크린 제어 ( ILI9341, UTouch )

스크린 핀연결

  • RESET 7
  • DC    9
  • CS   10
  • MOSI 11
  • CLK  13

터치 핀연결

  • CLK 6
  • CS 5
  • DIN 4
  • DO 3
  • IRQ 2

터치 테스트

#include <UTouch.h>

// Initialize touchscreen
#define PIN_CLK 6
#define PIN_CS 5
#define PIN_DIN 4
#define PIN_DO 3
#define PIN_IRQ 2

UTouch  myTouch(PIN_CLK, PIN_CS, PIN_DIN, PIN_DO, PIN_IRQ);

void setup() {
  Serial.begin(9600);
  // put your setup code here, to run once:
  myTouch.InitTouch();
  myTouch.setPrecision(PREC_HI);
}

void loop() {
  // put your main code here, to run repeatedly:
  long x, y;
  
  while (myTouch.dataAvailable() == true) {
    myTouch.read();
    x = myTouch.getX();
    y = myTouch.getY();
    if ((x!=-1) and (y!=-1)) {
      Serial.print("X = "); Serial.print(x);
      Serial.print("\tY = "); Serial.println(y);
    }
  }
}

텍스트 및 그래픽 함수 테스트

/*
 TFT LCD - TFT Simple driving
 modified on 21 Feb 2019
 by Saeed Hosseini
 https://electropeak.com/learn/
*/
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_RESET 7
#define TFT_DC    9
#define TFT_CS   10
#define TFT_MOSI 11
#define TFT_CLK  13

#define BLACK       0x0000
#define BLUE        0x001F
#define RED         0xF800
#define GREEN       0x07E0
#define CYAN        0x07FF
#define MAGENTA     0xF81F
#define YELLOW      0xFFE0
#define WHITE       0xFFFF
#define ORANGE      0xFD20
#define GREENYELLOW 0xAFE5
#define NAVY        0x000F
#define DARKGREEN   0x03E0
#define DARKCYAN    0x03EF
#define MAROON      0x7800
#define PURPLE      0x780F
#define OLIVE       0x7BE0
#define LIGHTGREY   0xC618
#define DARKGREY    0x7BEF

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RESET);

void setup() {
  Serial.begin(9600);
  Serial.println(F("TFT LCD test"));
#ifdef USE_ADAFRUIT_SHIELD_PINOUT
  Serial.println(F("Using Adafruit 2.4\" TFT Arduino Shield Pinout"));
#else
  Serial.println(F("Using Adafruit 2.4\" TFT Breakout Board Pinout"));
#endif
  Serial.print("TFT size is ");
  Serial.print(tft.width());
  Serial.print("x");
  Serial.println(tft.height());
  
  tft.begin();
  Serial.println(F("Benchmark                Time (microseconds)"));
  Serial.print(F("Screen fill              "));
  Serial.println(FillScreen());
  delay(500);
  
  tft.setTextColor(YELLOW);
  tft.setCursor(70, 180);
  tft.setTextSize(1);
  tft.println("Electropeak");
  delay(200);
  
  tft.fillScreen(PURPLE);
  tft.setCursor(50, 170);
  tft.setTextSize(2);
  tft.println("Electropeak");
  delay(200);
  
  tft.fillScreen(PURPLE);
  tft.setCursor(20, 160);
  tft.setTextSize(3);
  tft.println("Electropeak");
  delay(500);
  
  tft.fillScreen(PURPLE);
  for (int rotation = 0; rotation < 4; rotation++) { 
    tft.setRotation(rotation); 
    tft.setCursor(0, 0); 
    tft.setTextSize(3); 
    tft.println("Electropeak"); 
    delay(700); 
  }
  delay(500); 
  
  Serial.print(F("Rectangles (filled) ")); 
  Serial.println(testFilledRects(YELLOW, MAGENTA)); delay(500); 
} 
 
void loop() { 
} 

unsigned long FillScreen() { 
  unsigned long start = micros(); 
  tft.fillScreen(RED); 
  delay(500); 
  tft.fillScreen(GREEN); 
  delay(500); 
  tft.fillScreen(BLUE); 
  delay(500); 
  tft.fillScreen(WHITE); 
  delay(500); 
  tft.fillScreen(MAGENTA); 
  delay(500); 
  tft.fillScreen(PURPLE); 
  delay(500); 
  return micros() - start; 
} 

unsigned long testFilledRects(uint16_t color1, uint16_t color2) { 
  unsigned long start, t = 0; 
  int n, i, i2, cx = tft.width() / 2 - 1, cy = tft.height() / 2 - 1; 
  tft.fillScreen(BLACK); 
  n = min(tft.width(), tft.height()); 
  for (i = n; i > 0; i -= 6) {
   i2    = i / 2;
   start = micros();
   tft.fillRect(cx - i2, cy - i2, i, i, color1);
   t += micros() - start;
   // Outlines are not included in timing results
   tft.drawRect(cx - i2, cy - i2, i, i, color2);
 }
 return t;
}

터치스크린을 이용한 그림판

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include <UTouch.h>

#define PIN_CLK 6
#define PIN_CS 5
#define PIN_DIN 4
#define PIN_DO 3
#define PIN_IRQ 2
#define TS_MINX 10
#define TS_MINY 0
#define TS_MAXX 380
#define TS_MAXY 239
UTouch  ts(PIN_CLK, PIN_CS, PIN_DIN, PIN_DO, PIN_IRQ);

#define TFT_RESET 7
#define TFT_DC    9
#define TFT_CS   10
#define TFT_MOSI 11
#define TFT_CLK  13
#define  BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RESET);

#define BOXSIZE 40
#define PENRADIUS 3

int oldcolor, currentcolor;

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

  ts.InitTouch(LANDSCAPE); // PORTRAIT, LANDSCAPE
  ts.setPrecision(PREC_HI); // PREC_LOW, PREC_MEDIUM, PREC_HI, PREC_EXTREME
 
  tft.begin();
  tft.fillScreen(BLACK);
  
  tft.fillRect(0, 0, BOXSIZE, BOXSIZE, RED);
  tft.fillRect(BOXSIZE, 0, BOXSIZE, BOXSIZE, YELLOW);
  tft.fillRect(BOXSIZE*2, 0, BOXSIZE, BOXSIZE, GREEN);
  tft.fillRect(BOXSIZE*3, 0, BOXSIZE, BOXSIZE, CYAN);
  tft.fillRect(BOXSIZE*4, 0, BOXSIZE, BOXSIZE, BLUE);
  tft.fillRect(BOXSIZE*5, 0, BOXSIZE, BOXSIZE, MAGENTA);
  tft.drawRect(0, 0, BOXSIZE, BOXSIZE, WHITE);
  
  currentcolor = RED;
}

#define MINPRESSURE 10
#define MAXPRESSURE 1000

void loop() {
  long px, py;
  while (ts.dataAvailable() == true) {
    ts.read();
    px = ts.getX();
    py = TS_MAXY - 10 - ts.getY();
    if ((px!=-1) and (py!=-1)) {
      Serial.print("X = "); Serial.print(px);
      Serial.print("\tY = "); Serial.println(py);
    }
    
    if (py < (TS_MINY-5)) {
      Serial.println("erase");
      tft.fillRect(0, BOXSIZE, tft.width(), tft.height()-BOXSIZE, BLACK);
    }
    px = map(px, TS_MINX, TS_MAXX, tft.width(), 0);
    py = map(py, TS_MINY, TS_MAXY, tft.height(), 0);
    if (py < BOXSIZE) {
      oldcolor = currentcolor;
      if (px < BOXSIZE) { 
        currentcolor = RED; 
        tft.drawRect(0, 0, BOXSIZE, BOXSIZE, WHITE);
      } else if (px < BOXSIZE*2) {
        currentcolor = YELLOW;
        tft.drawRect(BOXSIZE, 0, BOXSIZE, BOXSIZE, WHITE);
      } else if (px < BOXSIZE*3) {
        currentcolor = GREEN;
        tft.drawRect(BOXSIZE*2, 0, BOXSIZE, BOXSIZE, WHITE);
      } else if (px < BOXSIZE*4) {
        currentcolor = CYAN;
        tft.drawRect(BOXSIZE*3, 0, BOXSIZE, BOXSIZE, WHITE);
      } else if (px < BOXSIZE*5) {
        currentcolor = BLUE;
        tft.drawRect(BOXSIZE*4, 0, BOXSIZE, BOXSIZE, WHITE);
      } else if (px < BOXSIZE*6) { 
        currentcolor = MAGENTA; 
        tft.drawRect(BOXSIZE*5, 0, BOXSIZE, BOXSIZE, WHITE); 
      } 
      if (oldcolor != currentcolor) {
        if (oldcolor == RED) 
          tft.fillRect(0, 0, BOXSIZE, BOXSIZE, RED); 
        if (oldcolor == YELLOW) 
          tft.fillRect(BOXSIZE, 0, BOXSIZE, BOXSIZE, YELLOW); 
        if (oldcolor == GREEN) 
          tft.fillRect(BOXSIZE*2, 0, BOXSIZE, BOXSIZE, GREEN); 
        if (oldcolor == CYAN) 
          tft.fillRect(BOXSIZE*3, 0, BOXSIZE, BOXSIZE, CYAN); 
        if (oldcolor == BLUE) 
          tft.fillRect(BOXSIZE*4, 0, BOXSIZE, BOXSIZE, BLUE); 
        if (oldcolor == MAGENTA) 
          tft.fillRect(BOXSIZE*5, 0, BOXSIZE, BOXSIZE, MAGENTA); 
      }
    }
    
    if (((py-PENRADIUS) > BOXSIZE) && ((py+PENRADIUS) < tft.height())) {
      tft.fillCircle(px, py, PENRADIUS, currentcolor);
    }
  }
}

실행 영상

728x90
728x90

출처

소스

/*Example sketch to control a 28BYJ-48 stepper motor with ULN2003 driver board, and Arduino UNO. More info: https://www.makerguides.com */
// Include the Arduino Stepper Library:
#include <Stepper.h>
// Number of steps per rotation:
const int stepsPerRevolution = 2048;
//Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);
void setup()
{
  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  // Initialize the serial port:
  Serial.begin(9600);
}
void loop() 
{
  // Step one revolution in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);
  // Step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

실행 영상

728x90
728x90

출처 : 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";
}
728x90
728x90

출처 : 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);
}
728x90
728x90

출처 : 블루투스 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);
}
728x90

+ Recent posts