Using AI to write Arduino code

I am new in coding with arduino, actually I do not know coding. So I tried ai, firsy by Gemini, started ok, specially advice about hardware, coding in beginning ok, but with a little more hardware, it was bad. Here no different. it is a simple project, pemf voor health, slow buildup power, 2 minutes working time and slow depower, 1 minute rest, the build up again. Slow begin and start because of change of reflux of the coils. Want to adjust the amps, pulse and frequency, thats it. Tried here for days, his lines and mine are different many times, so i do not know to paste or delete, and this i have to do many many times, full of errors all the time, asked ai what to do. Says it can not read my code propperly, with excuse ;). So why you started this, ai can not make code properly. Can you help?

@wimtttt

Topic split from another topic. Please do not add your own questions to the end of other people's topics.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

AI is a tool unsuited for doing a task that you cannot do yourself.

Why?

Because it makes stuff up. And if you don't know enough about whatever it is you have asked it to do to be able to spot subtle, yet superficially well written nonsense, you won't be able to tell when it is just making stuff up.

If you want to use it as a sounding board for ideas that you're trying to flesh out, have at it. But remain skeptical of what it says. Ask it for sources. Ask it to back up its answers with references. Challenge it. Accept that its value may largely be in making you rethink your assumptions rather than presenting you with an accurate answer.

But if you try and use it as a shortcut substitute to learning, you will be disappointed. The old adage of "there is no royal road to learning" remains as true today as it ever was.

Would have to concur. AI, whatever flavour, like any tool, should be used as a supplement, not a substitute.

The only way you can use AI is if you know that the answer is valid or made up (yes it does that). The solution is to learn to program, after a couple years you will know the difference.

If you post your code here, one of us will try to clean it up. That does NOT mean it is correct or what you want, just that it compiles. To get it correct and what you want you need to communicate to us what that is. I don't know anyone who does that using a word salad, so use diagrams, pictures, short to the point communications. There are industry standard ways but if you don't know how to code then you will not know those methods either. See the problem/solution?

I have learned to use AI for some coding. It can write it MUCH faster than I can. BUT…I do not let it write code that is far more advanced (maybe slightly more advanced) than me. Because coding can get real complicated real fast for an occasional user, and I am an occasional user, I ask AI to keep it dumbed down a little. Or I write some code in my style and ask AI to style it the way I am doing it.

The key is to already know about coding, at least up to a certain point. That way you can read through it and find the flaws or ask the right questions. If AI messes up, it tends to mess up more trying to fix the mess up.

You can always show another AI the code a previous AI wrote and ask for opinions from the 2nd AI.

I concur with all of the above.

Good luck!

If you want to use AI, do this:

  1. Start small.
  2. Prompt the AI to write your first code.
  3. Read every line of that code, and verify that it is a valid line using the Arduino Language Reference.
  4. Return to step 2 until step 3 "reads" correctly.
  5. Test the code first by compiling, then by uploading and running.
  6. Return to step 2 until step 5 runs correctly.

Have no fear! What's the worst that can happen?
Fluxx Capacity - U-Con Gaming Convention

This movie and The Hunt for Red October are the two that I always have to watch if they’re on TV. Just can’t help myself.

Sorry but had to spread it out a bit, makes it easier to read and more appealing to readers.

Do you have a schmatic?
Can you post your code and explain what you want it to do?

Thanks.. Tom.... :smiley: :+1: :coffee: :australia:

Thank you sonofy, hitseeker,van der decker, scottcalv, xfpet, Tom George, I did not expect so much help.
I was ai almost calling names, then I asked him, it, to give me forum, and then when you get on a new forum, you get lost a bit. But here it is ok, thanks again, read it many times.
You can always show another AI the code a previous AI wrote and ask for opinions from the 2nd AI. : I did this, even a third ai, so now it is almost ready, just a little thing, but it is a pretty long code, 228 lines, so maybe you find some rubbish in it, must be.
I saw a coding lesson thing here, looked good, so that is plan next. Was told here to go to Arduino Language Reference (maybe someone can explain a bit about this), also I do not understand the copy links of code of ai here: should i paste it in my line, and the red part (-) automatically takes away those lines in my code? I did it by hand.
Relaxed to be here, ai Gemini gave me 6 bursts of my BTI-2, cost 2 Arduino One R3, but I am not a quiter. Anyway again, took me more than a week for those 228 lines, so writing it is much faster ;).

