Мобалка в авто
- Войдите на сайт для отправки комментариев
Пт, 17/01/2020 - 14:49
Доброго вам времени суток. Очень прошу помощи в корректировке кода. сам уже всю голову сломал и весь интернет истоптал.
Имеется оборудование:
1. Arduino MEGA 2560
2. Sim800L
3. Дисплей 1,3' sh1106 i2c
ну и клавиатура.
не могу вывести данные на этот дисплей с Liqid krystal все работает.
код во вложении. Заранее спасибо!!!
#include <Arduino.h>
#include <SoftwareSerial.h>
#include<String.h>
#include <U8g2lib.h>
#include <Wire.h>
#ifdef U8X8_HAVE_HW_I2C
#endif
U8G2_SH1106_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
SoftwareSerial SIM800(12, 13); // These pins are connected to GSM module( RX, TX )
String number = "";
String action = "WT"; //String codes: RC =Receive call, RM= Receive msg, SC= Send calll, SM= Send message, WT= Wait
// Receive sms Strings
String Response = "";
String sms = "";
String Type;
String Caller_id;
String Text;
String SP_name = "";
char character;
char quote = 0x22;
// Global Flags
bool Send_m = false;
bool sms_Receive_mode_off = true;
bool Receive_mode = false;
bool msg_Receive = false;
bool time_registered = false;
bool msg_fetched = false;
bool on_call = false;
bool start_Receive = false;
bool flag = true;
int sec, minutes; // Clock variables
long c_start;
long c_time;
int i = 0;
int indexOfQuotes[10];
double time_start;
double time_current;
double operational_time;
/********* Keypad Variables**********/
int r1 = 14;
int r2 = 15;
int r3 = 16;
int r4 = 17;
int c1 = 18;
int c2 = 19;
int c3 = 2;
int c4 = 3;
int colm1;
int colm2;
int colm3;
int colm4;
char value;
//
char num1;
void setup()
{
Serial.begin(9600);
Serial.println("GSM startrd");
SIM800.begin(9600);
SIM800.setTimeout(2000);
Serial.setTimeout(2000);
initilise();
u8g2.begin();
u8g2.setFont(u8g2_font_6x10_tr);
get_SP();
}
void loop()
{
Serial.println("Action: " + action); //Reports it current mode of working
while (action == "WT") // Its wait for SMS and Calls in this loop
{
if (sms_Receive_mode_off) //So, This turns on the SMS recieve mode
{ delay(1000);
On_sms_Receive_mode();
}
if (flag)
{
Serial.println("Receive_ready");
flag = false;
print_head("Connected to:"); // Service provide name is printed on LCd
print_content(SP_name);
clear_Serial();
}
if (Receiving_on()) // FINALLY, the module is set to receive, Receive_on will beocome true in case msg or call arrives
{
Extract_type();
}
else
{ // In case of no reciving, update the current signal strength
update_signal_strength();
get_request(); // Or, check if user pressed any button for callling or SMS
}
}
while (action == "SM") // Sending Msg action
{
Serial.println("Enter number to message");
print_head("Send SMS to");
number = Take_input(); // Take input through swith matrix
//LCD print for Send message
bool success = send_sms(number);
if (success) // If sucessful go to wait state otherwise send again
{
action = "WT";
}
flag = true;
}
while (action == "SC") //Sending call action, similar process as above
{
print_head("Enter Call num");
Serial.println("Enter number to call");
number = Take_input();
if (valid_number()) // Check number is 10 digit long
{
print_head("Calling");
print_content(number);
delay(1000);
send_call(number);
print_head("On line with");
print_content(number);
delay(1000);
clear_Serial();
if (on_call)
{
terminate_call(); // Waits here till the user is on call
}
}
action = "WT";
flag = true;
}
while (action == "RC") // Recive call action
{
Serial.println("Press * to pick up or # to terminate");
print_head("Call from");
print_content(Caller_id);
clear_Serial();
WaitForPickup();
//incall
if (on_call) // Waits here till the user is on call
{
terminate_call();
}
Serial.println("Call response Recieved");
action = "WT";
flag = true;
}
while (action == "RM") // Recieve SMS action
{
Show_sms();
action = "WT";
flag = true;
}
}
/*
Function to get the service provider(SP) name
Sets a Global varible: SP_name
*/
void get_SP (void)
{ bool got_it = false;
delay(1000);
SIM800.println("AT");
delay(500);
print_head("Connecting GSM");
while (!( SP_name.indexOf('"') > 0))
{ if (GSM_operational())
{
SIM800.println("AT+COPS?"); //AT command for getting serivce provider name
SIM800.println();
}
delay(1000);
while (SIM800.available())
{
char character = SIM800.read();
SP_name.concat(character);
}
}
// Extracton process
SP_name = (SP_name.substring(SP_name.indexOf('"') + 1, SP_name.lastIndexOf('"')));
Serial.println("Connected to: " + SP_name);
}
// Fuciton to print current signal strength on lcd
void update_signal_strength (void)
{ String Network;
long Strength;
SIM800.println("AT+CSQ");
SIM800.println();
delay(500);
while (SIM800.available())
{
char character = SIM800.read();
Network.concat(character);
}
Network = Network.substring(Network.indexOf(':') + 2, Network.indexOf(','));
Strength = Network.toInt(); // Strength Int value here
Strength = (Strength * 100 / 31); // MAX strength= 31
u8g2.setCursor(0, 15);
u8g2.print(int(Strength));
u8g2.print('%');
}
//It recives a the char value of key pressed and stores it into
void get_request (void)
{
value = Return_Keypad_Values();
event(value);
}
// Select the apt mode as per the input
void event(char func)
{
switch (func)
{
case 'A':
action = "SC"; //Send call
break;
case 'B':
action = "SM"; // Send Message
break;
//case 'C': // you can use this case for any purpose
// receive_call();
// break;
default:
action = "WT"; // Wait for response
break;
}
}
/*
Input: (string:num,)
Output bool( t=sent f=unsent)
Function to send sms to number
*/
bool send_sms (String number)
{
delay(1000);
SIM800.println("AT");
delay(500);
if (GSM_operational())
{
SIM800.println("AT+CMGF=1");
delay(500);
}
if (GSM_operational())
{
SIM800.print("AT+CMGS=\""); // Send the SMS number
SIM800.print(number);
SIM800.println("\"");
delay(1000);
SIM800.print("GSM bot functonal"); // SMS BODY here in case u want change
// SIM800.print(i);
delay(500);
SIM800.write(0x1A);
SIM800.write(0x0D);
SIM800.write(0x0A);
Serial.println("SMS sent");
print_head("SMS Sent to");
print_content(number);
delay(2000);
return (true); //SMS sent succussfuly
}
return (false); // Failed attempt
}
/*
Input: (string:num,)
Output bool( t=sent f=failed)
Function to send call to number
*/
bool send_call (String number)
{
SIM800.println("AT");
delay(500);
if (GSM_operational())
{
//Number dialing
Serial.println("Calling to :" + number);
print_head("Calling to");
print_content(number);
SIM800.println("ATD" + number + ";"); // AT command for dialing up the number
SIM800.println();
on_call = true;
return (true);
}
return (false);
}
// This is to switch on the messaging mode of Gsm
void On_sms_Receive_mode (void)
{
SIM800.print("ATE0");
delay(500);
if (GSM_operational())
SIM800.print("AT");
delay(500);
if (GSM_operational())
SIM800.print("AT+CMGF=1"); // Setup in msging mode
delay(500);
if (GSM_operational())
{
SIM800.print("AT+CNMI=2,2,0,0,0\r" ); //Prints the msg on serial as soon as it arrives
delay(500);
while (SIM800.available())
{
char response = SIM800.read();
Serial.println(response);
}
Serial.println("Receive mode On");
sms_Receive_mode_off = false; //turn it on off
}
}
/*
Input: none
Output: True: A response( call or sms) incoming, Or false
*/
bool Receiving_on (void)
{
bool Response_available = false;
if (SIM800.available())
{
while (!halt_fetch()) //In case of incoming recieve until halt_fetch() gives true
{
while (SIM800.available())
{
if (!time_registered) //Capture the time of start of message receiving
{
time_start = millis();
time_registered = true;
}
char character = SIM800.read();
Response.concat(character);
Serial.print(character); // Store as a string
}
}
Serial.println("Response Received"); //Looks like we got something
Response_available = true;
msg_fetched = false;
flag = true;
}
return (Response_available);
}
/*
The function is created to halt or to indicate the end of receiving
It does that by a timeout of 3sec or Response Text limit of 500 characters
Input: none
Output: Boolean, T= halt fetching F= Wait for message
*/
bool halt_fetch (void)
{
bool halt = false;
if (time_registered)
{
time_current = millis();
operational_time = time_current - time_start;
}
if (operational_time > 3000 || Response.length() == 200 ) // Halt condition
{
halt = true;
operational_time = 0;
}
return halt;
}
/*
It extracts the Response and caller id
It does that by quotes position.
Caller id is between first and second quotes
While, Text message is after last quotes
*/
void Extract_type (void)
{
if (valid_input())
{
Serial.println("Valid respone");
extract();
// Serial.println(Response); //In case u want to see everything incoming
// Serial.println("Type: ");
// Serial.print(Type);
// Serial.println("Caller id : ");
// Serial.println(Caller_id);
// Serial.println("Text: ");
// Serial.println(Text);
callORsms();
Serial.print(Caller_id);
}
time_registered = false;
Response = ""; //Clear string for refresh incoming
}
/*
Checks the validity condition,
True: Its call or msg Resonse
False: it is some junk
*/
bool valid_input (void)
{
bool validity;
validity = (( Response.indexOf('+') > 0) && (Response.indexOf('"') > 0 )); //If the reponse has these two thing that means it is a 'real' response
if (!validity)
{
Serial.println("invalid input");
}
return (validity);
}
// Find the indexes of all the quotes in the stirng and sets them up in gloablevariable: indexOfQuotes[index]
void extract(void)
{
int Length, i, index = 0;
Length = Response.length();
for (i = 0; i <= Length; i++)
{
if (Response.charAt(i) == quote)
{
indexOfQuotes[index] = i;
index++;
}
}
Type = Response.substring(1, indexOfQuotes[0]);
Caller_id = Response.substring(indexOfQuotes[0] + 1, indexOfQuotes[1]);
Text = Response.substring(indexOfQuotes[5] + 3);
Serial.println("Extracted");
}
// Determine weather the response is of call or sms
void callORsms (void)
{
if ( Type.indexOf("LIP") > 0) //Call string consist this( +CLIP)
{ action = "RC";
Serial.println("Call from: ");
}
else if (Type.indexOf("MT") > 0 ) // Msg stirng consist (+CMT)
{ action = "RM";
Serial.println("Message from: ");
}
}
// Waits till customer press * or #
void WaitForPickup (void)
{
char key;
bool user_wait = true; //default state
while (user_wait)
{ user_wait = check_termination();
key = Return_Keypad_Values();
if (key == '*') //picking up reponse
{
SIM800.println("ATA");
SIM800.println();
Serial.println("Call picked up");
print_head("Call picked up");
print_content(Caller_id);
delay(1000);
user_wait = false;
on_call = true;
}
if (key == '#') //Termination action
{
SIM800.println("ATH");
SIM800.println();
Serial.println("Call Terminated");
print_head("Call Terminated");
delay(1000);
print_content(Caller_id);
on_call = false;
user_wait = false;
}
}
}
/*
This function is used after two user get connected on a call
It waits '#' to terminate or 'NO CARRIER' on serial monitor
It updates clock untill waiting
* */
void terminate_call (void)
{
char key;
bool user_wait = true; //default state
start_clock();
while (user_wait)
{
user_wait = check_termination();
key = Return_Keypad_Values();
if (key == '#')
{
SIM800.println("ATH"); //Termination action
SIM800.println();
Serial.println("Call Terminated");
print_head("Call Terminated");
delay(1000);
print_content(Caller_id);
user_wait = false;
}
else
{
update_clock();
}
}
on_call = false;
}
// Function to start a clock
void start_clock (void)
{
u8g2.clearBuffer();
c_start = millis();
sec = 0;
minutes = 0;
u8g2.print("On call");
}
// Function to update the value as arduino internal clock
void update_clock (void)
{
long current = millis();
if (current - c_start > 1000)
{
sec++;
c_start = current;
}
if (sec > 59)
{
minutes++;
sec = -0;
}
u8g2.setCursor(10, 30);
if (minutes < 10)
{
u8g2.print('0');
}
u8g2.print(minutes);
u8g2.print(':');
if (sec < 10)
{
u8g2.print('0');
}
u8g2.print(sec);
}
// Fuction to Show sms on a LCD
void Show_sms (void)
{
print_head("SMS from");
print_content(Caller_id);
char key;
// Enhance modularity
bool user_wait = true;
while (user_wait)
{ key = Return_Keypad_Values();
if (key == '*')
{
print_head(Text.substring(0, 16)); // This can scroll SMS
print_content(Text.substring(16, 32));
delay(2000);
print_head(Text.substring(16, 32));
print_content(Text.substring(32, 48));
delay(2000); //A scroll fuction can be made
Serial.println(Text);
user_wait = false;
}
if (key == '#')
{
print_head("OK");
Serial.println("MSG Terminated");
delay(500);
user_wait = false;
}
}
}
//True if starkey is pressed
bool Starkey_pressed (void)
{ char key;
key = Return_Keypad_Values();
return (key == '*');
}
//True if Hashkey is pressed
bool Hashkey_pressed (void)
{ char key;
key = Return_Keypad_Values();
return (key == '#');
}
//Check if 'NO CARRIER' is printer on Serial monitor
bool check_termination (void)
{
bool check = true;
String listen_no = "";
while (SIM800.available())
{
char data = SIM800.read();
Serial.print(data);
listen_no.concat(data);
}
if (listen_no.indexOf("CAR") > 0) // I check for only CAR
{
check = false;
}
return check;
}
// A Fuciton to check the lenth of number calling should be 10 + ('+91' country code) =13
bool valid_number (void)
{
bool valid = false;
if (number.length() == 13) // condition here
{
valid = true;
}
else
{ print_head("Invalid input");
delay(1000);
}
return valid;
}
//Essential command to determine the state of GSM module
bool GSM_operational(void)
{
int count = 0;
bool Status = false;
SIM800.println();
while (1)
{
if (SIM800.available() > 0)
{
char data = SIM800.read();
if ( data == 'O' || data == 'K') //Its working properly
{
Serial.println("OK");
Status = true;
break;
}
if ( data == 'E' || data == 'R' || data == 'O') // Working yet busy with some thing else
{
Serial.println("GSM not functional");
Status = false;
break;
}
}
count++;
delay(10);
if (count == 100)
{
Serial.println("GSM not connected"); // No reponse for AT commands
Status = false;
break;
}
}
return Status;
}
void clear_Serial (void)
{
while (SIM800.available())
{
char character = SIM800.read();
Serial.print(character);
}
}
/*************************************************************
Keypad Firmware Ahead
*************************************************************/
/*
input: none
Output: A 13 digit number
Waits till user enter a ten Digit number
*/
String Take_input (void)
{ String num = "+91";
int len = 0;
int len2;
while (len <= 13)
{
len = num.length();
num1 = Return_Keypad_Values();
if ((num1 != 'A') && (num1 != 'B') && (num1 != 'C') && (num1 != 'a'))
{
if ((num1 != '#') && (num1 != '*') && (num1 != 'D'))
{ num += String(num1);
print_content(num);
Serial.println(num);
}
else if (num1 == '*')
{
num.setCharAt(len - 1, '*');
print_content(num);
num.remove(len - 1);
}
else if (num1 == '#')
{
Serial.println(num);
break;
}
else if (num1 == 'D')
{
break;
}
}
}
return num;
}
void initilise()
{
pinMode(r1, OUTPUT);
pinMode(r2, OUTPUT);
pinMode(r3, OUTPUT); //use in setup
pinMode(r4, OUTPUT);
pinMode(c1, INPUT);
pinMode(c2, INPUT);
pinMode(c3, INPUT);
pinMode(c4, INPUT);
Serial.begin(9600);
digitalWrite(c1, HIGH);
digitalWrite(c2, HIGH);
digitalWrite(c3, HIGH);
digitalWrite(c4, HIGH);
}
void row1()
{
digitalWrite(r1, LOW);
digitalWrite(r2, HIGH);
digitalWrite(r3, HIGH);
digitalWrite(r4, HIGH);
}
void row2()
{
digitalWrite(r1, HIGH);
digitalWrite(r2, LOW);
digitalWrite(r3, HIGH);
digitalWrite(r4, HIGH);
}
void row3()
{
digitalWrite(r1, HIGH);
digitalWrite(r2, HIGH);
digitalWrite(r3, LOW);
digitalWrite(r4, HIGH);
}
void row4()
{
digitalWrite(r1, HIGH);
digitalWrite(r2, HIGH);
digitalWrite(r3, HIGH);
digitalWrite(r4, LOW);
}
void ReadRows()
{
colm1 = digitalRead(c1);
colm2 = digitalRead(c2);
colm3 = digitalRead(c3);
colm4 = digitalRead(c4);
}
char Return_Keypad_Values(void)
{
row1();
ReadRows();
delay(100);
if (colm1 == LOW)
{
Serial.println("1");
delay(200);
return '1';
}
else if (colm2 == LOW)
{
Serial.println("2");
delay(200);
return '2';
}
else if (colm3 == LOW)
{
Serial.println("3");
delay(200);
return '3';
}
else if (colm4 == LOW)
{
Serial.println("A");
delay(200);
return 'A';
}
row2();
ReadRows();
delay(100);
if (colm1 == LOW)
{
Serial.println("4");
delay(200);
return '4';
}
else if (colm2 == LOW)
{
Serial.println("5");
delay(200);
return '5';
}
else if (colm3 == LOW)
{
Serial.println("6");
delay(200);
return '6';
}
else if (colm4 == LOW)
{
Serial.println("B");
delay(200);
return 'B';
}
row3();
ReadRows();
delay(100);
if (colm1 == LOW)
{
Serial.println("7");
delay(200);
return '7';
}
else if (colm2 == LOW)
{
Serial.println("8");
delay(200);
return '8';
}
else if (colm3 == LOW)
{
Serial.println("9");
delay(200);
return '9';
}
else if (colm4 == LOW)
{
Serial.println("C");
delay(200);
return 'C';
}
row4();
ReadRows();
delay(100);
if (colm1 == LOW)
{
Serial.println("*");
delay(200);
return '*';
}
else if (colm2 == LOW)
{
Serial.println("0");
delay(200);
return '0';
}
else if (colm3 == LOW)
{
Serial.println("#");
delay(200);
return '#';
}
else if (colm4 == LOW)
{
Serial.println("D");
delay(200);
return 'D';
}
return 'a';
}
/*************************************************************
LCD functions Ahead
*************************************************************/
//Print out the Heading On lCD
void print_head (String str)
{
u8g2.clearBuffer();
u8g2.setFont(u8g_font_unifont);
u8g2.setCursor(0, 15);
u8g2.print(str);
}
//Print secondary content on LCD
void print_content (String str)
{
u8g2.setFont(u8g_font_unifont);
u8g2.setCursor(0, 15);
u8g2.print(str);
}
[/code]
А аффтар кода чо говорит?
аффтар кода не отвечает, и от авторского там много изменено.
Изначальный код работает на liquid crystal
Ну и ты хочешь на халяву чужой код под свой экран переделать, я так понимаю?
А вопрос в чем? "Не могу вывести" - это сообщение. Мы приняли, сочувствуем...
Если не поняли - это был как бы намек, что надо описать проблему подробнее, а то вникать в чужой код из 1000 строк вслепую и бесплатно... стимула нет :)
я понимаю, что тут сейчас набегут желающие заработать денег, но если бы я хотел кому то заплатить, перешел бы в соответствующий раздел. я не прошу переделывать код. а возможно лишь указать где ошибка.
вопрос в том. что не могу вывести информацию на этот дисплей. если ты хочешь заработать денег. извини но тебе не сюда. если ты можешь указать где моя ошибка и как ее исправить, я буду тебе благодарен и + тебе в карму.
я не прошу переделывать код. а возможно лишь указать где ошибка.
ну так помогите своим бесплатным помощникам - расскажите хотя бы, что не работает.
А иначе как вы себе представляете помощь? - кто-то должен собрать вашу схему, залить в МК код и протестировать? - и все это забесплатно?
ну так что, подробной диагностики - что именно и хотя бы в какой процедуре этой портянки глючит - мы не увидим?
Значит надо сначала написать свой скетч, в котором потренироваться в выводе на 1306, а потом, изучив принцип, встроить его в имеющийся. По аналогии.
на LCD дисплее выходит вся информация. это название оператора, при нажатии кнопки для ввода номера выходит строка куда вводить номер и соответственно сам вводимый номер. далее диалог вызова. при входящем звонке выводится на дисплей номер звонящего. а вот OLED просто молчит и не подает признаков жизни. возможно ему не хватает каких то строк, возможно я чего то не дописал в коде. я в ардуино новичек. через порт все работает.
1306 работает по аналогии. там такая же история. поэтому и обратился к форуму за помощью. просто написать код и вывести на него свою информацию я могу. а вот с этим кодом бьюсь уже не один месяц.
b707, в портянке по всей поверхности проблемы.
Потомушто вот, к примеру, "hello world" от U8G2:
u8g2.firstPage(); do { u8g2.setFont(u8g2_font_ncenB10_tr); u8g2.drawStr(0,24,"Hello World!"); } while ( u8g2.nextPage() );1306 работает по аналогии.
Нихрена подобного.
просто написать код и вывести на него свою информацию я могу.
сомневаюсь, иначе и ситуации "дисплей просто молчит" не было бы. Выводилась бы хоть что-то - пусть неправильно или не полностью, но выводилось.
А тут похоже, вы в принципе даже не пробовали работать с этим дисплеем - сразу халявы ждете
Дисплей завелся. пока ковыряю в коде дальше.
спасибо, дисплей завелся. ищу в коде как все скомпонавать на дисплее
вот она, помощь форума :)
Вот бы раньше самому так? - нет, пинок нужен
ведь форумы для этого и существуют.
но проблема полностью еще не решена.
ведь форумы для этого и существуют.
Да, неужели?
ведь форумы для этого и существуют.
Чтоб к чужому коду твои хотелки прикручивать, аха?
У меня предложение внести в правила форума:
"Если человек в течение первых двух недель после регистрации на форуме начинает учить старожилов, для чего предназначен форум, - банить такого без предупреждения."
господа старожилы. просьба не хамить. я помню форумы когда они только начали появляться и их на пост советском пространстве было всего несколько штук. а дата регистрации это всего лишь цифра. и попробуй прикинуть такой вариант, что был аккаунт и я его забыл. допускаешь такой вариант? желающие учить как, где и что. вам не в это ветку. здесь просьба помочь, а не учить жизни.
не учить жизни.
Почему? Вам же ничто не мешает учить нас для чего нужны форумы и в какую ветку нам всем следует пройти. Надеюсь, в этом случае Вас не удивит, если и мы попытаемся объяснить Вам, куда следует пройти Вам?
дата регистрации это всего лишь цифра. и попробуй прикинуть такой вариант, что был аккаунт и я его забыл. допускаешь такой вариант?
конечно допускаю, тут регулярно появляются люди со сроком регистрации и 3 и 5 лет назад - и при этом дуб дубом. Дата регистрации ничего не гарантирует.
Но вас тут гнобят не за дату, а за то что вы требуете от форума какой-то помощи, сами не показав ни малейшего признака, что вы что-то знаете и пытаетесь в чем-то разобраться. Типичный халявщик с чужим скетчем, ожидающий что ему сейчас все бросятся помогать дописывать чужой код.
Первая часть, до кодов - это как для тебя
https://arduino.ru/forum/programmirovanie/otobrazhenie-tekushchego-davleniya-i-davleniya-v-konkretnoe-vremya#comment-485357
ну и пунктики. Выбери свой.
это было сказано еще в #9