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



スケッチ
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
/*
 *    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 にする。
}

HTML本体
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<!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>

1
2
3
4
5
<!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行目)、

      削除