Here is my plan, i gave to Ai. The only thing that is not yet ok, maybe, is the pulsing potmeter, it is fixed, but ai said that my lcd, I should be soldering it, and thats right, numbers change when i touch them.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int dutyPin = A0; // Pot 1
const int mainFreqPin = A1; // Pot 2
const int powerPin = A3; // Pot 3
const int LPWM = 3;
const int RPWM = 5;

float smoothedFreq = 7.83;
int valDuty = 25;
int valPower = 127;
bool isRunning = true;
unsigned long lastPulseMicros = 0;
unsigned long lastDisp = 0;

void setup() {
Serial.begin(9600);
pinMode(LPWM, OUTPUT);
pinMode(RPWM, OUTPUT);
lcd.init();
lcd.backlight();
}

void loop() {
unsigned long nu = millis();
unsigned long nuMicros = micros();

// LEES POTMETERS
// Duty Cycle (D) via A0 - met extra stabiliteit
int rawA0 = analogRead(dutyPin);
delay(1); // Geef de ADC tijd om te schakelen
valDuty = map(rawA0, 0, 1023, 5, 50);

// Freq (F) via A1
int rawA1 = analogRead(mainFreqPin);
float f = (rawA1 / 1023.0) * 481.0 + 9.0;
smoothedFreq = (smoothedFreq * 0.9) + (f * 0.1);

// Power (P) via A3
valPower = map(analogRead(powerPin), 0, 1023, 0, 255);

// PULS GENERATOR
unsigned long period = 1000000.0 / smoothedFreq;
unsigned long onTime = (period * valDuty) / 100;
unsigned long cyclePos = nuMicros - lastPulseMicros;

if (cyclePos < onTime) {
analogWrite(RPWM, valPower); analogWrite(LPWM, 0);
} else if (cyclePos < period) {
analogWrite(LPWM, 0); analogWrite(RPWM, 0);
} else {
lastPulseMicros = nuMicros;
}

// DISPLAY
if (nu - lastDisp > 300) {
lastDisp = nu;
lcd.setCursor(0, 0);
lcd.print("F:"); lcd.print(smoothedFreq, 1);
lcd.print(" D:"); lcd.print(valDuty); lcd.print("% ");
lcd.setCursor(0, 1);
lcd.print("P:"); lcd.print((int)((valPower/255.0)*100)); lcd.print("% ");

// Debug naar PC
Serial.print("Raw A0: "); Serial.println(rawA0);

}
}

So, I want to make health better by pemf, 18 coils of 0.5mm 5m long I made in 2 series, in a blanket made. These coils give reflux voltage, when stopped suddenly, so slow start and stop in stopping , breaking etc.
So, 2 minutes of working time, doing 4 till 500 herz, depending on health things I wanna do, so this does potmeter 1, second potmeter should do pulse, can be 5 till 50%, in the latest it wil be more pitchy to get through my body cells.
Third potmeter is the amps, till 10 amps, otherwise coils get too hot . I got a button for the exact 7,83 herz, earth frequency. fixed, because i use much, and the potmeter is no accurate enough to do this.
second button is for pauze, and third for stopping, slow buildoff because of reflux. I got build in hardware safety, Gemini told me, by special diode, fuses, condensators ( big one because of reflux 4700, mF 2 of them on driver, 104 for inteference on all parts of the hardware).
Got Arduino Uno R3, BTI-2 (BTS 7960), Egbo LCD 1602+I2C, amp meter INA 228, maybe I gonna use this one, do not know yet, driver is 350 watts, 19 volt. Arduino is powered by 5 volt powerbank, stable and safe.
BTI-2 is not burning anymore, not because of reflux, but some faulty programing Gemini did and ai here fixed.

