Breaking News

아두이노 메가 + ESP8266 ESP-12E UART WIFI SHIELD

아두이노 메가

+

ESP8266 ESP-12E UART WIFI SHIELD


아두이노 메가를 데이터로거 수집용으로 사용하고 ESP8266 와이파이 쉴드를 와이파이 IOT서버로 데이터 송신하는 기능을 합니다.
아두이노 메가
ESP8266 ESP-12E UART WIFI SHIELD
와이파이 쉴드 0(RX), 1(TX) 핀과 아두이노 메가 TX3, RX3(하드웨어 시리얼) 와 연결합니다.
회로구성

와이파이 쉴드 + 아두이노 메가

와이파이 쉴드 + 아두이노 메가

ESP 와이파이 쉴드 - 보드 설정 NodeMCU 1.0으로 합니다.

딥스위치를 이용하여 업로드 / 실행모드를 설정해야 해서 좀 불편합니다.
실행모드 설정

펌웨어 업로드 가능모드 설정


ESP 와이파이 쉴드 소스코드입니다.
내용 :
구글로부터 시간정보 가져오기
Thingspeak.com으로 데이터 로거 송신


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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <Ethernet.h>
#include <TimeLib.h>
//const char* ssid     = "RION_WIFI";
//const char* password = "zzzzzzzz";
char ssid[32= { 0x00, };
char password[32= { 0x00, };
boolean bLogInInit = false;  
const char * host = "api.thingspeak.com";
 WiFiClient client;
int reset_timeout = 0;
int time_timeout = 5000;
const char *months[] = {
  "Jan""Feb""Mar""Apr""May""Jun""Jul""Aug""Sep""Oct""Nov""Dec"
};
String getTime() {
  while (!client.connect("google.com"80)) {}
  client.print("HEAD / HTTP/1.1\r\n\r\n");
  while(!client.available()) {}
  
  while(client.available()){
    if (client.read() == '\n') {    
      if (client.read() == 'D') {    
        if (client.read() == 'a') {    
          if (client.read() == 't') {    
            if (client.read() == 'e') {    
              if (client.read() == ':') {    
                client.read();
                // Sun, 06 May 2018 17:53:35 GMT
                // String 
                String timeData = client.readStringUntil('\r');
                
                time_t t;
                tmElements_t tm;
//              tm.Year = CalendarYrToTm(y);
                tm.Year = CalendarYrToTm(timeData.substring(12,16).toInt());
                Serial.println(timeData.substring(12,16));
                tm.Month = 0;
                for(int i = 0; i < 12; i++)
                {
                    if(true == timeData.substring(811).equals(months[i]))
                    {
                        tm.Month = i + 1;
                        Serial.println(tm.Month);
                        break;
                    }
                }
                
                
                tm.Day = timeData.substring(5,7).toInt();
                Serial.println(tm.Day);
                tm.Hour = timeData.substring(17,19).toInt();
                Serial.println(tm.Hour);
                tm.Minute = timeData.substring(20,22).toInt();
                Serial.println(tm.Minute);
                tm.Second = timeData.substring(23,25).toInt();
                Serial.println(tm.Second);
                t = makeTime(tm);
                
                //use the time_t value to ensure correct weekday is set
                setTime(t);                
                adjustTime(9*60*60);
                
                    Serial.print("TIME:");
                    char data[64= { 0x00, };                    
                  sprintf(data, "%d.%02d.%02d %02d:%02d:%02d",
                    year(), month(), day(),
                    hour(), minute(), second()
                    );
              
      
                  Serial.println(data);
              
                client.stop();
                return timeData;
              }
            }
          }
        }
      }
    }
  }
}
char* string2char(String command){
    if(command.length()!=0){
        char *= const_cast<char*>(command.c_str());
        return p;
    }
}
void tryLogIn()
{
//    if(bLogInInit == true) return;
    if(ssid[0== 0x00) return;
//    if(password == "") return;
    
//   WiFi.disconnect(); // Disconnect AP
   WiFi.mode(WIFI_STA);
   Serial.println("tryLogIn...");   
   Serial.println(ssid);   
   Serial.println(password);   
   
   WiFi.begin(ssid, password); // Connect to WIFI network
   
//  WiFi.begin("RION_WIFI", "zzzzzzzz");
  // Wait for connection
  int timeout = 0;
   while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.println(".");
      timeout += 1;
      if(20 < timeout) break;
   }
   if(timeout <= 20) {
   
       Serial.print("Connected to ");
       Serial.println(ssid);
       Serial.print("IP address: ");
       Serial.println(WiFi.localIP());   
       Serial.println(getTime());    
       bLogInInit = true;
   }
}
void setup() {
    
   Serial.begin(115200);
    //tryLogIn();
    /*
   WiFi.disconnect(); // Disconnect AP
   WiFi.mode(WIFI_STA);  
   WiFi.begin(ssid, password); // Connect to WIFI network
  // Wait for connection
   while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.println(".");
   }
   
   Serial.print("Connected to ");
   Serial.println(ssid);
   Serial.print("IP address: ");
   Serial.println(WiFi.localIP());   
   Serial.println(getTime());
   */
}
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0-1};
  int maxIndex = data.length()-1;
  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0= strIndex[1]+1;
        strIndex[1= (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
char buffer [256];
boolean ready = false;
int cnt = 0;
void RecvLine()
{
    int len = strlen(buffer);
    // Serial.print(strlen(buffer));
    // Serial.print(":");
    // Serial.println(buffer);    
    // CMD:STT: // start
    // if (client2.connect(thingSpeakAddress, 80))
    // CMD:CON:thingSpeakAddress,80
    // CMD:STP:
    // CMD:PRN:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    // RST:OK
    // RST:DIS
    // RST:DAT:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
     if(6 <= len && memcmp(buffer, "SSID"4== 0)
     {
         int len = strlen(buffer+5)-2// \r\n exclude
        Serial.print("ssid len=");
        Serial.println(len);
         memcpy(ssid, buffer+5, len);
     }
     else
     if(6 <= len && memcmp(buffer, "PASS"4== 0)
     {
         int len = strlen(buffer+5)-2// \r\n exclude
        Serial.print("pass len=");
        Serial.println(len);
         memcpy(password, buffer+5, len);
        tryLogIn();
     }
    /*
    if(8 <= len && memcmp(buffer, "CMD:CON:"8== 0)
    {
      // String str = String(buffer);
      Serial.println("#CMD: connect");
     }
    else
    if(7 <= len && memcmp(buffer, "CMD:STP:"7== 0)
    {
      Serial.println("#CMD: stop");
      // client.stop();
    }
    else 
    */
    {
      // Serial.println(buffer);
      if(bLogInInit == false) return ;
        const int httpPort = 80;
        if (!client.connect(host, httpPort)) {
            Serial.println("#RST:FAIL");     
            reset_timeout += 1;
        } 
        else {
            reset_timeout = 0;
            
//            Serial.println("#RST:OK");  
            String key = "";
            String url= "https://api.thingspeak.com/update?api_key="// 4Z9HH5SCR8D62ZBA&field1=0&field2=0";
//            String tsData = "field1=15.57&field2=14.34&field3=9.47&field4=6.92&field5=4.92&field6=4.85&field7=9.87&field8=11.63";
            
            String str = String(buffer);
            key = getValue(str, ','0);
            url += key;
            url += "&";
            url += getValue(str, ','1);
            
//               Serial.print("url=");
//            Serial.println(url);
            
            client.print(String("GET "+ url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
/*
            unsigned long timeout = millis();
            while (client.available() == 0) {
              if (millis() - timeout > 5000) {
                Serial.println(">>> Client Timeout !");
                client.stop();
                reset_timeout += 1;
                return;
              }
            } */
          
            // Read all the lines of the reply from server and print them to Serial
            while (0 < client.available()) {
              String line = client.readStringUntil('\r');
              if(line.substring(05== "Date:")
              {
                Serial.print(line);
              }
            }
          
            // Serial.println("closing connection");    
                  Serial.print("TIME:");
                    char data[64= { 0x00, };                    
                  sprintf(data, "%d.%02d.%02d %02d:%02d:%02d",
                    year(), month(), day(),
                    hour(), minute(), second()
                    );
              
                  Serial.println(data);
                  
            client.stop();
        }      
    }
    
}
void loop() {
    if (ready)
    {
        RecvLine();
        ready = false;
    } 
    
    while(0 < Serial.available())
    {
        char c = Serial.read();
        buffer[cnt] = c;
        if ((c == '\n'|| (sizeof(buffer)-1 <= cnt))
        {
            cnt += 1;
            buffer[cnt] = '\0';
            cnt = 0;
            ready = true;
            break;
        }
        else {
          cnt += 1;
        }
    }  
    if(10 < reset_timeout)
    {
      Serial.println("RESET!");
      software_Reset();
    }
    delay(10); // 
    /*
    time_timeout += 1;
    if(100 * 10 < time_timeout) // 1 min
    {
      time_timeout = 0;
      if(bLogInInit == false)
      {
          tryLogIn();
      }
      
    }
    */
    
}
#define RST 4
void software_Reset  () {
  WiFi.forceSleepBegin(); wdt_reset(); ESP.restart(); 
  while(1) wdt_reset();
}
cs

아두이노 메가 보드 사진 입니다.
LCD Display 연결 / 온도 센서 / SD File 저장


아두이노 메가 소스코드
내용 :
데이터 로거 수집
온도센서 / 태양광 / CO2 /
SD File 데이터 저장

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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
#include <SD.h>
// #include <SdFat.h>
#include <SPI.h>
//#include <Ethernet.h>
//#include <DS1302RTC.h>
#include <TimeLib.h>
//#include <utility/w5100.h>
// Set pins:  CE(reset), IO(DAT), CLK
// DS1302RTC RTC(27, 29, 31);
// Optional connection for RTC module
//#define DS1302_GND_PIN 33
//#define DS1302_VCC_PIN 35
///////////////////////////////////////////////////////////
char * ssid     = "RION_WIFI";
char * password = "zzzzzzzz";
boolean bLoingOK = false;
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey1 = "4Z9HH5SCR8D62ZBA"
String writeAPIKey2 = "Z4YBOPVSUUVWXH2D"
String writeAPIKey3 = "73529SGXZF9ILXCX"
const int updateThingSpeakInterval = 5 * 1000;      // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)
///////////////////////////////////////////////////////////
#include <TinyGPS.h>
#define BYTE 1
// GPS parser for 406a
//#define BUFFSIZ 90 // plenty big
//char buffer[BUFFSIZ];
//char *parseptr;
//char buffidx;
uint8_t _hour, _minute, _second, _year, _month, _day;
// uint32_t latitude, longitude;
// uint8_t groundspeed, trackangle;
//char latdir, longdir;
// char status;
TinyGPS gps;
float latitude, longitude;
///////////////////////////////////////////////////////////
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F204);
void printLCD(int col, int row , unsigned long value) {
    char str[21= { 0x00, };
    sprintf(str, "%lu", value);
    
    for(int i=0 ; i < strlen(str) ; i++){
      lcd.setCursor(col+i , row);
      lcd.print(str[i]);
    }
}
void printLCD(int col, int row , char *str) {
    for(int i=0 ; i < strlen(str) ; i++){
      lcd.setCursor(col+i , row);
      lcd.print(str[i]);
    }
}
void printLCD_M(int col, int row , char * str) { // MIDDLE
    int i = 0;
    i = (20-col-strlen(str)) / 2;
    int j = 0;
    for( ; j < strlen(str) ; j++){
      lcd.setCursor(col+i+j , row);
      lcd.print(str[j]);
    }
}
#define SOLAR_1 A0
#define SOLAR_2 A1
///////////////////////////////////////////////////////////
#include "thermistor.h"
#include "HardwareSerial.h"
#define NTC_PIN               A2
// Thermistor object �µ� ���� ����
THERMISTOR thermistor(NTC_PIN,        // Analog pin
                      10000,          // Nominal resistance at 25 ºC
                      3950,           // thermistor's beta coefficient
                      10000);         // Value of the series resistor
THERMISTOR thermistor_2(A3, 10000395010000);
THERMISTOR thermistor_3(A4, 10000395010000);
THERMISTOR thermistor_4(A5, 10000395010000);
THERMISTOR thermistor_5(A6, 10000395010000);
THERMISTOR thermistor_6(A7, 10000395010000);
THERMISTOR thermistor_7(A8, 10000395010000);
THERMISTOR thermistor_8(A9, 10000395010000);
THERMISTOR thermistor_9(A10, 10000395010000);
THERMISTOR thermistor_10(A11, 10000395010000);
THERMISTOR thermistor_11(A12, 10000395010000);
THERMISTOR thermistor_12(A13, 10000395010000);
THERMISTOR thermistor_13(A14, 10000395010000);
THERMISTOR thermistor_14(A15, 10000395010000);
////////////////////////////////////////////////////////////////
#define GPSBAUD 9600
////////////////////////////////////////////////////////////////
int failedCounter = 0;
long lastConnectionTime = 0
boolean lastConnected = false;
long lastConnectionTime2 = 0
boolean lastConnected2 = false;
long lastConnectionTime3 = 0
boolean lastConnected3 = false;
void startEthernet()
{
  
}
int ackTimeout = 0;
void updateThingSpeak(String key, String tsData)
{
  // Serial3.println("CMD:STP");
  // delay(100);
  Serial3.print(key);
  Serial3.print(",");
  Serial3.println(tsData);
  Serial.print("ackTimeout=");
    Serial.println(ackTimeout);
  ackTimeout += 1;
  if(10 < ackTimeout) {
      bLoingOK = false// retry LOGIN
  }
}
////////////////////////////////////////////////////////////////
// int chipSelect = 4; // uno
int chipSelect = 53// mega
void setup(void)
{
  Serial.begin(115200);
  Serial3.begin (115200); 
  
    Serial1.begin(GPSBAUD);
    Serial1.setTimeout(10);
    
    pinMode(10OUTPUT);
    gps = TinyGPS();
    // uart_gps.begin(GPSBAUD);
  // Activate RTC module
//  digitalWrite(DS1302_GND_PIN, LOW);
//  pinMode(DS1302_GND_PIN, OUTPUT);
//  digitalWrite(DS1302_VCC_PIN, HIGH);
//  pinMode(DS1302_VCC_PIN, OUTPUT);  
//  Serial.println("RTC module activated");
//  delay(500);
  
  
//  if (RTC.haltRTC()) {
//    Serial.println("The DS1302 is stopped.  Please set time");
//    Serial.println("to initialize the time and begin running.");
//    Serial.println();
//  }
//  if (!RTC.writeEN()) {
//    Serial.println("The DS1302 is write protected. This normal.");
//    Serial.println();
//  }
  
    digitalWrite(10,HIGH);
  // SD ī�� �ʱ�ȭ
  if(SD.begin(chipSelect) == 0// SS for SD card
  {
    Serial.println(F("SD init fail"));          
  }
  else {
    Serial.println(F("SD init OK"));          
  } 
  
      lcd.begin(); 
      lcd.backlight();
    
        printLCD(00"FARM1ST DATA LOGGER 2-1");
        printLCD(01"made by ZEROWIN");    
            printLCD(02"2018.4.4");    
        delay(2000);
        lcd.clear();
        lcd.noCursor();     
    
  // setSyncProvider() causes the Time library to synchronize with the
  //external RTC by calling RTC.get() every five minutes by default.
//  setSyncProvider(RTC.get);
//  Serial.println("RTC Sync");
//  if (timeStatus() == timeSet)
//    Serial.println(" Ok!");
//  else
//    Serial.println(" FAIL!");
  // Serial.println();
  
//    W5100.setRetransmissionCount(2);
}
// 10�ʵ��� ������ ��� -> �Ѳ����� SD ���� ����
#define MAX_NUM 10
int fileWrite_timeout = 0;
int timeout = 0;
time_t t_backup[MAX_NUM];
float voltage_backup[MAX_NUM];
float voltage2_backup[MAX_NUM];
float temperature_backup_01[MAX_NUM];
float temperature_backup_02[MAX_NUM];
float temperature_backup_03[MAX_NUM];
float temperature_backup_04[MAX_NUM];
float temperature_backup_05[MAX_NUM];
float temperature_backup_06[MAX_NUM];
float temperature_backup_07[MAX_NUM];
float temperature_backup_08[MAX_NUM];
float temperature_backup_09[MAX_NUM];
float temperature_backup_10[MAX_NUM];
float temperature_backup_11[MAX_NUM];
float temperature_backup_12[MAX_NUM];
float temperature_backup_13[MAX_NUM];
float temperature_backup_14[MAX_NUM];
// after your rtc is set up and working you code just needs:
/*
void dateTime(uint16_t* date, uint16_t* time) {
  time_t t = now();
  // return date using FAT_day macro to format fields
  *date = FAT_day(year(t), month(t), day(t));
  // return time using FAT_TIME macro to format fields
  *time = FAT_TIME(hour(t), minute(t), second(t));
}
*/
void software_Reset() // Restarts program from beginning but does not reset the peripherals and registers
{
    asm volatile ("  jmp 0");  
void readSerail3Data()
{
    String str3 = "";
    while(0 < Serial3.available())
    {
        char ch = Serial3.read();
        str3 += ch;
    }
    if(0 < str3.length()) {
        
        Serial.println(str3);
        if(str3.substring(04).equals("TIME"== true)
        {
                bLoingOK = true;
                ackTimeout = 0;
                
//            TIME:2018.05.07 03:56:50
                time_t t;
                tmElements_t tm;
//              tm.Year = CalendarYrToTm(y);
                tm.Year = CalendarYrToTm(str3.substring(5,9).toInt());
//                Serial.println(tm.Year);
                tm.Month = str3.substring(10,12).toInt();
//                Serial.println(tm.Month);
                tm.Day = str3.substring(13,15).toInt();
//                Serial.println(tm.Day);
                tm.Hour = str3.substring(16,18).toInt();
//                Serial.println(tm.Hour);
                tm.Minute = str3.substring(19,21).toInt();
//                Serial.println(tm.Minute);
                tm.Second = str3.substring(22,23).toInt();
//                Serial.println(tm.Second);
                t = makeTime(tm);        
                setTime(t);                
//                adjustTime(9*60*60); already done at wifi shield
                
        }
    }    
}
void loop(void)
{
    static time_t tLast;
    time_t t;
    tmElements_t tm;
    char data[256= { 0x00, };
         // ��¥ ���� ��� -> �ø��� ����Ϳ��� 2018,02,16,19,54,33 �Է�
    //check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
    /*
    if (Serial.available() >= 12) {
        //note that the tmElements_t Year member is an offset from 1970,
        //but the RTC wants the last two digits of the calendar year.
        //use the convenience macros from Time.h to do the conversions.
        int y = Serial.parseInt();
        
        if (y >= 100 && y < 1000)
            Serial.println("Error: Year must be two digits or four digits!");
            
        else {
            if (y >= 1000)
                tm.Year = CalendarYrToTm(y);
            else    //(y < 100)
                tm.Year = y2kYearToTm(y);
            tm.Month = Serial.parseInt();
            tm.Day = Serial.parseInt();
            tm.Hour = Serial.parseInt();
            tm.Minute = Serial.parseInt();
            tm.Second = Serial.parseInt();
            t = makeTime(tm);
            
      //use the time_t value to ensure correct weekday is set
            if(RTC.set(t) == 0) { // Success
            
              setTime(t);
              Serial.print("RTC set to: ");
              sprintf(data, "%d.%02d.%02d %02d:%02d:%02d",
                year(t), month(t), day(t),
                hour(t), minute(t), second(t)
                );
              printLCD(00, data);
      
              Serial.println(data);
      }
      else
        Serial.println();
        
        Serial.println("RTC set failed!");
  
        //dump any extraneous input
        while (Serial.available() > 0Serial.read();
        }
    }
    */
    
    // 1�ʸ��� ������ ����
    t = now();
    if (t != tLast) {
        tLast = t;
        // TODO: �µ�, �¾籤 �������б� 
      
        
        float voltage = float(analogRead(SOLAR_1)/1023.0 * 5.0);
        float voltage2 = float(analogRead(SOLAR_2)/1023.0 * 5.0);
        float temperature = thermistor.read();   // Read temperature
        float temperature_2 = thermistor_2.read();   // Read temperature
        float temperature_3 = thermistor_3.read();   // Read temperature
        float temperature_4 = thermistor_4.read();
        float temperature_5 = thermistor_5.read();
        float temperature_6 = thermistor_6.read();
        float temperature_7 = thermistor_7.read();
        float temperature_8 = thermistor_8.read();
        float temperature_9 = thermistor_9.read();
        float temperature_10 = thermistor_10.read();
        float temperature_11 = thermistor_11.read();
        float temperature_12 = thermistor_12.read();
        float temperature_13 = thermistor_13.read();
        float temperature_14 = thermistor_14.read();
        float weight = 24;
        float co2 = 24;
        t_backup[fileWrite_timeout] = t;
        voltage_backup[fileWrite_timeout] = voltage;
        voltage2_backup[fileWrite_timeout] = voltage2;
        temperature_backup_01[fileWrite_timeout] = temperature;
        temperature_backup_02[fileWrite_timeout] = temperature_2;
        temperature_backup_03[fileWrite_timeout] = temperature_3;     
        temperature_backup_04[fileWrite_timeout] = temperature_4;     
        temperature_backup_05[fileWrite_timeout] = temperature_5;     
        temperature_backup_06[fileWrite_timeout] = temperature_6;     
        temperature_backup_07[fileWrite_timeout] = temperature_7;     
        temperature_backup_08[fileWrite_timeout] = temperature_8;     
        temperature_backup_09[fileWrite_timeout] = temperature_9;     
        temperature_backup_10[fileWrite_timeout] = temperature_10;     
        temperature_backup_11[fileWrite_timeout] = temperature_11;     
        temperature_backup_12[fileWrite_timeout] = temperature_12;     
        temperature_backup_13[fileWrite_timeout] = temperature_13;     
        temperature_backup_14[fileWrite_timeout] = temperature_14;     
        fileWrite_timeout += 1;
        Serial.println(fileWrite_timeout);
        if(latitude != 0 && longitude != 0)
        {
            tm.Year = _year+30;
            tm.Month = _month;
            tm.Day = _day;
            tm.Hour = _hour;
            tm.Minute = _minute;
            tm.Second = _second;
            t = makeTime(tm);
            setTime(t);
            adjustTime(9*60*60);
        }
    
        
        sprintf(data, "%d.%02d.%02d %02d:%02d:%02d",
            year(), month(), day(), hour(), minute(), second());
//                year(t), month(t), day(t),
//                hour(t), minute(t), second(t));
//          _year, _month, _day,
//          _hour, _minute, _second);
        printLCD(00, data);
        if(fileWrite_timeout < 3) {
                sprintf(data, "SOLAR#1 %02d.%02d       ",
                  (int)voltage, (int)(voltage * 100) % 100);
                printLCD(01, data);       
                memset(data, ' '20);
                sprintf(data, "SOLAR#2 %02d.%02d       ",
                  (int)voltage2, (int)(voltage2 * 100) % 100);
                printLCD(02, data);
        }
        else
        if(fileWrite_timeout < 6) {
                memset(data, ' '20);
                printLCD(01, data);        
                sprintf(data, "TEMP %02d %02d",
                  (int)temperature, 
                  (int)temperature_2);
                printLCD(01, data);       
        //        Serial.println(data);
              sprintf(data, "%02d %02d %02d %02d %02d %02d %02d",
                  (int)temperature_3,
                  (int)temperature_4,
                  (int)temperature_5,
                  (int)temperature_6,
                  (int)temperature_7,
                  (int)temperature_8,
                  (int)temperature_9
                  );
                printLCD(02, data);       
        //        Serial.println(data);
                
                sprintf(data, "%02d %02d %02d %02d %02d",  
                  (int)temperature_10,
                  (int)temperature_11,
                  (int)temperature_12,
                  (int)temperature_13,
                  (int)temperature_14
                  );
            
                printLCD(03, data);       
        //        Serial.println(data);
        }
        else {
                sprintf(data, "latitude   %2d.%05d ",
                  (int)latitude, (int)(latitude* 100000) % 100000);
                printLCD(01, data);      
                
                
                sprintf(data, "longitude %3d.%05d ",
                  (int)longitude, (int)(longitude * 100000) % 100000);
                printLCD(02, data);      
                memset(data, ' '20);
                printLCD(03, data);  
        }
        if(MAX_NUM <= fileWrite_timeout) 
        {   
            if(bLoingOK == false)
            {
                Serial.println("Try Login...");
                
//                char temp[64] = { 0x00, };
//                sprintf(temp, "LOGIN:%s;%s", ssid, password);
                Serial3.print("SSID:");
                Serial3.println(ssid);
                Serial3.print("PASS:");
                Serial3.println(password);
            }              
        
            fileWrite_timeout = 0;       
            timeout += 1;
          {
//            Serial.println("...disconnected");
//            Serial.println();
            
//            Serial3.println("CMD:STP");
//              delay(1000);
          }
          //if(timeout % 3 == 0)
          // Update ThingSpeak
          {
            String temp1 = "field1=";
            temp1 += String((int)temperature, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature*100)%100, DEC);
            temp1 += "&field2=";
            temp1 += String((int)temperature_2, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_2*100)%100, DEC);
            temp1 += "&field3=";
            temp1 += String((int)temperature_3, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_3*100)%100, DEC);
            temp1 += "&field4=";
            temp1 += String((int)temperature_4, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_4*100)%100, DEC);
            temp1 += "&field5=";
            temp1 += String((int)temperature_5, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_5*100)%100, DEC);
            temp1 += "&field6=";
            temp1 += String((int)temperature_6, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_6*100)%100, DEC);
            temp1 += "&field7=";
            temp1 += String((int)temperature_7, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_7*100)%100, DEC);
            temp1 += "&field8=";
            temp1 += String((int)temperature_8, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_8*100)%100, DEC);
            
            updateThingSpeak(writeAPIKey1, temp1);
            delay(1000);
            readSerail3Data();
          }
          {
            String temp1 = "field1=";
            temp1 += String((int)temperature_9, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_9*100)%100, DEC);
            temp1 += "&field2=";
            temp1 += String((int)temperature_10, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_10*100)%100, DEC);
            temp1 += "&field3=";
            temp1 += String((int)temperature_11, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_11*100)%100, DEC);
            temp1 += "&field4=";
            temp1 += String((int)temperature_12, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_12*100)%100, DEC);
            temp1 += "&field5=";
            temp1 += String((int)temperature_13, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_13*100)%100, DEC);
            temp1 += "&field6=";
            temp1 += String((int)temperature_14, DEC);
            temp1 += ".";
            temp1 += String((int)(temperature_14*100)%100, DEC);
//            temp1 += "&field7=";
//            temp1 += String((int)temperature_7, DEC);
//            temp1 += ".";
//            temp1 += String((int)(temperature_7*100)%100, DEC);
//            temp1 += "&field8=";
//            temp1 += String((int)temperature_8, DEC);
//            temp1 += ".";
//            temp1 += String((int)(temperature_8*100)%100, DEC);
            
            updateThingSpeak(writeAPIKey2, temp1);
            delay(1000);
            readSerail3Data();
          }
                    
          
          // Update ThingSpeak
          //if(timeout % 3 == 1)
          {
            String temp1 = "field1=";
            temp1 += String((int)weight, DEC);
            temp1 += ".";
            temp1 += String((int)(weight*100)%100, DEC);
            temp1 += "&field2=";
            temp1 += String((int)co2, DEC);
            temp1 += ".";
            temp1 += String((int)(co2*100)%100, DEC);
            temp1 += "&field3=";
            temp1 += String((int)voltage, DEC);
            temp1 += ".";
            temp1 += String((int)(voltage*100)%100, DEC);
            temp1 += "&field4=";
            temp1 += String((int)voltage2, DEC);
            temp1 += ".";
            temp1 += String((int)(voltage2*100)%100, DEC);
            temp1 += "&field5=";
            temp1 += String((float)latitude, 5);
//            temp1 += String((int)latitude, DEC);
//            temp1 += ".";
//            temp1 += String((int)(latitude*100000)%100000, DEC);
            temp1 += "&field6=";
            temp1 += String((float)longitude, 5);
//            temp1 += String((int)longitude, DEC);
//            temp1 += ".";
//            temp1 += String((int)(longitude*100000)%100000, DEC);
            updateThingSpeak(writeAPIKey3, temp1);
            delay(1000);
            readSerail3Data();
          }
          
          // Check if Arduino Ethernet needs to be restarted
          if (failedCounter > 3 ) {
//                  startEthernet();
                software_Reset();
            }
          /////////////////////////////////////////////////////////
/*
      sprintf(data, "TEMP %02d %02d %02d %02d %02d %02d %02d %02d %02d %02d",
          (int)temperature,
          (int)temperature_2,
          (int)temperature_3,
          (int)temperature_4,
          (int)temperature_5,
          (int)temperature_6,
          (int)temperature_7,
          (int)temperature_8,
          (int)temperature_9,
          (int)temperature_10
          );
    
        Serial.println(data);
        */
    // 10�ʸ��� ������ ����
    
        {   
    
            // fileWrite_timeout = 0;           
                // Serial.println(data);
                char filename[16= { 0x00, };
                sprintf(filename, "s_%02d%02d%02d.txt",  year(t)-2000, month(t), day(t));
            
                Serial.print("filename=");
                Serial.println(filename);
//                SdFile::dateTimeCallback(dateTime);
                File dataFile = SD.open(filename, FILE_WRITE);
              
                // if the file is available, write to it:
                if (dataFile) {
                  
                    for(int i = 0; i < MAX_NUM; i++) {
                    
                          sprintf(data, "%d.%02d.%02d %02d:%02d:%02d %02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%02d.%02d,%03d.%05d,%03d.%05d",
                            year(t_backup[i]), month(t_backup[i]), day(t_backup[i]),
                            hour(t_backup[i]), minute(t_backup[i]), second(t_backup[i]),
                            (int)voltage_backup[i], (int)(voltage_backup[i] * 100) % 100,
                            (int)voltage2_backup[i], (int)(voltage_backup[i] * 100) % 100,
                            (int)temperature_backup_01[i], (int)(temperature_backup_01[i] * 100) % 100,
                            (int)temperature_backup_02[i], (int)(temperature_backup_02[i] * 100) % 100,
                            (int)temperature_backup_03[i], (int)(temperature_backup_03[i] * 100) % 100,
                            (int)temperature_backup_04[i], (int)(temperature_backup_04[i] * 100) % 100,
                            (int)temperature_backup_05[i], (int)(temperature_backup_05[i] * 100) % 100,
                            (int)temperature_backup_06[i], (int)(temperature_backup_06[i] * 100) % 100,
                            (int)temperature_backup_07[i], (int)(temperature_backup_07[i] * 100) % 100,
                            (int)temperature_backup_08[i], (int)(temperature_backup_08[i] * 100) % 100,
                            (int)temperature_backup_09[i], (int)(temperature_backup_09[i] * 100) % 100,
                            (int)temperature_backup_10[i], (int)(temperature_backup_10[i] * 100) % 100,
                            (int)temperature_backup_11[i], (int)(temperature_backup_11[i] * 100) % 100,
                            (int)temperature_backup_12[i], (int)(temperature_backup_12[i] * 100) % 100,
                            (int)temperature_backup_13[i], (int)(temperature_backup_13[i] * 100) % 100,
                            (int)temperature_backup_14[i], (int)(temperature_backup_14[i] * 100) % 100,
                            (int)latitude, (int)(latitude * 100000) % 100000,
                            (int)longitude, (int)(longitude * 100000) % 100000
                            );
                        
                          dataFile.println(data);
                          
                          // print to the serial port too:
//                          Serial.print("DataLogger: ");
//                          Serial.println(data);
                    }
                    dataFile.close();
                }
                // if the file isn't open, pop up an error:
                else {
                  Serial.println("error opening datalog.txt");
                }  
            }
        }
    }
        // GPS
        /* JoyTest
        {
            // loop_gps();
            
            String temp = "";
            
          while(0 < Serial1.available())     // While there is data on the RX pin...
          {
                char c = Serial1.read();    // load the data into a variable...
                Serial.print(c);
              if(gps.encode(c))      // if there is a new valid sentence...
              {
                getgps(gps);         // then grab the data.
              }   
                
          }    
          if(0 < temp.length())
          {
              
  
          }
          
        }
        */
   delay(100);
}
// The getgps function will get and print the values we want.
void getgps(TinyGPS &gps)
{
  // To get all of the data into varialbes that you can use in your code, 
  // all you need to do is define variables and query the object for the 
  // data. To see the complete list of functions see keywords.txt file in 
  // the TinyGPS and NewSoftSerial libs.
  
  // Define the variables that will be used
  // float latitude, longitude;
  // Then call this function
  gps.f_get_position(&latitude, &longitude);
  // You can now print variables latitude and longitude
  Serial.print("Lat/Long: "); 
  Serial.print(latitude,5); 
  Serial.print(", "); 
  Serial.println(longitude,5);
  
  // Same goes for date and time
  int year;
  byte month, day, hour, minute, second, hundredths;
  gps.crack_datetime(&year,&month,&day,&hour,&minute,&second,&hundredths);
  // Print data and time
  Serial.print("Date: "); Serial.print(month, DEC); Serial.print("/"); 
  Serial.print(day, DEC); Serial.print("/"); Serial.print(year);
  Serial.print("  Time: "); Serial.print(hour, DEC); Serial.print(":"); 
  Serial.print(minute, DEC); Serial.print(":"); Serial.print(second, DEC); 
  Serial.print("."); Serial.println(hundredths, DEC);
  //Since month, day, hour, minute, second, and hundr
  _year = year-2000;
  _month = month;
  _day = day;
  _hour = hour;
  _minute = minute;
  _second = second;
  
  // Here you can print the altitude and course values directly since 
  // there is only one value for the function
  Serial.print("Altitude (meters): "); Serial.println(gps.f_altitude());  
  // Same goes for course
  Serial.print("Course (degrees): "); Serial.println(gps.f_course()); 
  // And same goes for speed
  Serial.print("Speed(kmph): "); Serial.println(gps.f_speed_kmph());
  Serial.println();
  
  // Here you can print statistics on the sentences.
  unsigned long chars;
  unsigned short sentences, failed_checksum;
  gps.stats(&chars, &sentences, &failed_checksum);
  //Serial.print("Failed Checksums: ");Serial.print(failed_checksum);
  //Serial.println(); Serial.println();
  // delay(10000);
}
cs


댓글 1개:

  1. 안녕하세요 지금 아두이노 메가보드 + wifi쉴드 + lcd키패드 쉴드 3개를 결합하려고 하는데
    쉴드의 핀 충돌의 문제인지 업로드 방식의 문제인지 lcd에 글자가 출력이 안되고있습니다...
    wifi쉴드와 메가보드는 게시글의 제품과 동일한 제품을 가지고 있습니다 ㅠㅠ 어떤식으로 연결해야하는지 팁좀 부탁드립니다 ...

    답글삭제