I would like some help to get this code to work. I am not an Arduino expert, I put this code together, but it doesn't work.
Reports error connecting to the traccar server.
#define TINY_GSM_MODEM_A7672X // Define o modem utilizado
#define TINY_GSM_RX_BUFFER 1024 // Tamanho do buffer de recepção
#include <HardwareSerial.h>
#include <TinyGsmClient.h>
#include <Wire.h>
#include <TinyGPS++.h>
#include <EthernetUdp.h>
// Configurações do modem
#define MODEM_RST_PIN 5
#define MODEM_PWRKEY_PIN 4
#define MODEM_POWER_ON_PIN 12
#define MODEM_TX_PIN 26
#define MODEM_RX_PIN 27
#define MODEM_DTR_PIN 25
#define MODEM_RI_PIN 33
// Configurações do GPS
#define GPS_TX_PIN 21
#define GPS_RX_PIN 22
// Configurações de rede
const char apn[] = "timbrasil.br"; // Substitua com o APN da sua operadora
const char user[] = "tim"; // Usuário do APN, se necessário
const char pass[] = "tim"; // Senha do APN, se necessário
const char server[] = "server???"; // Endereço do servidor Traccar
const int port = 5055; // Porta padrão do Traccar
// Objeto para comunicação com o modem
HardwareSerial SerialAT(1);
TinyGsm modem(SerialAT);
// Objeto para comunicação com o GPS
TinyGPSPlus gps;
HardwareSerial gpsSerial(2);
// Cliente para conexão ao servidor Traccar
TinyGsmClient client(modem);
void powerOnModem() {
// Ligar o modem
pinMode(MODEM_PWRKEY_PIN, OUTPUT);
pinMode(MODEM_POWER_ON_PIN, OUTPUT);
digitalWrite(MODEM_PWRKEY_PIN, HIGH);
digitalWrite(MODEM_POWER_ON_PIN, HIGH);
// Resetar o modem
pinMode(MODEM_RST_PIN, OUTPUT);
digitalWrite(MODEM_RST_PIN, LOW);
delay(100);
digitalWrite(MODEM_RST_PIN, HIGH);
delay(3000);
}
void setup() {
// Inicializar serial para depuração
Serial.begin(115200);
delay(10);
// Inicializar comunicação com o modem
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX_PIN, MODEM_TX_PIN);
delay(3000);
powerOnModem(); // Ligar o modem
// Inicializar comunicação com o GPS
gpsSerial.begin(9600, SERIAL_8N1, GPS_RX_PIN, GPS_TX_PIN);
//Teste
Serial.println("\n---Starting GPRS ---\n");
Serial.println("Connecting to: " + String(apn));
if (!modem.gprsConnect(apn, user, pass)) {
delay(10000);
return;
}
Serial.print("GPRS status: ");
if (modem.isGprsConnected()) {
Serial.println("GPRS connected");
} else {
Serial.println("GPRS not connected");
}
String ccid = modem.getSimCCID();
Serial.println("CCID: " + ccid);
String imei = modem.getIMEI();
Serial.println("IMEI: " + imei);
String cop = modem.getOperator();
Serial.println("Operator: " + cop);
IPAddress local = modem.localIP();
Serial.println("Local IP: " + String(local));
int csq = modem.getSignalQuality();
Serial.println("Signal quality: " + String(csq));
// Set up the GPRS connection
if (!modem.gprsConnect(apn, user, pass)) {
Serial.println("Failed to connect to GPRS");
// Handle the failure as needed
} else {
Serial.println("Connected to GPRS");
}
}
void loop() {
// Atualizar informações do GPS
while (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
}
// Verificar se há uma nova localização disponível
if (gps.location.isUpdated()) {
float latitude = gps.location.lat();
float longitude = gps.location.lng();
float speed = gps.speed.kmph();
// Conectar ao servidor Traccar com tentativas
bool serverConnected = false;
for (int i = 0; i < 3 && !serverConnected; i++) {
if (client.connect(server, port)) {
serverConnected = true;
Serial.println("Conectado ao servidor Traccar");
// Construir a string com os dados de localização
String url = String("GET /?id=") + "YOU_ID" + "&lat=" + latitude + "&lon=" + longitude + "&speed=" + speed + " HTTP/1.1\r\n";
url += String("Host: ") + server + "\r\n";
url += "Connection: close\r\n\r\n";
// Enviar a string ao servidor Traccar
client.print(url);
// Esperar a resposta do servidor
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
// Fechar a conexão
client.stop();
Serial.println("Dados enviados ao servidor Traccar");
} else {
Serial.println("Falha ao conectar ao servidor Traccar. Tentando novamente...");
delay(5000);
}
}
if (!serverConnected) {
Serial.println("Falha ao conectar ao servidor Traccar após múltiplas tentativas.");
}
}
delay(10000); // Esperar 10 segundos antes de enviar a próxima localização
}
//ttgo t call sim800l
#define TINY_GSM_MODEM_SIM800
#define SerialMon Serial
#define SerialGPRS Serial1
#define Serial_GPS Serial2
#define TINY_GSM_TEST_BATTERY true
#include <TinyGsmClient.h>
#include <TinyGPS++.h>
#include "utilities.h" // confg de inicializaçaão
static const uint32_t BAUD_RATE = 9600;
static const uint32_t GSM_RATE = 115200;
static const uint32_t GPS_RATE = 230400;
const unsigned long RESET_INTERVAL = 6UL * 60UL * 60UL * 1000UL; // 6 horas
const unsigned long SEND_INTERVAL = 1500;
const unsigned long RECONNECT_INTERVAL = 160000;
static unsigned long lastResetTime = 0;
static unsigned long lastSendTime = 0;
static unsigned long lastReconnectAttempt = 0;
#define APN "claro.com.br"
#define USER "claro"
#define PASS "claro"
const char deviceId[] = "739155";
const char server[] = "104xxxxxxx";
const int port = 5055;
TinyGsm modem(SerialGPRS);
TinyGsmClient client(modem);
TinyGPSPlus gps;
void connectGPRS()
{
const int maxAttempts = 5;
int attempt = 0;
while (attempt < maxAttempts)
{
if (modem.gprsConnect(APN, USER, PASS))
{
SerialMon.println("\nConectado!");
IPAddress local = modem.localIP();
SerialMon.println(local);
return;
}
else
{
attempt++;
SerialMon.print("Falha ao conectar. Tentativa ");
SerialMon.print(attempt);
SerialMon.print(" de ");
SerialMon.println(maxAttempts);
delay(5000);
}
}
SerialMon.println("Falha ao conectar após várias tentativas. Reiniciando...");
ESP.restart();
}
void resetModulo()
{
unsigned long currentTime = millis();
if (currentTime - lastResetTime >= RESET_INTERVAL)
{
SerialMon.println("Reiniciando ESP32...");
lastResetTime = currentTime;
ESP.restart();
}
}
void ledStatus()
{
pinMode(LED_GPIO, OUTPUT);
digitalWrite(LED_GPIO, LED_ON);
delay(500);
digitalWrite(LED_GPIO, LED_OFF);
}
float ajustaVelocidade(float speed) {
if (speed <= 3.00) {
return 0.00;
} else {
return speed;
}
}
void sendLocation()
{
if (millis() - lastSendTime > SEND_INTERVAL){
lastSendTime = millis();
// Verifica se o número de satélites é maior que 4
int satellites = gps.satellites.value();
if (satellites <= 4)
{
SerialMon.println("Poucos satélites conectados. Dados não enviados.");
return;
}
if (gps.location.isValid())
{
unsigned long timestamp = gps.time.value();
double latitude = gps.location.lat();
double longitude = gps.location.lng();
int satellites = gps.satellites.value();
float speed = ajustaVelocidade(gps.speed.kmph());
float course = gps.course.deg();
float altitude = gps.altitude.meters();
float battery = modem.getBattVoltage() / 1000.0F;
int rssi = modem.getSignalQuality();
unsigned long adjustedTimestamp = timestamp - (3 * 3600); // 3 horas em segundos
String url = "/?id=" + String(deviceId) +
"×tamp=" + String(adjustedTimestamp) +
"&lat=" + String(latitude, 6) +
"&lon=" + String(longitude, 6) +
"&sat=" + String(satellites) +
"&speed=" + String(speed, 1) +
"&bearing=" + String(course, 1) +
"&altitude=" + String(altitude, 1) +
"&battery=" + String(battery) +
"&rssi=" + String(rssi) +
"&ignition=1";
if (modem.isGprsConnected())
{
if (client.connect(server, port))
{
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Connection: close\r\n\r\n");
client.stop();
Serial.println("Dados enviados com sucesso.");
ledStatus();
}
else
{
Serial.println("Falha ao conectar ao servidor.");
}
}
Serial.println(url);
}
}
}
void setup()
{
SerialMon.begin(BAUD_RATE);
setupModem();
delay(10);
Serial_GPS.begin(GPS_RATE, SERIAL_8N1, GPS_RX, GPS_TX);
SerialMon.println("Inicializando GPS...");
delay(2000);
SerialGPRS.begin(GSM_RATE, SERIAL_8N1, MODEM_RX, MODEM_TX);
SerialMon.println("Inicializando GSM...");
delay(2000);
SerialMon.println("Restarting modem...");
modem.restart();
delay(1000);
SerialMon.print("Conectando a Internet... ");
connectGPRS();
}
void loop()
{
while (Serial_GPS.available() > 0)
{
gps.encode(Serial_GPS.read());
sendLocation();
}
if (!modem.isGprsConnected())
{
if (millis() - lastReconnectAttempt > RECONNECT_INTERVAL)
{
lastReconnectAttempt = millis();
SerialMon.println("Reconectando ao GPRS...");
connectGPRS();
}
}
resetModulo();
}
//utilities.h
#include <Wire.h>
#define MODEM_RST 5
#define MODEM_PWRKEY 4
#define MODEM_POWER_ON 23
#define MODEM_TX 27
#define MODEM_RX 26
#define GPS_RX 32
#define GPS_TX 33
#define I2C_SDA 21
#define I2C_SCL 22
#define LED_GPIO 13
#define LED_ON HIGH
#define LED_OFF LOW
#define IP5306_ADDR 0x75
#define IP5306_REG_SYS_CTL0 0x00
bool setPowerBoostKeepOn(int en)
{
Wire.beginTransmission(IP5306_ADDR);
Wire.write(IP5306_REG_SYS_CTL0);
if (en) {
Wire.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
} else {
Wire.write(0x35); // 0x37 is default reg value
}
return Wire.endTransmission() == 0;
}
void setupModem(){
Wire.begin(I2C_SDA, I2C_SCL, 400000);
bool isOk = setPowerBoostKeepOn(1);
SerialMon.println(String("Setting power ") + (isOk ? "OK" : "FAIL"));
#ifdef MODEM_RST
// Keep reset high
pinMode(MODEM_RST, OUTPUT);
digitalWrite(MODEM_RST, HIGH);
#endif
pinMode(MODEM_PWRKEY, OUTPUT);
pinMode(MODEM_POWER_ON, OUTPUT);
// Turn on the Modem power first
digitalWrite(MODEM_POWER_ON, HIGH);
// Pull down PWRKEY for more than 1 second according to manual requirements
digitalWrite(MODEM_PWRKEY, HIGH);
delay(100);
digitalWrite(MODEM_PWRKEY, LOW);
delay(1000);
digitalWrite(MODEM_PWRKEY, HIGH);
// Initialize the indicator as an output
pinMode(LED_GPIO, OUTPUT);
digitalWrite(LED_GPIO, LED_OFF);
}
I would like some help to get this code to work. I am not an Arduino expert, I put this code together, but it doesn't work.
Reports error connecting to the traccar server.