The code above I did not test yet, have to do some soldering first, but the code seems a bit short, so the coming here code I tested and was ok, but one potmeter changes amps and pulse simultaniously, and I want this to be separate, so that is plan next, maybe in the code above, but I am not sure

Very, Very curious about your findings, Greeting, Wim :)

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);

// --- PINS ---
const int fijnFreqPin = A0;
const int mainFreqPin = A1;
const int powerPin = A3; // De potmeter voor D en P
const int schuPin = 7;
const int stopPin = 8;
const int pausePin = 9;
const int LPWM = 3;
const int RPWM = 5;

// --- VARS ---
float smoothedFreq = 4.0;
int dutyCycle = 25; // Startwaarde
int actuelePower = 127; // Startwaarde
bool isSystemRunning = true;
bool richting = true;

int currentPhase = 0;
unsigned long phaseStartTime = 0;
unsigned long displayMillis = 0;
unsigned long vorigePulsMicros = 0;
unsigned long lastSerial = 0;
float powerMultiplier = 1.0;

const unsigned long WORK_PHASE = 120000;
const unsigned long TRANSITION_TIME = 5000;
const unsigned long BREAK_PHASE = 60000;

unsigned long lastStopPress = 0;
unsigned long lastPausePress = 0;
const unsigned long debounceTime = 300;
bool showStopMessage = false;
unsigned long stopMessageStart = 0;

void setup() {
Serial.begin(9600);
pinMode(schuPin, INPUT_PULLUP);
pinMode(stopPin, INPUT_PULLUP);
pinMode(pausePin, INPUT_PULLUP);
pinMode(LPWM, OUTPUT);
pinMode(RPWM, OUTPUT);

lcd.init();
lcd.backlight();
lcd.clear();
phaseStartTime = millis();
}

void startPuls() {
if (!isSystemRunning) return;
int outputPower = (float)actuelePower * powerMultiplier;
outputPower = constrain(outputPower, 0, 255);

if (richting) {
analogWrite(RPWM, outputPower);
analogWrite(LPWM, 0);
} else {
analogWrite(LPWM, 0);
analogWrite(RPWM, outputPower);
}
}

void stopPuls() {
analogWrite(LPWM, 0);
analogWrite(RPWM, 0);
}

void handlePhaseTransitions() {
if (!isSystemRunning) return;
unsigned long phaseElapsed = millis() - phaseStartTime;

if (currentPhase == 0 && phaseElapsed >= WORK_PHASE) { currentPhase = 1; phaseStartTime = millis(); }
else if (currentPhase == 1) {
powerMultiplier = 1.0 - ((float)phaseElapsed / TRANSITION_TIME);
if (powerMultiplier <= 0) { powerMultiplier = 0; currentPhase = 2; phaseStartTime = millis(); }
}
else if (currentPhase == 2 && phaseElapsed >= BREAK_PHASE) { currentPhase = 3; phaseStartTime = millis(); richting = !richting; }
else if (currentPhase == 3) {
powerMultiplier = (float)phaseElapsed / TRANSITION_TIME;
if (powerMultiplier >= 1.0) { powerMultiplier = 1.0; currentPhase = 0; phaseStartTime = millis(); }
}
}

