Help me finish writing the code to a working state

I am new to C++ code development, so this code was written by GPT chat. I am making a project of an on-board computer based on arduino nano. I have a code but I can't remove errors from it. The compiler gives errors with copies and with speed calculation. Can you please help me and finish writing it to a working state, please. Я новичок в сфере разработки кода на с++, по этому этот код писал чат GPT. Я делаю проект бортового компьютера на основе ардуино нано. У меня есть код но я не могу убрать из него ошибки. Компилятор выдает ошибки со скобками и с расчётом скорости. Можете мне пожалуйста помочь и дописать его до рабочего состояния пожалуйста.

#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <TinyGPS++.h>
#include <MPU6050.h>
#include <SoftwareSerial.h>

#define SD_CS_PIN 10

Adafruit_BMP280 bmp; // Объект для BMP280
TinyGPSPlus gps; // Объект GPS
MPU6050 mpu; // Объект для MPU6050

SoftwareSerial sim800l(7, 8); // RX, TX для SIM800L
SoftwareSerial gpsSerial(3, 4); // RX, TX для GPS

File dataFile;

unsigned long lastDataTimestamp = 0;
unsigned long lastMessageTimestamp = 0;

void setup() {
    Serial.begin(9600);
    gpsSerial.begin(9600);
    sim800l.begin(9600);

    // Инициализация SD-карты
    if (!SD.begin(SD_CS_PIN)) {
        Serial.println("Ошибка инициализации SD-карты!");
        while (1);
    }

    // Инициализация BMP280
    if (!bmp.begin(0x76)) {
        Serial.println("Ошибка инициализации BMP280!");
        while (1);
    }

    // Инициализация MPU6050
    Wire.begin();
    mpu.initialize();
    if (!mpu.testConnection()) {
        Serial.println("Ошибка соединения с MPU6050!");
        while (1);
    }
}

void loop() {
    // Считывание GPS-данных
    while (gpsSerial.available() > 0) {
        gps.encode(gpsSerial.read());
    }

    // Считывание данных каждые 6 секунд
    if (millis() - lastDataTimestamp >= 6000) { 
        lastDataTimestamp = millis();
        float altitude = bmp.readAltitude(1013.25); 
        float temperature = bmp.readTemperature(); 
        float pressure = bmp.readPressure() / 100; 
        int16_t ax, ay, az, gx, gy, gz;
        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        float speed = calculateSpeed(ax, ay, az); // Ваша функция для расчета скорости

        // Формируем строку для записи на SD
        String dataString = String(altitude) + "," + String(temperature) + "," + String(pressure) + "," + String(speed);
        if (gps.location.isUpdated()) {
            dataString += "," + String(gps.location.lat(), 6) + "," + String(gps.location.lng(), 6);
        }

        // Запись данных в файл
        dataFile = SD.open("data.txt", FILE_WRITE);
        if (dataFile) {
            dataFile.println(dataString);
            dataFile.close();
        } else {
            Serial.println("Ошибка записи в файл!");
        }
        Serial.println(dataString);
    }

    // Отправка SMS каждые 20 секунд с координатами
    if (millis() - lastMessageTimestamp >= 20000) {
        lastMessageTimestamp = millis();
        if (gps.location.isUpdated()) {
            String coordinates = "Lat: " + String(gps.location.lat(), 6) + ", Lng: " + String(gps.location.lng(), 6);
            sendSMS(coordinates);
        }
    }
}

void sendSMS(String message) {
    sim800l.println("AT");
    delay(100);
    sim800l.println("AT+CMGF=1"); // Устанавливаем текстовый режим
    delay(100);
    sim800l.println("AT+CMGS=\"ВашНомерТелефона\""); // Замените на ваш номер
    delay(100);
    sim800l.println(message); // Сообщение
    delay(100);
    sim800l.write(26); // Ctrl+Z для отправки
    delay(1000);
}

Since ChatGPT wrote it get it to fix it. Otherwise spend a couple years studying programming and do it yourself.

  • When you asked GPT chat to fix it what did she/he say to do ?
1 Like

And that is why you fail.

As more than one wise man has said over the centuries, "There is no royal road to learning."

1 Like

TBH I stopped reading at this point.

TBH I will not be able to keep from looking into this matter, if only to see what kind of mess chatGPT has thrown up.

