LED調光_WEBからと外付けのボリュームからを切り替えて調光(例)



/*
 *    WiFi LED ON/OFF TEST
 *     PWM Control
 */
 
#include <WiFi.h>
#include "FS.h"
#include <SPIFFS.h>
#include <Ticker.h>

//#define DEBUG

const char* ssid = "hogehoge";
const char* password = "hogehogepaswd";

IPAddress ip(192, 168, 1, 32);           // for fixed IP Address
IPAddress gateway(192,168, 1, 1);        //
IPAddress subnet(255, 255, 255, 0);      //
IPAddress DNS(192, 168, 1, 90);          //

WiFiServer server(80);

String html_1;
String resp_1;
byte led_brightness = 0 ;
int val = 0 ;
char local_val[10]="checked" ;
char remote_val[10]="" ;
bool local = true ;
bool localen = false ;

Ticker ticker;
bool ticker_val = false ;
int vol_value = 0 ;
int loopcnt = 0;

void setup()
{
    Serial.begin(115200);
    SPIFFS.begin();          //SPIFFSを開始
    pinMode(2, OUTPUT);      // set the LED pin mode

    WiFi.config(ip, gateway, subnet, DNS);   // Set fixed IP address
    delay(10);

    // We start by connecting to a WiFi network -----------------------------
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    
    server.begin();

    //index.htmlファイルの読み込み
    File index1 = SPIFFS.open("/test_pwm_vol.html", "r");
    if(!index1)
       Serial.println("file open failed");
    else{
      html_1 = index1.readString();    //index.htmlをstringで読み込み
      index1.close();     //ファイルを閉じる
    }

    //resp.htmlファイルの読み込み
    File index2 = SPIFFS.open("/resp_slid.html", "r");
    if(!index2)
       Serial.println("file open failed");
    else{
      resp_1 = index2.readString();    //index.htmlをstringで読み込み
      index2.close();     //ファイルを閉じる
    }      

    // for LED PWM Control ---------------------------------------------------
    ledcSetup(0, 5000, 13);        // setup channel 0 with frequency 5000 Hz, 13 bit precission for LEDC timer
    ledcAttachPin(2,0);            // attach pin 2 to channel 0
    ledcWrite(0, 0);               // initialize channel 0 to off     

    // for Ticker 
    ticker.attach_ms(100, execTicker) ; // 割り込み間隔と割り込み処理を設定。

}

void loop(){
  WiFiClient client = server.available();     // listen for incoming clients
  int pos ;
  int xhr ;
  String cmd = "" ;
  String htmlwk = "" ;
  String respwk = "" ;

  if (ticker_val) {  // フラグが true だったら、処理を実行。
     do_JOB() ;
  }

  if (client) {                                               // if you get a client,
    # ifdef DEBUG
        Serial.println("***** Client access start *****");       // print a message out the serial port
    #endif
    xhr = 0 ;
    while (client.connected()) {                              // loop while the client's connected
      if (client.available()) {                               // if there's bytes to read from the client,
        String line = client.readStringUntil('\n');           // Get Line data until '\n'
        # ifdef DEBUG
            Serial.println(line);
        #endif
        if ((pos= line.indexOf("GET /?remote")) != -1) {
          pos += 13 ;
          while(line.charAt(pos) !=' ') { 
            cmd += line.charAt(pos++) ;
          }
          if (cmd=="local") {
            local = true ;
            ticker.attach_ms(100, execTicker) ; // 割り込み間隔と割り込み処理を設定。
            strcpy(local_val,"checked") ;
            strcpy(remote_val,"") ;
          } else {
            local = false ;
            localen = false ;
            ticker.detach() ;    
            strcpy(local_val,"") ;
            strcpy(remote_val,"checked") ;
          }
        }
        if ((pos= line.indexOf("GET /?pol")) != -1) {
          xhr=1;
        }
        if ((pos= line.indexOf("GET /?slid")) != -1) {
          pos += 11 ;
          while((line.charAt(pos) >='0') & (line.charAt(pos) <='9')) { 
            cmd += line.charAt(pos++) ;
          }
          val = cmd.toInt() ;
          if (val>256) val = 255 ;
          led_brightness = (byte)val ;
          xhr=1;
        }
        if ((pos= line.indexOf("GET /?led_v")) != -1) {
          pos += 12 ;
          while((line.charAt(pos) >='0') & (line.charAt(pos) <='9')) { 
            cmd += line.charAt(pos++) ;
          }
          val = cmd.toInt() ;
          if (val>256) val = 255 ;
          led_brightness = (byte)val ;
        }
        if ((pos=line.indexOf("GET /?on")) != -1) {                 // Client request was "GET /?on" 
          led_brightness += 1 ;
        }
        if ((pos=line.indexOf("GET /?off")) != -1) {                // Client request was "GET /?off"
          led_brightness = 0 ;
        }
        ledcWrite(0, 8191*led_brightness/255) ;                  // set PWM value to channel#0

        if (line.length() == 1 && line[0] == '\r'){           // end of HTTP request
          if (xhr == 0) {
            htmlwk = html_1 ;
            htmlwk.replace("$led_brightness",String(led_brightness)) ;
            Serial.print("radio_local = ");
            Serial.println(local);
            Serial.print("brightness  = ");
            Serial.println(led_brightness);
            htmlwk.replace("$checked_lo",local_val) ;
            htmlwk.replace("$checked_rm",remote_val) ;
            send_html(client,htmlwk) ;                             // send response to client
          } else {
            respwk = resp_1 ;
            respwk.replace("$led_brightness",String(led_brightness)) ;
            send_html(client,respwk) ;                             // send response to client
            # ifdef DEBUG
                Serial.print("xhr value :"); Serial.println(led_brightness);
            #endif
          }
          break;                                              // break while loop
        }
      }
    }
    delay(1);                                        // give the web browser time to receive the data
    // close the connection:
    client.stop();
    //
    # ifdef DEBUG
        Serial.println("Client Disconnected.");
        Serial.println("--------------------------------------------------");
    #endif
  }
}