void loop() {
unsigned long nuMillis = millis();
unsigned long nuMicros = micros();

handlePhaseTransitions();

// Knoppen checken
if (digitalRead(stopPin) == LOW && (nuMillis - lastStopPress > debounceTime)) {
lastStopPress = nuMillis;
isSystemRunning = !isSystemRunning;
if (!isSystemRunning) { stopPuls(); showStopMessage = true; stopMessageStart = nuMillis; lcd.clear(); lcd.print("STOPPED"); }
else { showStopMessage = false; phaseStartTime = nuMillis; currentPhase = 0; lcd.clear(); }
}

// Frequentie berekening
float doelFreq;
if (digitalRead(schuPin) == LOW) { doelFreq = 7.83; }
else {
doelFreq = (analogRead(mainFreqPin) / 1023.0) * 481.0 + 9.0;
doelFreq += ((analogRead(fijnFreqPin) - 512.0) / 512.0) * 5.0;
}
smoothedFreq = (smoothedFreq * 0.9) + (doelFreq * 0.1);

// --- HIER WORDT DE POTMETER A3 UITGELEZEN ---
int potA3 = analogRead(powerPin);
dutyCycle = map(potA3, 0, 1023, 5, 50); // D: 5% tot 50%
actuelePower = map(potA3, 0, 1023, 20, 255); // P: 20 tot 255 PWM

// Puls generatie
if (isSystemRunning && currentPhase != 2) {
unsigned long pulsInterval = 1000000.0 / smoothedFreq;
unsigned long aanTijd = (pulsInterval * dutyCycle) / 100;

if ((nuMicros - vorigePulsMicros) < aanTijd) { startPuls(); }
else if ((nuMicros - vorigePulsMicros) < pulsInterval) { stopPuls(); }
else { vorigePulsMicros = nuMicros; }

} else { stopPuls(); }

// Display update
if (nuMillis - displayMillis > 250) {
displayMillis = nuMillis;
if (!showStopMessage && isSystemRunning) {
lcd.setCursor(0, 0);
lcd.print("F:"); lcd.print(smoothedFreq, 1);
lcd.print(" D:"); lcd.print(dutyCycle);
lcd.print("% ");
lcd.setCursor(0, 1);
lcd.print("P:"); lcd.print((int)((actuelePower/255.0)*100));
lcd.print("% Ph:"); lcd.print(currentPhase);
lcd.print(richting ? " R " : " L ");
}
if (showStopMessage && (nuMillis - stopMessageStart > 1500)) { showStopMessage = false; lcd.clear(); }

// Debug naar Seriële monitor: draai aan de potmeter en kijk hier
Serial.print("Potmeter A3: "); Serial.print(potA3);
Serial.print(" | Duty: "); Serial.print(dutyCycle);
Serial.print(" | Power: "); Serial.println(actuelePower);

}
}
here is the good, allright working code, did not see it in the text, so now the

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

Please post your full sketch, using code tags when you do

Posting your code using code tags prevents parts of it being interpreted as HTML coding and makes it easier to copy for examination

In my experience the easiest way to tidy up the code and add the code tags is as follows

Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

It depends on what you want to do. 228 lines is not long. The professionals on here can probably figure out how to get it much smaller. Some challenge themselves to make it use as little storage as possible.

But for hobbiests?? My opinion is this: If it should have only taken 100 lines of code but your 228 works, then 228 lines is fine.

what was the AI asked to produce the code to do?

I build my hardware.

I prepare the working principles of my project and accordingly I prepare the codes. When I am lazy, I submit it to the ChatGPT for complete sketch.

I run the received sketch just making a quick look into it if the codes are in agreement with my submitted descriptions.

If it runs or not, later on, I study the codes carefully particulalrly for those lines that I could not have thought to write myself.

If used properly, ChatGPT can help to become a good programmer both in theory and practice.

Had to look this one up. Pulsed Electromagnetic Field (therapy)
Are you intending to code and build one of these?
Not something I'll be trying.
Comes with definite hazards for some individuals (Implanted Cardiac Devices)

Nothing terrible :slight_smile:

My project for Atmega2560 is now long 5493 lines in main part and 13300 in libraries which all I wrote (part of it are comments) and it is not finished yet :slight_smile:

Some problems just need more lines than other :stuck_out_tongue:

(and premature optimization is the root of all evil :slight_smile: )

https://docs.arduino.cc/language-reference/

Another tip: you can try to simulate your setup and code using Wokwi