I have no life, this will pass for entertainment.

a7

2 Likes

There is only one error, if you can't fix that you need to consider another course.

I have already reviewed the code many times. I wrote other logic for calculating the speed. And yes, I know that the neural network writes raw codes. I rebuilt the code associated with the GSM module. And instead of helping, you start to hate me, yes, I write codes poorly on Arduino because I now have almost no time for any other field of activity due to my studies in the final year

Imagine how difficult it was when I was in school, no internet, just the library.

2 Likes

You tried to short cut by having ChatGPT write the code for you.

When that didn't work, you again tried to short cut by having others figure out the problems for you. And you didn't even have the common courtesy to show the errors you were encountering. Instead, you make others do the work to find out what they are.

There's a common theme here.

I'm going to help you: by not helping you. Life is hard. You've got to put in the work. No one else is going to do it for you. And until you start putting in the work... you're on your own.

2 Likes

I know HR reads social media when hiring these days, they also need to start reading these kinds of forums in order to determine character etc.

1 Like

The error in the code made by ChatGPT is so fundamental, you wonder how much trust you could put in the rest of the code it manufactured.

2 Likes

OR he simply didn't copy all the code.

No hate.

alto777

chatGPT can be fun, but I sure am glad I am neither a student or teacher. When a few suggestions can produce a fairly plausible essay on any topic, totally grammatically correct if a bit verbose, repetitive and obvsly not my work, I worry that we will find ppl holding down jobs they have no right to do.

It can't be our fault that your path is difficult and you find you have been fed, or bitten off, more than can be chewed.

Would you like going to the doctor and seeing her talking to chatGPT about that thing growing out the top of your head?

It seems you are trying to take a short cut, as has been said there isn't any. The fact that you may never need to write another computer program in your life does not make what you are doing different to cheating or plagiarism.


chatGPT

Constructive Feedback on Using AI Assistance in Problem Solving:

While it’s understandable to seek quick solutions, it’s important to remember that relying too heavily on AI for tasks like coding, writing, or problem-solving can have unintended consequences. AI tools, like ChatGPT, can be fun and offer helpful suggestions, but they don’t replace the value of genuine learning and hands-on experience. It’s crucial to engage with the material yourself to truly understand the concepts and build your skills.

While AI-generated content can appear plausible, it often lacks the nuance, originality, and depth that would come from a personal, thoughtful effort. Over time, this approach can lead to gaps in your knowledge and ultimately hinder your growth, whether it’s in coding, writing, or other fields.

If you’re finding the work overwhelming, it’s okay to seek help or clarification from your teachers or peers. They can provide the guidance needed to navigate challenges more effectively. However, relying on shortcuts that bypass this deeper engagement can lead to issues down the road—whether in school, at work, or in professional settings.

Think of it like this: just as we wouldn’t want a doctor or engineer relying solely on a tool without the necessary understanding, we shouldn’t expect to grow in a field without putting in the effort ourselves. Taking shortcuts might seem easier now, but it can impact long-term success and personal satisfaction.

The goal isn’t to discourage using AI as a resource, but rather to encourage a balance—using it as a tool to assist your learning, not replace it. The best way forward is to actively engage with the material, seek genuine understanding, and embrace the process, even when it feels challenging. It’s through overcoming these challenges that true growth occurs.

a7

1 Like

Hi @genius228

welcome to the arduino-Forum.
Well done to post your code as a code-section in your first posting.

You will get help if you throw away the whole code from
G)oofy P)lagiatarism T)ransScrapper

and start over with describing your project like explained in the linked tutorial below.

This requires to invest 20 minutes of your precious time to read how to speedup solving your problems.

Directly after registering you got presented informations how to speed up solving your problem.
You should really read it.

Ok ok I would like to ask you kind people to please help me and point out the mistakes that were made. And maybe we all just misunderstood each other, then I apologize because I am an ordinary Belarusian student who is finishing school and I am writing through a translator. I am not asking you to do my work for me, I just want you to help me and tell me what I am doing wrong

I asked what to do different

it seems GPT has added current information to its knowledge base.
But somehow it seems to me like it is just parroting what it has read online.
Still I am very ambivalent about the answer because it is - somehow - a pretty good summary.