// ------------------------------------------------------------------

void send_html(WiFiClient client, String html ) {
    client.println("HTTP/1.1 200 OK");
    client.println("Content-type:text/html");
    client.println();

    client.print(html) ;

    # ifdef DEBUG
        Serial.println( " --- send html --- ");
    #endif
}

void execTicker() {
  ticker_val = true ;  // フラグを True にする。
}

void do_JOB() {
  // ... 実行したい処理 ...
  vol_value  = analogRead(A4);

  if (localen == true) {
    led_brightness = (byte) ((vol_value*255)/4095) ;
    ledcWrite(0, 8191*led_brightness/255) ;                  // set PWM value to channel#0
  } else  if (vol_value == 0)
    localen = true ;
        
  loopcnt++ ;
  if (loopcnt ==10) {
    Serial.println("") ;
    Serial.print( "A4 :") ; Serial.println(vol_value) ;
    loopcnt = 0;
  }
  ticker_val = false ;    // 処理を実行したら、フラグを false にする。
}

<!DOCTYPE html><html lang='ja'><head><meta charset='UTF-8'>
<style>
       #base          {font-size:16pt;text-align:center;width:300px;border:solid 4px #93ff93; }
       #radio_box     {font-size:12pt;float:left ;text-align:left; width:45%; }
       #disp_box      {font-size:12pt;float:right;text-align:left; width:50%; }
       #brightness    {font-size:12pt;text-align:right; }
       #val_box       {font-size:12pt;text-align:center; clear:both ;}
       #ctl_box       {text-align:center; }
       input.radio    {margin-left:8px; width:30px;}
       input.value    {margin-left:8px; width:30px;}
       input.setbutton{margin-left:8px; width:40px;}
       input.slider   {margin-left:8px; width:250px;}
       input.button   {margin:0px 15px; width:100px;}
       </style>

<title>Color LED Controller</title></head>

