-
Notifications
You must be signed in to change notification settings - Fork 12
/
main10.c
1761 lines (1427 loc) · 81.3 KB
/
main10.c
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ----------------------------------------------------------------------------------------------
* real GPS car tracker on ATMEGA328P + SIM7000 module - version 2.0
* by Adam Loboda - [email protected]
* baudrate UART is 9600 as most stable using RC internal clock 1MHz (8MHz with division by 8)
* MCU clock is lowered to 1MHz to reduce power consumption
*
* SIM7000 default serial port speed is 115200 bps
* please configure SIM7000 to fixed 9600 first by AT+IPR=9600 command
* and disable echo by ATE0 command
* to ensure stability, and then save config via AT&W command
* this version is suitable for the SIM7000 boards that have DTR pin exposed, utilizes sleepmode on SIM7000
*
* connections to be made :
* SIM7000 RXD to ATMEGA328 TXD PIN #3,
* SIM7000 TXD to ATMEGA328 RXD PIN #2
* SIM7000 DTR/SLEEP to ATMEGA PC5 PIN #28
* VCC :
* ATMEGA328 VCC (PIN #7) must be connected to lower voltage VCC ~3.3V than 5V of SIM7000 board
* you may use 3x 1N4007 diodes in serial to drop voltage from 5V to ~3.3V
* GND :
* ATMEGA328 GND (PIN #8 and PIN #22) to SIM7000 GND and 0V
* other info :
* the prototype board was built using www.and-global.com BK-808 breadboard
* SIM7000 breadboard which is powered from 5V DC but uses 3.3V TTL logic on RXD/TXD
*
* this version has more accurate positioning from GPS module and SMS command support
* following commands :
* ACTIVATE : validates sending MSISDN as a voice caller
* SINGLE : gives single position result
* MULTI : gives 5 positions with 5 min intervals
* GUARD : enables GUARD MODE - notifies when GPS position changes over SMS
* HTTP : will send continously positions to your HTTP server using HTTP GET method with parameters : time,longtitude,latitude
* STOP : disables GUARD MODE or HTTP MODE if active
* ----------------------------------------------------------------------------------------------
*/
#include <inttypes.h>
#include <stdio.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <string.h>
#include <avr/power.h>
#include <avr/eeprom.h>
#define UART_NO_DATA 0x0100
// internal RC oscillator 8MHz with divison by 8 and U2X0 = 1, gives 0.2% error rate for 9600 bps UART speed
// and lower current consumption
// for 1MHz : -U lfuse:w:0x62:m on ATMEGA328P
#define F_CPU 1000000UL
// EEPROM address to store phonenumber for messages
#define EEADDR 0
#define BAUD 9600
// formula for 1MHz clock and U2X0 = 1 double UART speed
#define MYUBBR ((F_CPU / (BAUD * 8L)) - 1)
// SIM and GSM related commands
const char AT[] PROGMEM = { "AT\r" };
const char ISATECHO[] PROGMEM = { "AT" };
const char ISOK[] PROGMEM = { "OK" };
const char ISREG1[] PROGMEM = { "+CREG: 0,1" }; // SIM registered in HPLMN
const char ISREG2[] PROGMEM = { "+CREG: 0,5" }; // SIM registered in ROAMING NETWORK
const char SHOW_REGISTRATION[] PROGMEM = {"AT+CREG?\r"};
const char DISREGREPORT[] PROGMEM = {"AT+CREG=0\r"}; // disable reporting URC of losing 2G coverage by +CREG=0
const char PIN_IS_READY[] PROGMEM = {"+CPIN: READY"};
const char PIN_MUST_BE_ENTERED[] PROGMEM = {"+CPIN: SIM PIN"};
const char SHOW_PIN[] PROGMEM = {"AT+CPIN?\r"};
const char ECHO_OFF[] PROGMEM = {"ATE0\r"};
const char ENTER_PIN[] PROGMEM = {"AT+CPIN=\"1111\"\r"};
const char CFGRIPIN[] PROGMEM = {"AT+CFGRI=1\r"};
const char SMS1[] PROGMEM = {"AT+CMGF=1\r"}; // select txt format of SMS
const char SMS2[] PROGMEM = {"AT+CMGS=\""}; // begin of sending SMS in text format
const char DELSMS[] PROGMEM = {"AT+CMGD=4\r"}; // delete all stored SMS just in case
const char SHOWSMS[] PROGMEM = {"AT+CNMI=1,2,0,0,0\r"}; // display automatically SMS when arrives
const char ISSMS[] PROGMEM = {"CMT:"}; // beginning of mobile terminated SMS identification
// SMS commands to be interpreted
const char ISMULTI[] PROGMEM = {"MULTI"}; // MULTI option gives 5 continous measurements
const char ISSINGLE[] PROGMEM = {"SINGLE"}; // SINGLE option gives single measurement GPS or GSM
const char ISACTIVATE[] PROGMEM = {"ACTIVATE"}; // ACTIVATE activates sending number as allowed to call
const char ISGUARD[] PROGMEM = {"GUARD"}; // GUARD mode to automatically alert of GPS position change
const char ISSTOP[] PROGMEM = {"STOP"}; // STOP GUARD & HTTP mode
const char ISHTTP[] PROGMEM = {"HTTP"}; // HTTP mode activation to store data using HTTP GET with parameters
const char COMMANDACK[] PROGMEM = {"COMMAND ACCEPTED\n"}; // Acknowledge that the SMS command was accepted
const char COMMANDSINGLEACK[] PROGMEM = {"SINGLE MEASUREMENT IN PROGRESS... PLEASE WAIT 7-8 MINUTES BEFORE NEXT COMMAND\n"}; // Acknowledge that the SINGLE command was accepted
const char COMMANDMULTIACK[] PROGMEM = {"MULTIPLE MEASUREMENTS IN PROGRESS.. PLEASE WAIT 25 MINUTES BEFORE NEXT COMMAND\n"}; // Acknowledge that the MULTI command was accepted
const char ACTIVATED[] PROGMEM = {"ACTIVATED CALLS FROM "}; // Ack activated sending number as allowed to call
const char GUARD[] PROGMEM = {"GUARD MODE ACTIVATED.. PLEASE WAIT 5 MINUTES BEFORE NEXT COMMAND\n"}; // Confirmation of guard mode activated
const char HTTP[] PROGMEM = {"HTTP MODE ACTIVATED.. PLEASE WAIT 5 MINUTES BEFORE NEXT COMMAND\n"}; // Confirmation of HTTP mode activated
const char ALERT[] PROGMEM = {"ALERT, POSITION CHANGED TO : "}; // Alert, that guard detected position change
const char STOP[] PROGMEM = {"MODE STOPPED"}; // Guard & HTTP mode deactivated
const char CRLF[] PROGMEM = {"\"\n\r"};
// Flightmode ON OFF - for saving battery while in underground garage with no GSM signal
// tracker will check 2G network availability in 30 minutes intervals
// meanwhile radio will be switched off for power saving
const char FLIGHTON[] PROGMEM = { "AT+CFUN=4\r" };
const char FLIGHTOFF[] PROGMEM = { "AT+CFUN=1\r" };
// Sleepmode ON OFF - mode #1 requires DTR pin manipulation,
// to get out of SIM7000 sleepmode DTR must be LOW for at least 50 miliseconds
const char SLEEPON[] PROGMEM = { "AT+CSCLK=1\r" };
const char SLEEPOFF[] PROGMEM = { "AT+CSCLK=0\r" };
// Fix UART speed to 9600 bps
const char SET9600[] PROGMEM = { "AT+IPR=9600\r" };
// Save settings to SIM7000
const char SAVECNF[] PROGMEM = { "AT&W\r" };
// Disable SIM7000 LED for further reduction of power consumption
const char DISABLELED[] PROGMEM = { "AT+CNETLIGHT=0\r" };
// for sending SMS predefined text
const char GOOGLELOC1[] PROGMEM = {"\r\n http://maps.google.com/maps?q="};
const char GOOGLELOC2[] PROGMEM = {","};
const char GOOGLELOC3[] PROGMEM = {"\r\n"};
const char LONG[] PROGMEM = {" LONGTITUDE="};
const char LATT[] PROGMEM = {" LATITUDE="};
const char BATT[] PROGMEM = {"\nBATTERY[mV]="};
const char GPSTIME[] PROGMEM = {"\nGPSTIME="};
// check statuses & cells
const char CHECKBATT[] PROGMEM = {"AT+CBC\r"}; // check battery voltage
// GPS SIM7000 only related AT commands and responses
const char GPSPWRON[] PROGMEM = {"AT+CGNSPWR=1\r"}; // enable GPS inside SIM7000
const char GPSISFIXED[] PROGMEM = {"+CGNSINF: 1,1,"}; // GPS in now fixed
const char GPSINFO[] PROGMEM = {"AT+CGNSINF\r"}; // Read GPS LAT & LONG for SMS
const char GPSCLDSTART[] PROGMEM = {"AT+CGNSCOLD\r"}; // GPS cold restart
const char GPSHOTSTART[] PROGMEM = {"AT+CGNSHOT\r"}; // GPS hot restart
const char GPSPWROFF[] PROGMEM = {"AT+CGNSPWR=0\r"}; // disable GPS inside SIM7000
const char INITLOC[] PROGMEM = {"0000000000000000000\x00"}; // to clear location at the beginning
// HTTP communication commands
// Definition of APN used for GPRS communication
// Please put correct APN, USERNAME and PASSWORD here appropriate for your Mobile Network provider.
// If no password and username delete the text between < and >
const char SAPBR2[] PROGMEM = {"AT+SAPBR=3,1,\"APN\",\"internet\"\r"}; // Put your mobile operator APN name here
const char SAPBR3[] PROGMEM = {"AT+SAPBR=3,1,\"USER\",\"<MyUsername>\"\r"}; // Put your mobile operator APN USERNAME here if any
const char SAPBR4[] PROGMEM = {"AT+SAPBR=3,1,\"PWD\",\"<MyPassword>\"\r"}; // Put your mobile operator APN PASSWORD here if any
// PDP-LTE bearer context commands
const char SAPBROPEN[] PROGMEM = {"AT+SAPBR=1,1\r"}; // open IP bearer
const char SAPBRQUERY[] PROGMEM = {"AT+SAPBR=2,1\r"}; // query IP bearer
const char SAPBRCLOSE[] PROGMEM = {"AT+SAPBR=0,1\r"}; // close bearer
const char SAPBRSUCC[] PROGMEM = {"+SAPBR: 1,1"}; // bearer was succesfull we are not checking IP assigned
// HTTP communication with server - put your server URL broken down to parameters of HTTP GET here
// HTT GET parameters : longtitude, latitude, time
// this is what your server must process and store during URL HTTP GET
const char HTTPINIT[] PROGMEM = { "AT+HTTPINIT\r" };
const char HTTPPARA[] PROGMEM = { "AT+HTTPPARA=\"CID\",1\r" };
const char HTTPURL1[] PROGMEM = { "AT+HTTPPARA=\"URL\",\"http://" };
const char HTTPURL2[] PROGMEM = { "myserver.com/update" }; // this is exact url of your HTTP server
const char HTTPURL3[] PROGMEM = { "&longtitude=" };
const char HTTPURL4[] PROGMEM = { "&latitude=" };
const char HTTPURL5[] PROGMEM = { "&time=" };
const char HTTPURL6[] PROGMEM = { "\"\n\r" };
const char HTTPACTION[] PROGMEM = { "AT+HTTPACTION=0\r" };
// buffers for number of phone, responses from modem
// must fit SMS message with details
#define BUFFER_SIZE 170
volatile static uint8_t response[BUFFER_SIZE] = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
volatile static uint8_t response_pos = 0;
volatile static uint8_t phonenumber[20] = "12345678901234567890";
volatile static uint8_t phonenumber_pos = 0;
volatile static uint8_t smsphonenumber[20] = "12345678901234567890";
volatile static uint8_t smsphonenumber_pos = 0;
volatile static uint8_t smstext[BUFFER_SIZE] = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
volatile static uint8_t smstext_pos = 0;
// buffers for Google GPS API data - longtitude & latitude data
volatile static uint8_t latitude[20] = "00000000000000000000";
volatile static uint8_t latitude_pos = 0;
volatile static uint8_t longtitude[20] = "00000000000000000000";
volatile static uint8_t longtitude_pos = 0;
volatile static uint8_t utctime[20] = "00000000000000000000";
volatile static uint8_t utctime_pos = 0;
// buffers for SIM7000 GPS data - longtitude & latitude data
volatile static uint8_t latitudegps[20] = "00000000000000000000";
volatile static uint8_t longtitudegps[20] = "00000000000000000000";
volatile static uint8_t utctimegps[20] = "00000000000000000000";
volatile static uint8_t latitudegpsold[20] = "00000000000000000000";
volatile static uint8_t longtitudegpsold[20] = "00000000000000000000";
// other buffers
volatile static uint8_t buf[40]; // buffer to copy string from PROGMEM for modem output comparision
volatile static uint8_t battery[10] = "0000000000"; // for battery voltage checking
volatile static uint8_t battery_pos = 0;
// other flags and counters
volatile static uint8_t continousgps = 0;
// ----------------------------------------------------------------------------------------------
// init_uart
// ----------------------------------------------------------------------------------------------
void init_uart(void) {
// double speed by U2X0 flag = 1 to have 0.2% error rate on 9600 baud
UCSR0A = (1<<U2X0);
// set baud rate from PRESCALER
UBRR0H = (uint8_t)(MYUBBR>>8);
UBRR0L = (uint8_t)(MYUBBR);
UCSR0B|=(1<<TXEN0); //enable TX
UCSR0B|=(1<<RXEN0); //enable RX
// set frame format for SIM7000 communication
UCSR0C|=(1<<UCSZ00)|(1<<UCSZ01); // no parity, 1 stop bit, 8-bit data
}
// ----------------------------------------------------------------------------------------------
// send_uart
// Sends a single char to UART without ISR
// ----------------------------------------------------------------------------------------------
void send_uart(uint8_t c) {
// wait for empty data register
while (!(UCSR0A & (1<<UDRE0)));
// set data into data register
UDR0 = c;
}
// ----------------------------------------------------------------------------------------------
// receive_uart
// Receives a single char without ISR
// ----------------------------------------------------------------------------------------------
uint8_t receive_uart() {
while ( !(UCSR0A & (1<<RXC0)) )
;
return UDR0;
}
// ----------------------------------------------------------------------------------------------
// function to search RX buffer for response SUB IN RX_BUFFER STR
// ----------------------------------------------------------------------------------------------
uint8_t is_in_rx_buffer(char *str, char *sub, uint8_t buffersize) {
uint8_t i, j=0, k;
for(i=0; i<buffersize; i++)
{
if(str[i] == sub[j])
{
for(k=i, j=0; str[k] && sub[j]; j++, k++) // if NOT NULL on each of strings
if(str[k]!=sub[j]) break; // if different - start comparision with next char
// if(!sub[j]) return 1;
if(j == strlen(sub)) return 1; // full substring has been found
}
}
// substring not found
return 0;
}
// ----------------------------------------------------------------------------------------------
// uart_puts
// Sends a string.
// ----------------------------------------------------------------------------------------------
void uart_puts(const char *s) {
while (*s) {
send_uart(*s);
s++;
}
}
// ----------------------------------------------------------------------------------------------
// uart_puts_P
// Sends a PROGMEM string.
// ----------------------------------------------------------------------------------------------
void uart_puts_P(const char *s) {
while (pgm_read_byte(s) != 0x00) {
send_uart(pgm_read_byte(s++));
}
}
// ------------------------------------------------------------------------------------------------------------
// READLINE from serial port that starts with CRLF and ends with CRLF and put to 'response' buffer what read
// ------------------------------------------------------------------------------------------------------------
uint8_t readline()
{
uint16_t char1, wholeline ;
uint8_t i;
// wait for first CR-LF or exit after timeout 'i' cycles - safe fuse
i = 0;
wholeline = 0;
response_pos = 0;
//
do {
// read single char
char1 = receive_uart();
// if CR-LF combination detected start to copy the response right after
if ( (char1 != 0x0a) && (char1 != 0x0d) && (i<150) )
{ response[response_pos] = char1;
response_pos++;
};
// if CR or LF detected - end of line
if ( char1 == 0x0a || char1 == 0x0d )
{
// if the line was already received & copied and this is only CR/LF ending :
if (response_pos > 0) // this is EoL
{ response[response_pos] = NULL;
response_pos = 0;
wholeline = 1; };
};
// increment number of read chars and check against overflow
i++;
} while ( (wholeline == 0) && (i<150) );
return(1);
}
// ------------------------------------------------------------------------------------------------------------
// Read content of SMS message right after CMT URC and put to 'smstext' buffer what read
// ------------------------------------------------------------------------------------------------------------
uint8_t readsmstxt()
{
uint16_t char1, wholeline ;
uint8_t i;
// wait for first CR-LF or exit after timeout i cycles
i = 0;
wholeline = 0;
smstext_pos = 0;
//
do {
// read single char and check it
char1 = receive_uart();
// if CR-LF combination detected start to copy the response
if ( (char1 != 0x0a) && (char1 != 0x0d) && (i<150) )
{ smstext[smstext_pos] = char1;
smstext_pos++;
};
// if CR or LF detected - end of line
if ( char1 == 0x0a || char1 == 0x0d )
{
// if the line was already received & copied and this is only CR/LF ending :
if (smstext_pos > 0) // this is EoL
{ smstext[smstext_pos] = NULL;
smstext_pos = 0;
wholeline = 1; };
};
// increment number of read chars and check for overflow
i++;
} while ( (wholeline == 0) && (i<150) );
return(1);
}
// ----------------------------------------------------------------------------------------------------------------------------
// read SMS message PHONE NUMBER from +CMT: output and response buffer and copy it to buffer 'phonenumber' for SMS sending
// ----------------------------------------------------------------------------------------------------------------------------
uint8_t readsmsphonenumber()
{
// need 8bit ascii
uint8_t char1;
uint8_t i;
// 'i' is a safe fuse not to get out of response buffer
i = 0;
phonenumber_pos = 0;
// reading from RESPONSE buffer of modem output, rewind to beginning of buffer
response_pos = 0;
// wait for "+CMT:" and space
do {
char1 = response[response_pos];
response_pos++;
i++;
} while ( (char1 != ':') && (i<150) );
// wait for first quotation sign - there will be MSISDN number of sender
do {
char1 = response[response_pos];
response_pos++;
i++;
} while ( (char1 != '\"') && (i<150) );
// if quotation detected start to copy the response - phonenumber
do {
char1 = response[response_pos];
response_pos++;
phonenumber[phonenumber_pos] = char1;
phonenumber_pos++;
i++;
} while ( (char1 != '\"') && (i<150) ); // until end of quotation
// put NULL to end the string phonenumber
phonenumber[phonenumber_pos-1] = NULL;
phonenumber_pos=0;
response_pos = 0;
return (1);
}
// ----------------------------------------------------------------------------------------------
// Read BATTERY VOLTAGE in milivolts from AT+CBC output and put results to 'battery' buffer
// ----------------------------------------------------------------------------------------------
uint8_t readbattery()
{
uint16_t char1;
uint8_t i;
// 'i' is a safe fuse not to get deadlocked in code
i = 0;
battery_pos = 0;
// wait for first COMMA sign
do {
char1 = receive_uart();
i++;
} while ( (char1 != ',') && (i<70) );
// check if deadlocked
if (i == 70) return(0);
// wait for second COMMA sign
do {
char1 = receive_uart();
i++;
} while ( (char1 != ',') && (i<70) );
// if 2 COMMA detected start to copy battery voltage to buffer
do {
char1 = receive_uart();
battery[battery_pos] = char1;
battery_pos++;
i++;
} while ( (char1 != 0x0a) && (char1 != 0x0d) && (i<70) );
battery[battery_pos-1] = NULL;
battery_pos=0;
return (1);
}
// -----------------------------------------------------------------------------------------------------
// READ SIM7000 GPS from AT+CGPSINF output and put output to 'lattitude' and 'longtitude' buffers
// -----------------------------------------------------------------------------------------------------
uint8_t readSIM7000gps()
{
uint16_t char1;
uint8_t i;
// 'i' is a safe fuse not to get deadlock on serial port reading
i = 0;
// set positions to start of each buffer
longtitude_pos = 0;
latitude_pos = 0;
uart_puts_P(GPSINFO); // try to retrieve GPS position
// wait for "+CGNSINF:" last sign
do {
char1 = receive_uart();
i++;
} while ( (char1 != ':') && (i<20) );
// check if deadlocked and buffer overrun, there should be +CGPSINF: within first 20 chars
if (i == 20) return(0);
// wait for FIRST COMMA sign - we omit GNSPWR info
do {
char1 = receive_uart();
i++;
} while ( (char1 != ',') && (i<150) );
// wait for SECOND COMMA sign - we omit GNS fixation info
do {
char1 = receive_uart();
i++;
} while ( (char1 != ',') && (i<150) );
// if COMMA detected start to copy the response - UTCTIME comes first
do {
char1 = receive_uart();
utctime[utctime_pos] = char1;
utctime_pos++;
i++;
} while ( (char1 != ',') && (i<150) );
// put end of string to latitude
utctime[utctime_pos-1] = NULL;
utctime_pos=0;
// if COMMA detected start to copy the response - LATITUDE comes second
do {
char1 = receive_uart();
latitude[latitude_pos] = char1;
latitude_pos++;
i++;
} while ( (char1 != ',') && (i<150) );
// put end of string to latitude
latitude[latitude_pos-1] = NULL;
latitude_pos=0;
// if COMMA detected start to copy the response - LONGTITUDE is third
do {
char1 = receive_uart();
longtitude[longtitude_pos] = char1;
longtitude_pos++;
i++;
} while ( (char1 != ',') && (i<150) );
longtitude[longtitude_pos-1] = NULL;
longtitude_pos=0;
// now comes ATTITUDE - bypassing
do {
char1 = receive_uart();
i++;
} while ( (char1 != ',') && (i<150) );
return (1);
}
// --------------------------------------------------------------------------------------------------------------------
// Power on GPS and retrieve position from GPS and put it to LOC and LATT buffers by calling 'readSIM7000gps' function
// --------------------------------------------------------------------------------------------------------------------
uint8_t readgpsinfo()
{
uint8_t gpsattempts, gpsfixed; // counter on attempts to get proper GPS position from SIM7000 - for indoor scenarios
gpsattempts = 0;
gpsfixed = 0;
// if begining/last cycle of continous GPS mode we need to turn on and restart GPS module
if ( (continousgps == 1) || (continousgps == 5) )
{
delay_sec(1);
uart_puts_P(GPSPWRON); // enable SIM7000 GPS power
delay_sec(2);
uart_puts_P(GPSCLDSTART); // cold start of SIM7000 GPS
}
else // during continous mode cycle - we dont need to turn on and restart GPS module
{
delay_sec(1);
// hot start of SIM7000 GPS if needed, otherwise simply poll GPS data
// uart_puts_P(GPSHOTSTART);
};
// now we have to wait some time until SIM7000 gets GPS signal, assume we are waiting 10 minutes
// check the status in 30 sec intervals and then quit
do
{
if ( continousgps != 255 ) delay_sec(15); // in NOT in GUARD mode - wait 15 sec for first fix checking
uart_puts_P(GPSINFO); // check GPS status
if (readline()>0) // check GPS status response if NOT FIXED
{
gpsfixed = 0;
// check if already fixed for GPS coordinates ?
memcpy_P(buf, GPSISFIXED, sizeof(GPSISFIXED));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE ) == 1)
{
// when CGNSINF: 1,1 - stop checking GPS anymore
gpsfixed = 1;
};
// special treatment for GUARD MODE - if not fix quit immediatelly, because there will be repeatition in 1 min
if ( (gpsfixed == 0) && (continousgps == 255) ) return (0);
// there was some fix - 3D or 2D, poll the data from GPS
if ( gpsfixed == 1)
{
// initialize buffers with zero characters first before reading new values from SIM7000 GNSS
memcpy_P(latitudegps, INITLOC, sizeof(INITLOC));
memcpy_P(longtitudegps, INITLOC, sizeof(INITLOC));
memcpy_P(utctimegps, INITLOC, sizeof(INITLOC));
readSIM7000gps(); // poll GPS position and parse to buffers LAT & LONG
delay_sec(2);
if (continousgps == 1) // ... if last GPS cycle or single sequence
{ uart_puts_P(GPSPWROFF); // disable SIM7000 GPS power to save battery
delay_sec(1);
};
return(1); // succesful GPS position decoding from SIM7000
} // end of second IF
else gpsattempts++; // if not fixed just increase attempts counter
}; // end of first IF
} while (gpsattempts<20); // end of DO loop - only 20 attempts in 15 sec intervals to get GPS fixation - 5 minutes of searching
// GPS position retrieval not succesful - we are disabling GPS/GNSS power
delay_sec(2);
if (continousgps == 1) // ... if last GPS cycle or single sequence
{ uart_puts_P(GPSPWROFF); // disable SIM7000 GPS power to save battery
delay_sec(1);
};
return(0); // 0 means that GPS was unable to fix on sattelites at all
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// delay procedure ASM based because _delay_ms() is working bad for 1 MHz clock MCU
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// delay partucular number of seconds
void delay_sec(uint8_t i)
{
while(i > 0)
{
// Delay 1 000 000 cycles
// 1s at 1 MHz
asm volatile (
" ldi r18, 6" "\n"
" ldi r19, 19" "\n"
" ldi r20, 174" "\n"
"1: dec r20" "\n"
" brne 1b" "\n"
" dec r19" "\n"
" brne 1b" "\n"
" dec r18" "\n"
" brne 1b" "\n"
" rjmp 1f" "\n"
"1:" "\n"
);
i--; // decrease another second
}; // repeat until i not zero
}
//
// delay multiplication of 50 microseconds
//
void delay_50usec()
{
// Generated by delay loop calculator
// at http://www.bretmulvey.com/avrdelay.html
// Delay 50 cycles
// 50us at 1 MHz
asm volatile (
" ldi r18, 16" "\n"
"1: dec r18" "\n"
" brne 1b" "\n"
" rjmp 1f" "\n"
"1:" "\n"
);
}
//////////////////////////////////////////
// SIM7000 initialization procedures
//////////////////////////////////////////
// -------------------------------------------------------------------------------
// wait for first AT in case SIM7000 is starting up
// -------------------------------------------------------------------------------
uint8_t checkat()
{
uint8_t initialized2;
// wait for first OK while sending AT - autosensing speed on SIM7000, but we are working 9600 bps
// SIM 800L can be set by AT+IPR=9600 to fix this speed
// which I do recommend by connecting SIM7000 to PC using putty and FTD232 cable
initialized2 = 0;
do {
uart_puts_P(AT);
if (readline()>0)
{ // check if OK was received
memcpy_P(buf, ISOK, sizeof(ISOK));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) initialized2 = 1;
}
else
{ // maybe ECHO is ON and first line was AT
memcpy_P(buf, ISATECHO, sizeof(ISATECHO));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) initialized2 = 1;
};
delay_sec(1);
} while (initialized2 == 0);
// send ECHO OFF
delay_sec(1);
uart_puts_P(ECHO_OFF);
delay_sec(1);
return (1);
}
// -------------------------------------------------------------------------------
// check if PIN is needed and enter PIN 1111
// -------------------------------------------------------------------------------
uint8_t checkpin()
{
uint8_t initialized2;
// readline and wait for PIN CODE STATUS if needed send PIN 1111 to SIM card if required
initialized2 = 0;
do {
delay_sec(2);
uart_puts_P(SHOW_PIN);
if (readline()>0)
{
memcpy_P(buf, PIN_IS_READY, sizeof(PIN_IS_READY));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) initialized2 = 1;
memcpy_P(buf, PIN_MUST_BE_ENTERED, sizeof(PIN_MUST_BE_ENTERED));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1)
{
delay_sec(1);
uart_puts_P(ENTER_PIN); // ENTER PIN 1111
delay_sec(1);
};
};
} while (initialized2 == 0);
return (1);
}
// -------------------------------------------------------------------------------
// check if registered to the network
// -------------------------------------------------------------------------------
uint8_t checkregistration()
{
uint8_t initialized2, attempt2, nbrminutes;
// readline and wait for STATUS NETWORK REGISTRATION from SIM7000
// first 2 networks preferred from SIM list are OK
initialized2 = 0;
nbrminutes = 0;
attempt2 = 0;
// check if already registered first and quit immediately if true
delay_sec(1);
uart_puts_P(SHOW_REGISTRATION);
if (readline()>0)
{
memcpy_P(buf, ISREG1, sizeof(ISREG1));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) return(1);
memcpy_P(buf, ISREG2, sizeof(ISREG2));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) return(1);
}
// if not registered enable radio.. just in case
// TURN ON RADIO IF WAS NOT BEFORE
delay_sec(1);
uart_puts_P(FLIGHTOFF); // disable airplane mode - turn on radio and start to search for networks
do {
delay_sec(120); // first searching 1 min in case of instability
// now after searching check if already registered to 2G GSM
uart_puts_P(SHOW_REGISTRATION);
if (readline()>0)
{
memcpy_P(buf, ISREG1, sizeof(ISREG1));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) initialized2 = 1;
memcpy_P(buf, ISREG2, sizeof(ISREG2));
if (is_in_rx_buffer(response, buf, BUFFER_SIZE) == 1) initialized2 = 1;
// if not registered do a backoff for 1 hour, maybe in underground garage or something
if (initialized2 == 0)
{
// if not registered or something wrong turn off RADIO for minutes
// this is not to drain battery in underground garage
delay_sec(1);
uart_puts_P(FLIGHTON); // enable airplane mode - turn off radio
delay_sec(1);
uart_puts_P(GPSPWROFF);
// enter SLEEP MODE of SIM800L for power saving when no coverage
delay_sec(1);
uart_puts_P(SLEEPON);
// now wait XX min before turning on radio again, here XX = 30 min
for (nbrminutes = 0; nbrminutes<30; nbrminutes++)
{
delay_sec(60);
};
// Wake up SIM800L and search for network again
// disable SLEEPMODE
PORTC &= ~_BV(PC5); // Toggle LOW the DTR pin of SIM7000
// send first dummy AT command
uart_puts_P(AT);
delay_sec(1);
uart_puts_P(SLEEPOFF); // switch off to SLEEPMODE = 0
delay_sec(1);
PORTC |= _BV(PC5); // Toggles again HIGH the DTR pin
delay_sec(1);
uart_puts_P(FLIGHTOFF); // disable airplane mode - turn on radio and start to search for networks
}; // end of no-coverage IF
}
attempt2++; // increase number of attempts - max 24 attempts = 12 hours of no signal 2G network
// end of DO loop
} while ( (initialized2 == 0) && (attempt2 < 24) );
return initialized2;
}
//////////////////////////////////////////////////////////////////////////////////
// POWER SAVING mode on ATMEGA 328P handling to reduce the battery consumption
// this part of code can be used ONLY if you have SIM7000 RI/RING PIN connected
// to ATMEGA D2/INT0 interrupt input - otherwise program will hang
//////////////////////////////////////////////////////////////////////////////////
void sleepnow(void)
{
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
DDRD &= ~(1 << DDD2); // Clear the PD2 pin
// PD2 (PCINT0 pin) is now an input
PORTD |= (1 << PORTD2); // turn On the Pull-up
// PD2 is now an input with pull-up enabled
// stop interrupts for configuration period
cli();
// update again INT0 conditions
EICRA &= ~(1 << ISC01); // set INT0 to trigger on low level
EICRA &= ~(1 << ISC00); // set INT0 to trigger on low level
EIMSK |= (1 << INT0); // Turns on INT0 (set bit)
sei(); //ensure interrupts enabled so we can wake up again
sleep_cpu(); //go to sleep
// MCU ATTMEGA328P sleeps here until INT0 interrupt
sleep_disable(); //wake up here
}
// when interrupt from INT0 disable next interrupts from RING pin of SIM7000 and go back to main code
ISR(INT0_vect)
{
EIMSK &= ~(1 << INT0); // Turns off INT0 (clear bit)
}
// *********************************************************************************************************
//
// MAIN PROGRAM
//
// *********************************************************************************************************
int main(void) {
uint8_t initialized, ringrcvd, attempt, gpsdataavailable, char1;
double latdiff, longdiff;
uint32_t nbr50useconds;
uint32_t nbrseconds;
attempt = 0; // number of attempts for GPRS connections
initialized = 0; // flag for getting in-out of loops
ringrcvd = 0; // flag if there was anything valuable received
latdiff = 0; // calculation of position change for GUARD MODE
longdiff = 0; // calculation of position change for GUARD MODE
nbr50useconds = 0; // timer for checking serial port activities or SIM7000 chip sanity
nbrseconds = 0; // used for delay function
continousgps = 0; // distinguish between modes : 1 = single, 5 = multi, 255 = guard
gpsdataavailable = 0; // flag if real GPS data from SIM7000 were OK
// enable INPUT on INT0 / PD2 (ATMEGA PIN #4) to connect RI/RING from SIM7000 if available
DDRD &= ~(1 << DDD2); // Clear the PD2 pin - PD2 (PCINT0 pin) is now an input
PORTD |= (1 << PORTD2); // turn On the Pull-up - PD2 is now an input with pull-up enabled
// enable output to control DTR signal of SIM7000
// ATMEGA pin PC5 must be connected to DTR/SLEEP signal of SIM7000 board
DDRC |= (1<<5) ; // set OUTPUT mode for PC5
// PORTC &= ~_BV(PC5); // Toggle LOW the DTR pin of SIM7000
PORTC |= _BV(PC5); // Toggles HIGH the DTR pin
// pull up RXD input on ATMEGA
//DDRD &= ~(1 << DDD0); // Clear the PD2 pin
// PD2 (PCINT0 pin) is now an input
//PORTD |= (1 << PORTD0); // turn On the Pull-up
// PD2 is now an input with pull-up enabled
// initialize variables
memcpy_P(latitudegpsold, INITLOC, sizeof(INITLOC));
memcpy_P(latitudegps, INITLOC, sizeof(INITLOC));
memcpy_P(longtitudegpsold, INITLOC, sizeof(INITLOC));
memcpy_P(longtitudegps, INITLOC, sizeof(INITLOC));
memcpy_P(utctimegps, INITLOC, sizeof(INITLOC));
// initialize 9600 baud 8N1 RS232
init_uart();
// delay 10 seconds for safe SIM7000 startup and network registration
delay_sec(10);
// turno of ECHO proactively
uart_puts_P(ECHO_OFF);
delay_sec(1);
// try to communicate with SIM7000 over AT
checkat();
delay_sec(1);
// Fix UART speed to 9600 bps to disable autosensing
uart_puts_P(SET9600);
delay_sec(1);
// TURN ON RADIO IF WAS NOT BEFORE
uart_puts_P(FLIGHTOFF);
delay_sec(1);
// if you have connected SIM7000 board RI/RING pint to ATMEGA328P INT0 pin
// configure RI PIN activity for URC ( unsolicited messages like restart of the modem or battery low)
// uart_puts_P(CFGRIPIN);
// delay_sec(2);
// disable reporting URC of losing 2G coverage by +CREG=0
uart_puts_P(DISREGREPORT);
delay_sec(1);
// Save settings to SIM7000
uart_puts_P(SAVECNF);
delay_sec(3);
// check PIN status
checkpin();
delay_sec(1);
// delete all previous SMSes and SMS confirmation to keep SIM7000 memory empty
uart_puts_P(SMS1);
delay_sec(1);
uart_puts_P(DELSMS);
// delay another 90 sec to search for GSM network
delay_sec(90);
// check registration status
checkregistration();
// neverending LOOP