Last active
November 24, 2019 02:54
-
-
Save doorbash/6867dd2b044f945690fbad4dc51ace27 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define MESSAGE_TOTAL_LENGTH 301 | |
| #define BIT_PERIOD 350 | |
| #define DATA_PIN 4 | |
| #include <SoftwareSerial.h> | |
| int data[] = {0, 0, 0, 0, 0, 0, 0, 0, 0}; | |
| int size = sizeof(data) / sizeof(int); | |
| SoftwareSerial mSerial(2, 3); // RX, TX | |
| char message[MESSAGE_TOTAL_LENGTH]; | |
| char command[MESSAGE_TOTAL_LENGTH]; | |
| int messageLen = 0; | |
| int commandLen = 0; | |
| bool readyToDeleteAllMessages = false; | |
| void openDoor() { | |
| Serial.println("Opening door..."); | |
| for (int cnt = 0; cnt < 15; cnt++) { | |
| for (int i = 0; i < size; i++) { | |
| digitalWrite(DATA_PIN, data[i]); | |
| delayMicroseconds(BIT_PERIOD); | |
| } | |
| digitalWrite(DATA_PIN, LOW); | |
| delay(12); | |
| } | |
| } | |
| bool messageStartsWith(const char *str) { | |
| if (messageLen < strlen(str)) return false; | |
| for (int i = 0; i < strlen(str); i++) { | |
| if (str[i] != message[i]) return false; | |
| } | |
| return true; | |
| } | |
| void setup() { | |
| Serial.begin(9600); | |
| mSerial.begin(2400); | |
| pinMode(DATA_PIN, OUTPUT); | |
| } | |
| void loop() { | |
| if (mSerial.available() > 0) { | |
| char r = (char)mSerial.read(); | |
| if ((r == '\r' || r == '\n')) { | |
| if (messageLen > 0) { | |
| message[messageLen] = 0; | |
| parseMessage(); | |
| messageLen = 0; | |
| } | |
| } else if (messageLen < (MESSAGE_TOTAL_LENGTH - 1)) { | |
| message[messageLen] = r; | |
| messageLen++; | |
| } else messageLen = 0; | |
| } | |
| if (Serial.available() > 0) { | |
| char r = (char)Serial.read(); | |
| if (r == '\n') { | |
| if (commandLen > 0) { | |
| command[commandLen] = 0; | |
| if (strcmp(command, "OPEN") == 0) openDoor(); | |
| else { | |
| Serial.print("command is "); | |
| Serial.println(command); | |
| } | |
| commandLen = 0; | |
| } | |
| } else if (commandLen < (MESSAGE_TOTAL_LENGTH - 1)) { | |
| command[commandLen] = r; | |
| commandLen++; | |
| } else commandLen = 0; | |
| } | |
| } | |
| void parseMessage() { | |
| if (messageStartsWith("+CMTI:")) { | |
| char *buf = &message[12]; | |
| int msgNumber = atoi(buf); | |
| delay(1000); | |
| mSerial.print("AT+CMGR="); | |
| mSerial.print(msgNumber); | |
| mSerial.print("\r\n"); | |
| mSerial.flush(); | |
| } else if (messageStartsWith("+CMGR:")) { | |
| Serial.println(message); | |
| readyToDeleteAllMessages = true; | |
| } else if (messageStartsWith("OK") && readyToDeleteAllMessages) { | |
| mSerial.println("AT+CMGD=1 ,4\r"); | |
| readyToDeleteAllMessages = false; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment