2018/02/27

Arduino - Switch celling light with TV remote (2/2)

This is the part two of Switch celling light with TV remote tutorial. If needed, please check out the part one from link below. By the way, the source code is also available there.


Quick Link


System Design

See the illustration below. I used a phone charger(purple block; AC110V to DC5V) to supply power from 110v AC power outlet from the celling. The Arduino controls the relay module to switch the celling light and Arduino interpret IR code to change  RGB LED to shift color and on/off accordingly. 

Connections

  • IR Receiver to Arduino pin 2
  • IR Receiver + to VCC
  • IR Receiver - to GND
  • Relay + to VCC
  • Relay - to GND
  • Relay to Arduino pin 8
  • RGB Red to Resistor to Arduino pin 3
  • RGB Green to Resistor to Arduino pin 5
  • RGB Blue to Resistor to Arduino pin 6
  • *** CAUTION: Turn off home main power switch first before 110V connection! ***
  • *** Connect 110V to the system after you secure prefboard to the celling light ***
  • Connect 110V VCC to "Relay NO (Normally Open)" on the left
  • Connect Relay COM (Common connection) to 110V GND. 

      Step by step



      Solder pins to Arduino mini pro.

      Pick up the corner of the perfboard as the fix position. Then, solder pin header connectors on the side of Arduino mini pro, so we could have the flexibility to change wiring later.  Don't forget to face Arduino five data pins towards outside of the prefboard for easier connection to upload source code later.

      Selected few unused solder holes from the Arduino Mini Pro and used the connection pin headers as supporting material on the perfboard. This could prevent unintentional shortage. See below:


      After fixed Arduino Mini Pro in place, solder RGB LED, resistors, and wires to the prefboard. 
      Remember to power up to test the whole setup before moving forward.


      I used a screw to fix the relay module on the perfboard. However, fixed on one side is not stable enough, so I took a cable tight to keep the relay module tightly in place.  *Remember to reserve a very long IR reception wire*, so the IR receiver could placed outside of the celling light or the IR receiver might be obscured by the decorative glass cover.



      Here is the over all system in action!



      Next, find a good power source for the system. 
      For this project, I used a HTC smart phone charger. At least, HTC is (or was?) an international brand name smartphone company and has good reputation regarding to safety. Again, for safety reason, please use certified chargers only, such as CE, FCC, UL from well-know brand name company. *** Do not use no brand or very cheap chargers from unknown source. You are on your own risk! ***



      I used a short USB cable to connect the HTC charger to the system.  Cut the USB cable near micro-B (smaller connector) and strip the shielding off the cable. In there, you will find four wires with GREEN, WHITE, RED, BLACK. Solder the RED(5V+) and BLACK(GND) wires to positive and negative respectively on the perfboard. 

      Cable connection:
      • USB type-A (Larger connector) to HTC charger
      • USB micro-B (smaller connector) to system



      After soldered the USB wires, plug the charger to power outlet and test the system.



      My bedroom celling light looks like this below. It has a switch located at the entrance of the bedroom. And the switch works like this. After implement this system, the control of the switch will be shift to Arduino Mini Pro.

      For every switch on/off, it cycles through 

      1.  Turn on three lights
      2.  Turn off
      3.  Turn on Five lights
      4.  Turn off 
      5.  Turn on two lights
      6.  Turn off



      Carefully loosen the screw from the bottom glass cover and remove the decorative glass away.


      Drill a hole on the light base for tightening the system.


      Use a screw to secure the prefboard to the celling light as shown below.


      *** Important: Wrong connection will cause the light not working ***
      • Connect 110v VCC to "Relay NO (Normally Open)" on the left
      • Connect Relay COM (Common connection) to 110v GND



      When connect AC 110V power line to phone charger, please make sure the isolation is done properly. It would be better to use Heat shrink tube for the isolation. However, I didn't have those on hand, so I used the isolation tape and tight them 3~4 times to ensure it's 100% isolated.  

      *** Disclaimer: Many experts expressed safety concerns for connecting Arduino with relay to AC 110V power!  I'm not responsible for any damage or lose that could happened to your projects or properties! You are at your own risk of doing this! ***



      Before tighten the light frame and decorative glass back to the celling, use the remote to test the system to see if it's working as expected.

      See the red circle below, that's the IR receiver that I used an extended wire from the perfboard to the rim of the light to get better IR reception.



      Let's try to change the color with the TV remote.


      Finally, the project is completed! Watch the video below to see it in action!
      Now I can turn the celling light off directly from my bed after turn TV off!  




      This is the end of this tutorial. I hope you liked it! Please leave comments below and I will see you next time.

      Enjoy!


      2018/02/25

      Arduino - Switch celling light with TV remote (1/2)

       Preface

      It must be happened to you before that in a very cold night watching TV or movie in bed and you were ready for bed. You turned off the TV or DVD player with remote control easily. However, for the celling light, you just had to get out of the bed to turn the light off. What a pain! 

      After I searched the Internet, there are many examples out there suit for this purpose, such as IR receiver, relay module, and RGB LED shift hue and most of them have codes that I could utilize on this project.  

      Quick Link

      Material Needed

      • Arduino mini pro *1 
      • USB upload module *1 
      • Relay module (5V/10A/125V) * 1 
      • IR Receiver LED * 1 (Aixin AX-1838HS 38KHz * 1 / All 38KHz should work) 
      • RGB LED *2 
      • Resister 220 Om * 3
      • Few jump wires
      • Any TV or DVD remote you have at home
      • Breadboard * 1
      It's not difficult to find these components on Amazon or eBay.

      System Functionality

      Assign two buttons on the remote to control the celling light. Remember to assign less frequently used buttons on the remote or you might accidentally activate the particular function on your appliances. :)
      • Button 1: Turn on/off
      • Button 2: Switch LED color hues (static or color shifting)

      Schematic

      This schematic is made with Fritzing. 
      You can download it from its official website: www.fritzing.org


      Connections

      • IR Receiver to Arduino pin 2
      • IR Receiver + to VCC
      • IR Receiver - to GND
      • Relay + to VCC
      • Relay - to GND
      • Relay to Arduino pin 8
      • RGB Red to Resistor to Arduino pin 3
      • RGB Green to Resistor to Arduino pin 5
      • RGB Blue to Resistor to Arduino pin 6

      Check Remote IR code

      You have to find out the remote button IR codes on your remotes and embed them in the source code below for this project to work.


      For Example, my Sanyo TV remote has the following codes. As you can see, I have assigned two buttons for each feature to have a fall back plan.

      • Celling Light Switch function
        • Mute:irCode: 1CE318E7,  bits: 32  sanyoLight1
        • Channel minus :irCode: 1CE3D02F,  bits: 32  sanyoLight2
      • LED Switch function
        • Volume minus :irCode: 1CE3F00F,  bits: 32  sanyoLED1
        • CH View: irCode: 1CE352AD,  bits: 32 sanyoLED2

      To find out the IR codes for you remote, please refer to my previous IR Repeater Tutorial (Part 2)

      Source Code

      /*
       * Author: Stonez56
       * IRRemote for bedroom lighting control 
       *   Light buttons: Switch lights through the 
       *            cycle - 3, 5, 2, off with 2 types of remote
       *   LED buttons: Switch display random color a, b, transistion, off
       */
      
      #include <IRremote.h>
      
      // Setting up pins
      // Setup pin 8 for relay. 
      //    For some reason, Pin 13 will cause relay to switch one time
      //    when system powers on
      const int relay1Pin = 8; 
      const int redPin = 3;                    
      const int greenPin = 5;
      const int bluePin = 6;
      const int irReceiverPin = 2;
      
      // Milisecond to delay when shifting colors
      int colorShiftTime[] = {20, 10, 1, 50}; 
      int colorShiftTimeCounter = 0;
      
      int myPins[] = {2, 4, 8, 3, 6};
      int LEDstatus = 0;       // mode of LED or switch light
                          /*
                           * 0 = LED off
                           * 1 = LED orange
                           * 2 = LED color rotation
                           * 3 = Relay Light swtich
                           */
      
      int relay1Status = 0; // Switch of the relay; either 1 or 0;
      
      
      IRrecv irrecv(irReceiverPin);            
      decode_results results;  // IR decode_results 
      
      unsigned int rgbColour[3]; //RGB LED array
      
      unsigned int preCode = 0x0;  //Previous remote code
      unsigned int currentCode = 0x0; //Current remote code
      
      /* Define remote codes  
      Remote A (iBit Remote)
       Switch
        - (L/R) irCode: 609E09F6,  bits: 32 bitLigth1
        - Subtitle:irCode: 609E8877,  bits: 32  bitLight2
       LED Switch
        - Sound change irCode: 609E42BD,  bits: 32 bitLED1
        - Favorite channel:irCode: 609E728D,  bits: 32 bitLED2
        LED Color speed 
          - colorShiftTime: irCode: 
      
      */
       
      const unsigned long bitLight1 = 0x609E09F6;
      const unsigned long bitLight2 = 0x609E8877;
      const unsigned long bitLED1 = 0x609E42BD;
      const unsigned long bitLED2 = 0x609E728D; 
      const unsigned long bitLEDspeed = 0x609EAA55;
      /*
      Remote B (Sanyo Remote)
       Switch
        - Mute:irCode: 1CE318E7,  bits: 32  sanyoLight1
        - Channel minus :irCode: 1CE3D02F,  bits: 32  sanyoLight2
       LED Switch
        - Volume minus :irCode: 1CE3F00F,  bits: 32  sanyoLED1
        - CH View: irCode: 1CE352AD,  bits: 32 sanyoLED2
        LED Color speed
          - colorShiftTime: irCode: 
      
      */
      const unsigned long sanyoLight1 = 0x1CE318E7;
      const unsigned long sanyoLight2 = 0x1CE3F00F;
      const unsigned long sanyoLED1 = 0x1CE352AD;
      const unsigned long sanyoLED2 = 0x1CE3D02F;
      const unsigned long sanyoLEDspeed = 0x1CE350AF;
      
      void setup()
      {
        
        //////Serial.begin(9600);   
        irrecv.enableIRIn(); // enable IR pin
        pinMode(relay1Pin, OUTPUT);
        // Start off with the LED off.
        ledOff();
      }
      
      // Turn off LED
      void ledOff(){
        rgbColour[0] = 255;
        rgbColour[1] = 255;
        rgbColour[2] = 255;  
        setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]);
      
        preCode = currentCode;
        while(preCode == currentCode){
              currentCode = checkRemoteCode();
              // Check the code on Serial port
              Serial.print(rgbColour[0]); Serial.print(" | ");
              Serial.print(rgbColour[1]);  Serial.print(" | ");
              Serial.println(rgbColour[2]);
        }
      }
      
      /*
      * Turn on LED to Orange color
      */
      void ledOrange(){
        //LED color orange??
        rgbColour[0] = 65391;
        rgbColour[1] = 400;
        rgbColour[2] = 255;  
        setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]);
      
        preCode = currentCode;
        while(preCode == currentCode){
              currentCode = checkRemoteCode();
        }
      
      }
      
      
      /*
       * Rotating RGB LED color
       */
      void colorRotation(){
        // Start off with red.
        rgbColour[0] = 0;
        rgbColour[1] = 255;
        rgbColour[2] = 255;  
      
        preCode = currentCode;
       
        // Choose the colours to increment and decrement.
        for (int decColour = 0; decColour < 3; decColour += 1) {
          int incColour = decColour == 2 ? 0 : decColour + 1;
       
          // cross-fade the two colours.
          for(int i = 0; i < 255; i += 1) {
            rgbColour[decColour] -= 1;
            rgbColour[incColour] += 1;   
      
            setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]);
            delay(colorShiftTime[colorShiftTimeCounter]);
            currentCode = checkRemoteCode();
      
      /*
            Serial.print(" R:");Serial.print(rgbColour[0]);
            Serial.print(" G:");Serial.print(rgbColour[1]);
            Serial.print(" B: ");Serial.println(rgbColour[2]); 
            */     
            //if accepted new remote codes,
            //     exit this function and back to the main loop;
            if(preCode != currentCode){
              return;
            }
          }
        }
      } // End of LED color rotation
      
      
      /* This turn on/off relay switch
       *
       */
      void switchRelay(){
        relay1Status = 1 - relay1Status;   
         if(relay1Status == 0){
          digitalWrite(relay1Pin, HIGH);
          delay(500);
         }else{ 
          digitalWrite(relay1Pin, LOW);
          delay(500);
         }
      }
      
      /* Check remote code and return a mode to be changed
       *
       */
      int checkRemoteCode(){
        if (irrecv.decode(&results)) { // Received IR code and decoded ok!
          // Print to Serial port for debug purposes
          Serial.print("Color shift time: ");
          Serial.print(colorShiftTime[colorShiftTimeCounter]);
          Serial.print("  irCode: ");           
          Serial.print(results.value, HEX);    // IR decode
          Serial.print(",  bits: ");          
          Serial.println(results.bits);        // IR codes
          
          irrecv.resume();                    // Continue to receive next IR code 
          if(results.bits == 32){ //only 32bit code will be evaluated
            switch(results.value){
              /*All these buttons switch lights */ 
              case bitLight1:
              case bitLight2:
              case sanyoLight1:
              case sanyoLight2:  
              case 0x992A2843: //Benq Remote Green button for test
                   LEDstatus = 3; //switch relay;
      
                break;
              case bitLED1:
              case bitLED2:
              case sanyoLED1:
              case sanyoLED2:
                    //Check LEDstatus and switch to next mode
                    LEDstatus += 1;
                    if(LEDstatus >= 3){ 
                        LEDstatus = 0; //LEDstatus only has 0,1,2 if == 3, reset it to 0;
                    }
                break; 
              case bitLEDspeed:
              case sanyoLEDspeed:
                    colorShiftTimeCounter++;
                    if(colorShiftTimeCounter==4){ 
                        colorShiftTimeCounter=1; //only 4 elements, from 0~3
                      }
                    colorShiftTime[colorShiftTimeCounter];
                break;
              default:
                break;        
            } //switch
          } // check 32bits
        } //end of get a remote code
      
        return LEDstatus;
      }
      
      void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
        analogWrite(redPin, red);
        analogWrite(greenPin, green);
        analogWrite(bluePin, blue);
       }
      
      void loop(){
        switch(LEDstatus){
           case 0:
              ledOff();
              break;
           case 1:
              ledOrange();
              break;
           case 2:
              colorRotation();
              break;
           case 3:
              switchRelay();
              LEDstatus = 99;
              break;
           default: // set it up to do nothing, but wait the remote code to activate
               break;
        }
        //constanly check new remote code
        LEDstatus = checkRemoteCode();
        //////Serial.print("LEDstatus: ");Serial.println(LEDstatus);
      } // end of loop
      
      
      Here is the prototype in the photo below.



      In next tutorial, I will show you the 2nd phase to put everything together and install the whole system in the celling light.  See you soon!


      2017/12/04

      MIT Scratch Game: Ghoul Buster

      This game, Ghoul Buster, is made by my son Ryan with the MTI Scratch. Ryan is 7th grade now and this was a project he made at school when he was 6th Grade. If you watched to the end, there is a big enemy boss with really powerful thunder weapons to attack the battleship! He is planning to make level 2 of this game.

      I am still trying to convince my son to write a tutorial on how to make this...

      我兒子今年國一,這個遊戲 Ghoul Buster是他在小學六年級時做的。Ryan 使用了MIT Scratch 做了這個遊戲。玩起來有 Arcade 雷電的感覺!如果你有看到最後面,他設計的大魔王有很強大的閃電來功擊玩家的太空船! 目前他還在試著做出第二關。

      目前我正在說服我兒子來寫一篇如何用 Scratch 來做個教學....

      #scratch #scratchgame #mitscratch #minigame #game #kids #coding #programming #kidscoding #kidsprogramming #hourofcode #selfmade #selfmadegame #play #playgame #stonez56 #ryan #yuanryan #yuanryangames





      2017/11/12

      Getting Started with EPS8266-12E Wi-Fi | ESP8266-12E 筆記本



      I wanted to test out ESP8266 for a long time. However, I never got it to work until today. There are many tutorials and articles detailed how to make ESP8266 work, but even I followed many of those tutorials step by step mine ESP8266 just didn't work.  It was very frustrating not able to figure out what went wrong.  Anyway, I got it worked today, so it's better for me to write the steps down, not just for blog visitor like you, but also for myself as a good reference later on.

      Previous three failed attempts... 😒


      Different Version of ESP8266

      There are many ESP8266 variations, the one I used for this tutorial is ESP8266-12E. Please refer to this page[2] to get more information for ESP8266 variations.

      ESP8266 Pin Assignment

      Most of the people probably will solder ESP8266 with metal covers facing up, so I placed a reversed pin assignment on the right side for easier pin reference.

      Material Needed:
      • ESP8266-12E * 1
      • Perfboard * 1 
      • Breadboard * 1 
      • Wires - as many as needed
      • Resistors 1K * 4 
      • CP2102 USB-Serial Converter * 1
      Tools Needed:
      • Power supply (3.3V)
      • Soldering iron 
      • Solder Tin
      • Plier-wire cutter
      • Plier

      Step One: 

      ESP8266 has 2mm pin pitch instead of 2.54mm standard pitch. So we have to place it on a prefboard to make connections easier. 

      Place ESP8266 on a prefboard and draw its relative size that's larger to accommodate pins along both sides for easier connections with DuPoint wires. Cut down the piece of prefboard with a plier. 

      [Important: I later found out from the ESP8266 datasheet recommended to place Wi-Fi antenna outside of prefboard to get better signal reception & transmission.] 😄

      Step Two:

      Solder wires on each ESP8266 pin to the prefboard as shown below. I found out that after stripped skin of the wires, soldering job just got a little bit easier.

      Note: My previous attempt was to solder wires without strip the wire skin and it was more difficult to solder; harder to bend the wires. Be careful, do not short these wires! :) 

      Step Three:

      Solder 8 pin headers on each side of ESP8266 as shown below.

      Step Four: 

      Time to connect all wires together. Check out the schematic diagram below for all the connections needed.

      Schematic Diagram




      ESP8266 Connection:

      1. VCC -> 3.3V power source
      2. EN-CHPD -> 1K resistor -> 3.3V
      3. Reset -> 1K resistor -> 3.3V
      4. TX -> USB/UART RX
      5. RX -> USB/UART TX
      6. GPIO0 -> do not connect anything for this AT command tutorial
      7. GPIO15 -> 1K resistor -> GND
      8. GND -> GND
      CP2012 USB/UART Connection
      1. RX -> ESP8266 TX
      2. TX -> ESP8266 RX
      3. GND -> GND (command ground with ESP8266)
      NOTE:
      • Supply 3.3V to EPS8266! 5V will burn ESP8266!
      • GPIO-0 is connected to GND: upload Arduino programming code. 
      • GPIO-0 is not connected: Enter AT Command.


      Step Five:

      Here, I used a red breadboard for wire connections with resistors and the power supply. As long as you follow the schematic diagram above and wiring tips for the connection, it shouldn't be too difficult. (I only use two transistors to share with common pins to VCC and GND.  Not sure if this is a good practice?)


      I have purchased an inexpensive power supply as the 3.3V power source. It displayed the how much the current is using, in this case "068mA",  allowing me to see what power was consumed at the particular point of time, which it's very convenient!  I checked ESP8266 datasheet "68mA ~ 71mA" means it's working probably.


      Step Six:

      Test AT Command. I think this is a quick method to check whether the ESP8266 is working or not. 
      • Connect CP2012 to a Mac USB port
      • Power on power supply with 3.3V 

      Arduino IDE Operations:

      • First, let's load ESP8266 Library into Arduino IDE
      • Copy this string "http://arduino.esp8266.com/stable/package_esp8266com_index.json" into Arduino IDE preference -> Settings -> Additional Board Manager URLs. See below in yellow highlighted strings.



      • Select correct Arduino board type. Select "ESPino (ESP-12 module)" If you don't see this option, please restart Arduino IDE to ensure the library is properly loaded.


      • Select Port from port list. My serial port is /dev/cu.SLAB_USBtoUART


        • Click [Tools] - [Serial Monitor] from Arduino IDE to open the serial monitor.
        • Select baud rate from the baud rate list below. Select [115200 baud].  Your ESP8266 might have default baud rate of 9600 or 38400. If 15200 doesn't work, please try all other baud rate values.

        Start AT Command

        • AT:  You should be able to see the terminal replied "AT   OK" back. Congratulation, your ESP8266 is working!

        • AT+GMR: Display ESP8266 firmware version. My ESP8266 is V1.2.0.0 Date: Dec 2, 2016.  
        • AT+CWJAP="Wi-Fi_SSID","Password": Connect to the particular Wi-Fi Access point with the password designated.  As you can see, the WiFi got connected immediately. 
              

        • AT+CWMODE?[1]: Setup ESP8266 working mode. Let's setup ESP8266 to mode 3 both STA and AP. This allows ESP8266 connecting to your Wi-Fi router/Access point as a client also works as a router/Access point allowing other Wi-Fi client connect to it.
          • AT+CWMODE=1: STA (Become a Wi-Fi client to connect to AP)
          • AT+CWMODE=2: AP (Become an Assess point, so other clients can connect to this AP)
          • AT+CWMODE=3: BOTH = STA + AP (As an access point and a Wi-Fi client)

        • AT+CIFSR: Get IP Address. Since we setup CWMODE=3 (STA+AP mode), the first IP you see is AP IP (ESP8266 IP 192.168.4.1), the second IP is the WAN IP(your Wi-Fi IP 192.168.0.105 where ESP8266 is connected to)


        • AT+CWLAP: Scan Wi-Fi AP in the nearby area and show them all in a list.
          Text in first double quotes are WI-Fi SSID.


          • AT+RST: Reset command to reset ESP8266



          It's great! Your ESP8266 is ready to connect to the Internet.

          Load First Arduino Code:

          ESP8266 can be used as an Arduino board itself without buying another Arduino board to work with ESP8266. Let's flash Arduino code into ESP8266 to test it out. 
          1. Connect GPIO0 -> 1K resistor -> GND (Without GPIOpull low, you can't flash code to ESP8266!
          2. Copy the code below into your Arduino IDE and upload the code and the ESP8266-12E
          *********************************************************************************
          IMPORTANT:  After you upload Arduino codes, the AT command will no longer work. If you still prefer use AT command with ESP8266, you have to reflash AT command firmware to enable it. 

          It took me few days to figure out this!
          ***
          ******************************************************************************

          First Arduino code for ESP8266-12E, Connect to Wifi

          This Arduino code below will connect ESP8266 to your WiFi AP/router and display the IP address it obtain.  For this code to work, please replace Wifi_SSID with your Wifi-SSID and Wifi_Password with your own Wifi-Password. Do not forget to open Arduino IDE serial port to see the connection message!

          #include <ESP8266WiFi.h>
          
          void setup()
          {
            Serial.begin(115200);
            Serial.println();
          
            WiFi.begin("Wifi_SSID", "Wifi_Password");
          
            Serial.print("Connecting");
            while (WiFi.status() != WL_CONNECTED)
            {
              delay(500);
              Serial.print(".");
            }
            Serial.println();
          
            Serial.print("Connected, IP address: ");
            Serial.println(WiFi.localIP());
          }
          
          void loop() {}
          
          

          Second Arduino code for ESP8266-12E, Blink

          #include <ESP8266WiFi.h>
          void setup()
          {
            Serial.begin(115200);
            Serial.println();
            pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
          
            WiFi.begin("Wifi-SSID", "Wifi-Password");
          
            Serial.print("Connecting");
            while (WiFi.status() != WL_CONNECTED)
            {
              delay(500);
              Serial.print(".");
            }
            Serial.println();
          
            Serial.print("Connected, IP address: ");
            Serial.println(WiFi.localIP());
          }
          
          void loop() {
            digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                              // but actually the LED is on; this is because 
                                              // it is acive low on the ESP-01)
            delay(1000);                      // Wait for a second
            digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
            delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
            }
          

          That's all for this step by stpe notes. Hope you are getting something from here! :)

          REFERENCE

          1. ESP8266 Wi-Fi Library Great info to get more about ESP8266 Wi-Fi Library as well as what's AP, STA, and BOTH modes.
          2. Various ESP8266 boards Great info to understand the different types of ESP8266.
          ==============================================================

            EPS8266-12E Wi-Fi 筆記

          真的很高興,這個部落格在這幾天已經超過30萬的瀏覽次數!謝謝大家拜訪Stonez56的部落格來獲取有對你價值的資訊。😁

          長久以來,我一直想測試ESP8266,但是一直沒有成功。雖然,網上有很多教學和文章詳細介紹如何使用ESP8266,但即使我跟著很多這些教學一步一步地做,大部份都失敗了。 很多時候無法弄清楚哪裡出了問題,真是令人非常沮喪。 今天我手上的ESP8266已經正常的能回覆 AT Command,所以我趕快把這些步驟寫下來,不只可以提各位讀者參考,以後也可以作為自己的一份筆記。

          看看我之前失敗的例子...都堆在角落裡!


          不同版本的 ESP8266

          市面上有很多不同的版本,請參考這裡[2] 來了解其它ESP8266版本的差異。


          ESP8266 腳位說明

          ESP8266腳位說明如下。 由於大多數人可能會把ESP8266的金屬蓋朝上焊接,所以我在右側放置了一個反向的腳位,以便於大家參考。

          所需材料:

          •      ESP8266-12E * 1
          •      洞洞板* 1
          •      麵包板* 1
          •      電線 - 十多條
          •      電阻器1K * 4
          •      CP2102 USB 轉換器 * 1

          所需工具:

          •      電源(3.3V)
          •      烙鐵
          •      焊錫
          •      鋼絲鉗
          •      鑷子

          步驟一:

          ESP8266 腳位是 2mm 的間距,而不是2.54mm的標準間距。 所以我們必須把它銲在洞洞板上以方便連接

          先將ESP8266放置在
          洞洞板上,並畫下其相對尺寸較大的尺寸,沿著兩側留下兩三個洞的距離,等會要銲上接腳,便於用杜邦線測試連接。 先用鉗子剪下畫好大小的洞洞板。

          [重要說明:我從ESP8266官方文件中發現,
          Wi-Fi天線不能放在金屬的上方,以便獲得更好的接收信號和處理能力!所以最後我把天線底下的洞洞板都用斜口鉗剪掉!]😄

          步驟二:

          如下所示,把每個ESP8266的腳位上用電線連接到洞洞板上。我發現電線剝皮後,比較容易焊一些。我看許多網友也都這樣做!

          注意:我以前的嘗試是焊接電線時沒有剝掉電線的外皮,焊接起來也比較困難; 也較不容易彎曲電線。 但是請小心,不要把這些電線短路! ☺

          步驟三:

          在ESP8266的兩側焊接上 8 個針腳,如下所示。

          步驟四:

          參考下面的示意圖,把所有電線接好準備測試。

          Schematic Diagram


          ESP8266連接方法:

          •      VCC - &gt; 3.3V 電源
          •      EN-CHPD - &gt; 1K 電阻 - &gt;3.3V
          •      重置 - &gt; 1K 電阻 - &gt;3.3V
          •      TX - &gt; USB / UART RX
          •      RX - &gt; USB / UART TX
          •      GPIO0 - &gt; 請先不要連接任何腳位,才能做 AT Command 測試
          •      GPIO15 - &gt; 1K 電阻 - &gt;GND
          •      GND - &gt;GND

          CP2012 USB / UART連接方法:

          •      RX - &gt; ESP8266 TX
          •      TX - &gt; ESP8266 RX
          •      GND - &gt; GND(ESP8266共同接地)

          注意:

          •      EPS8266只能使用 3.3V 電源! 使用5V會燒掉ESP8266!
          •      GPIO-0連接到GND:可上傳Arduino程式
          •      GPIO-0未連接:可輸入AT Command


          步驟五:

          如下圖,我用一個紅色小麵包板用來連接電阻和電源連接。 只要你按照上面的示意圖和接線提示連接即可。 (我只使用兩個 1K 電阻與VCC和GND共用腳位,不知道這是否是一個好的方法?)

          我買了一台電源供應器來提供3.3V穩定電源。它也可以顯示目前的電流量,如:“068mA”,讓我知道在特定的時間點,電流量是多少,非常方便! 我查了一下ESP8266的資料“68mA〜71mA”,表示它 Wi-Fi 是開啟中工作中。


          步驟六:

          測試AT命令。這是一個檢查ESP8266是否正常運作的快速方法。
          •      將 CP2012 連接到 Mac USB
          •      開啟3.3V電源

          Arduino IDE使用說明:

          •      先讓我們將ESP8266程式資料載入到Arduino IDE 中
          •      將此字串 “http://arduino.esp8266.com/stable/package_esp8266com_index.json” 複製到Arduino IDE Preference - &gt; Settings - &gt; Additional Board Manager URLs:  下方我用黃色標出的字符:



          • 一定要選擇正確的Arduino類型。 在選單中選擇“ESPino(ESP-12 Module)”如果您沒有看到此選項,請重新啟動一次Arduino IDE以確保ESP8266資料有帶進來。


          • 選擇 Port,我的 serial port 設定是 /dev/cu.SLAB_USBtoUART


            • 按一下 [Tools] -> [Serial Monitor] 打開序列埠的監看視窗。
            • 選擇連接速率 baud rate。 我用的是 [115200 baud].  您的ESP8266的內建速率可能是9600或38400.如果15200沒法使用,請嘗試所有其他的速率值。

            開使使用 AT Command:

            • 在最上方的命令列上打 AT,您應該能夠看到監看視窗回答“AT OK”。 恭喜,您的ESP8266已在正常工作中!

            • AT+GMR: 顯示 ESP8266 軔體版本. 我的 ESP8266 是 V1.2.0.0 Date: Dec 2, 2016.  
            • AT+CWJAP="Wi-Fi_SSID","Password": 使用指定的SSID 和 密碼 連接到特定的Wi-Fi分享器或路由器。 監看視窗會顯示,WiFi已連接成功!
                  

            • AT+CWMODE?[1]: 設定ESP8266工作模式。讓我們將ESP8266設置為模式3 STA和AP。 這可以讓ESP8266作為客戶端連接到您的Wi-Fi路由器,ESP8266自己也可以作為路由器/,允許其他Wi-Fi客戶端連接到它。
              • AT+CWMODE=1: STA (Become a Wi-Fi client to connect to AP)
              • AT+CWMODE=2: AP (Become an Assess point, so other clients can connect to this AP)
              • AT+CWMODE=3: BOTH = STA + AP (As an access point and a Wi-Fi client)

            • AT+CIFSR: 顯示IP位址。 由於我們設置了CWMODE = 3(STA + AP模式),所以您看到的第一個IP是ESP8266自己的 IP(ESP8266 IP 192.168.4.1),第二個IP是連到Internet的路由器 IP(ESP8266 Wi-Fi IP 192.168.0.105)


            • AT+CWLAP: 掃描附近區域的Wi-Fi 路由器,並將其全部顯示在列表中。
              下方左側第一個雙引號中的文字是各路由器的 SSID。為了安全,我把 mac adress 畫掉了~


              • AT+RST: 重置 ESP8266,讓它重新開機!


              太好了! 您的ESP8266已準備好連接到Internet。

              載入第一個Arduino 程式到 ESP8266:

              其實ESP8266可以當作一般Arduino板來使用,它上面也有很多 I/O 腳位,不要再連另一塊 Arduino 來節省成本。 現在我們把Arduino的程式碼載入到ESP8266中進行測試。
              • 記得連接GPIO0 -&gt; 1K電阻器 - &gt; GND(GPIO0 要 pull low,不然,程式碼無法載入到ESP8266!
              • 將以下程式碼複製到您的Arduino IDE並載入到ESP8266-12E裡
              *********************************************************************************
              重要提示:在您上傳Arduino程碼後,AT命令將不能再使用。 如果您仍然想要使用ESP8266的AT命令,則必須上載AT command 的軔體才能再使用。
              ***
              ******************************************************************************

              第一個 ESP8266-12E 程式,連接到 WiFi AP :

              下面這個Arduino程式碼將啟動ESP8266連接到您的WiFi AP /路由器,並顯示它取得的IP地址。 要使用此程式碼,記得把您的Wifi密碼將Wifi_SSID替換為您的Wifi-SSID和Wifi_Password。

              #include <ESP8266WiFi.h>
              
              void setup()
              {
                Serial.begin(115200);
                Serial.println();
              
                WiFi.begin("Wifi_SSID", "Wifi_Password");
              
                Serial.print("Connecting");
                while (WiFi.status() != WL_CONNECTED)
                {
                  delay(500);
                  Serial.print(".");
                }
                Serial.println();
              
                Serial.print("Connected, IP address: ");
                Serial.println(WiFi.localIP());
              }
              
              void loop() 
              {}
              

              第二個 ESP8266-12E 程式,  閃爍 ESP8266 內建 LED

              #include <esp8266wifi.h>
              
              void setup()
              {
                Serial.begin(115200);
                Serial.println();
                pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
              
                WiFi.begin("Wifi-SSID", "Wifi-Password");
              
                Serial.print("Connecting");
                while (WiFi.status() != WL_CONNECTED)
                {
                  delay(500);
                  Serial.print(".");
                }
                Serial.println();
              
                Serial.print("Connected, IP address: ");
                Serial.println(WiFi.localIP());
              }
              
              void loop() {
                digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                                  // but actually the LED is on; this is because 
                                                  // it is acive low on the ESP-01)
                delay(1000);                      // Wait for a second
                digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
                delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
                }
              

              OK,希望你從這裡能得到你要的一些資訊!:)

              參考文件:

              1. ESP8266 Wi-Fi Library Great info to get more about ESP8266 Wi-Fi Library as well as what's AP, STA, and BOTH modes.
              2. Various ESP8266 boards Great info to understand the different types of ESP8266.