<body>
<div id="base">
  <p>LED ON/OFF</p>
  <div id="radio_box">
    <form method="get"> 
      <input class='radio' type='radio' name='remote' id="rad_lo" value='local' $checked_lo onclick='disp_ctrl(this.value); submit(this.value)'>local<br>
      <input class='radio' type='radio' name='remote' id="rad_rm" value='remote' $checked_rm onclick='disp_ctrl(this.value); submit(this.value)'>remote<br>
    </form>
  </div>
  <div id="disp_box">
      <span> brightness value</span><br>
      <div id="brightness"><output id="o1">$led_brightness</output></div>
  </div>
  <div id="val_box">
    <form method="get">
      <span style="font-size:10pt;"> LED brightness (0-255)</span> 
      <input class='value'  type='text' name='led_v' value=$led_brightness id='led_v' disabled>
      <input class='setbutton' type='submit' name='set' id='set' value='SET' disabled>
    </form> 
    <form method='get'> 
      <input class="slider" type="range" name='led_s' id='led_s' value=$led_brightness min="0" max="255" step="1" disabled
        onchange="setval(this.value);" oninput="setval(this.value)"; onmouseup="submit(this.form)": ontouchend="submit(this.form)">
    </form> 
  </div>
  <div id="ctl_box">
    <form method='get'>
      <input class='button' type='submit' name='on' id="on" value='ON' disabled >
      <input class='button' type='submit' name='off' id="off" value='OFF' disabled><br>
    </form>
  </div>
</div>


<script>
var polling = null ;

function setval(ledval){
 var xhr = new XMLHttpRequest();
        xhr.open("get", "?slid="+ledval );
        xhr.timeout = 2000 ;
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT');
        xhr.responseType = 'document' ;

        xhr.onreadystatechange = function() {
          if( (xhr.readyState == 4) && (xhr.status == 200) ) {
            document.getElementById('led_v').value = xhr.response.getElementById("output1").innerHTML;
            document.getElementById('o1').innerHTML = xhr.response.getElementById("output1").innerHTML;
          }
        }

        xhr.ontimeout = function(e) {
          xhr.abort() ;
        }
        xhr.send();
}


function getval(){
 var xhrget = new XMLHttpRequest();
        xhrget.open("get", "?pol" );
        xhrget.setRequestHeader('Cache-Control', 'no-cache');
        xhrget.setRequestHeader('If-Modified-Since', 'Thu, 01 Jun 1970 00:00:00 GMT');
        xhrget.responseType = 'document' ;

        xhrget.onreadystatechange = function() {
          if( (xhrget.readyState == 4) && (xhrget.status == 200) ) {
            document.getElementById('o1').innerHTML = xhrget.response.getElementById("output1").innerHTML;
          }
        }

        ntimeout = function(e) {
          xhrget.abort() ;
        }
        xhrget.send();
}

function disp_ctrl( radioid ) {
   if(radioid == 'remote') {
      document.getElementById('led_v').disabled = false;
      document.getElementById('set').disabled = false;
      document.getElementById('led_s').disabled = false;
      document.getElementById('on').disabled = false;
      document.getElementById('off').disabled = false;
      clearInterval(polling);
   } else {
      document.getElementById('led_v').disabled = true;
      document.getElementById('set').disabled = true;
      document.getElementById('led_s').disabled = true;
      document.getElementById('on').disabled = true;
      document.getElementById('off').disabled = true;
      polling = setInterval(getval,100) ;
   }

}

window.onload = function() {
    if(document.getElementById("rad_rm").checked) {
      document.getElementById('led_v').disabled = false;
      document.getElementById('set').disabled = false;
      document.getElementById('led_s').disabled = false;
      document.getElementById('on').disabled = false;
      document.getElementById('off').disabled = false;
      clearInterval(polling);
    } else if(document.getElementById("rad_lo").checked) {
      document.getElementById('led_v').disabled = true;
      document.getElementById('set').disabled = true;
      document.getElementById('led_s').disabled = true;
      document.getElementById('on').disabled = true;
      document.getElementById('off').disabled = true;
      polling = setInterval(getval,100) ;
    }
}

</script>

</body>
</html>

  <!DOCTYPE html><html lang='ja'>
  <head> <title>Color LED Controller</title></head>
  <html> <body>
    <output id='output1'>$led_brightness</output>
  </body> </html>

2 件のコメント:

  1. これのコピペで勉強中です。
    少し質問ですが、ローカルVRに戻った時に入力が受付しません。
    はじめは、VR抵抗値が高すぎるor接触で考えていましたが。

    122行local = true ;の後にlocalen = true ;が必要では?
    do_job処理は、入っているような? その後ifで蹴られているような?

    すみません素人が、余分な指摘かも です。

    返信削除
    返信
    1. ローカルにした時、ボリュームを '0' に戻さないとボリュームの値を反映しないようにしています。
      vol_value ==0 で localen=true にしています。 (223,224行目)、

      削除