My question at GPT
Hi ChatGPT. If I post code you (=chatGPT) created on the Arduino User Forum, I will be hated for it and will not receive any help. What do you suggest I do to get help?

This is the answer.
Hi! I'm sorry to hear that you had this experience. Here are some tips to help you get better help on the Arduino User Forum:

  1. Write your own code: Try to write the code yourself, even if you have difficulties. This shows that you have studied the topic.

  2. Describe the problem clearly: Explain exactly what problem you are having. What is not working? What error messages are you getting? The more specific you are, the easier it is for others to help you.

  3. Comment on code: When sharing code, comment on it to explain what you are trying to achieve. This helps others understand your thought process.

  4. Ask questions: Ask specific questions about the parts of the code that are unclear to you. Instead of just asking for help, ask about specific features or logic.

  5. Examples and references: If possible, link to tutorials or examples you've used. This shows that you've done your research.

  6. Patience and politeness: Be patient and polite in your requests. The community is made up of volunteers who are willing to help if they can.

  7. Accept feedback: When you receive feedback, be open to it and show that you're willing to learn from it.

By following these tips, you can increase the likelihood of getting help on the forum. Good luck!
as an exception the same text google-translated to belarussion
Klick on the triangle to unfold the text

answer in belarussian

Я спытаў, што зрабіць па-іншаму

здаецца, GPT дадаў актуальную інфармацыю ў сваю базу ведаў.
Але чамусьці мне здаецца, што ён проста паўтарае прачытанае ў інтэрнэце.
Тым не менш, я вельмі неадназначна стаўлюся да адказу, таму што гэта - так ці інакш - даволі добрае рэзюмэ.

Маё пытанне ў GPT
Прывітанне, ChatGPT. Калі я апублікую створаны вамі код (=chatGPT) на форуме карыстальнікаў Arduino, мяне будуць ненавідзець за гэта, і я не атрымаю ніякай дапамогі. Што вы прапануеце мне зрабіць, каб атрымаць дапамогу?

Гэта і ёсць адказ.
Прывітанне! Мне шкада чуць, што ў вас быў такі вопыт. Вось некалькі парад, якія дапамогуць вам атрымаць лепшую дапамогу на форуме карыстальнікаў Arduino:

Напішыце ўласны код: паспрабуйце напісаць код самастойна, нават калі ў вас узнікнуць цяжкасці. Гэта паказвае, што вы вывучылі тэму.

Дакладна апішыце праблему: дакладна растлумачце, якая ў вас праблема. Што не працуе? Якія паведамленні пра памылкі вы атрымліваеце? Чым больш вы канкрэтныя, тым лягчэй іншым вам дапамагчы.

Каментар да кода: калі вы абагульваеце код, каментуйце яго, каб растлумачыць, чаго вы спрабуеце дасягнуць. Гэта дапамагае іншым зразумець ваш працэс мыслення.

Задавайце пытанні: задавайце канкрэтныя пытанні аб частках кода, якія вам незразумелыя. Замест таго, каб проста прасіць аб дапамозе, спытайце аб канкрэтных асаблівасцях або логіцы.

Прыклады і спасылкі: калі магчыма, дайце спасылкі на падручнікі або прыклады, якія вы выкарыстоўвалі. Гэта паказвае, што вы зрабілі сваё даследаванне.

Цярплівасць і ветлівасць: Будзьце цярплівыя і ветлівыя ў сваіх просьбах. Суполка складаецца з валанцёраў, якія гатовы дапамагчы, калі могуць.

Прымайце зваротную сувязь: Калі вы атрымліваеце зваротную сувязь, будзьце адкрытыя да яе і пакажыце, што вы гатовыя вучыцца ў іх.

Выконваючы гэтыя парады, вы можаце павялічыць верагоднасць атрымання дапамогі на форуме. Поспехаў!

best regards Stefan

3 Likes

I vote that as the answer of the year. It's what everyone wants to say but is afraid of getting banned or at least chastised. BRAVO!!!

What do you mean?

I believe @sonofcy is referring to chatGPT's response to @StefanL38's prompt, the part obvsly written not by him following

This is the answer.

a7

You are doing "wrong" to demonstrate too less own effort.

You should at least

  • post the error that you get if you compile your code
  • having done a quick google-research with the exact error-message of the compiler
  • asking at least one specific question after having read two or three google-hits found by googling the error-message