Using ChatGPT and Bing for Arduino

About this post

Arduino is a great platform for Makers to implement their own electronics projects. But sometimes programming the Arduino boards can be difficult – especially for beginners. This is where ChatGPT can help: As an intelligent chatbot, it can answer questions about Arduino programming, provide tips and advice, and respond to problems during project development. In this post, we will explore how ChatGPT and Arduino can work together to improve the Maker experience and reduce development time.

ChatGPT

The above paragraph was written by ChatGPT. I only specified that I would like to write a post about how ChatGPT can support Arduino users and asked for a brief introduction. Artificial intelligence is already very mature for such tasks.

No matter what you think of AI, it will come and permanently change our lives, just as the Internet did. However, this post will not be an ethical-moral discussion, but we will simply explore the question: What can ChatGPT already do in relation to the Arduino world today – and what not?

“The new” Bing (Microsoft’s chatbot) and ChatGPT are based on GPT. I have tried both, but put the emphasis on ChatGPT. Bard, the competitor from Google, was not yet available in Germany at the time of writing – exciting times are ahead.

By the way, the post image (brain with MCU) was also generated by an artificial intelligence, namely Dall⋅E 2. Only the lettering “Microcontroller” was added manually. In contrast to ChatGPT, Dall-E 2 is only available for a fee (approx. 10 euro cents per image or attempt).

What is ChatGPT?

Let us ask ChatGPT: What is ChatGPT, and how does it work?

ChatGPT is an artificial intelligence chatbot based on OpenAI’s GPT (Generative Pre-trained Transformer) architecture. ChatGPT is trained to hold human-like conversations in English and other languages.

ChatGPT’s functionality is based on machine learning and, in particular, Deep Learning methods. It has been pre-trained on large text corpora using transformer networks to learn language understanding and the ability to generate human-like responses.

When you talk to ChatGPT, it analyzes your input and uses its understanding of language and context to generate a response. These responses are based on the patterns and correlations discovered in the model’s training dataset.

Because ChatGPT has been trained on large amounts of data, it can handle a variety of topics and even provide specific information if it has sufficient knowledge in that area.

ChatGPT about ChatGPT

How can I try ChatGPT?

If you want to use ChatGPT, then sign up here. You will need to provide your email address and (for whatever reason) a phone number. Then think of a password, confirm the email address, and you’re ready to go. 

According to OpenAI, there may be waiting times when using the free version. However, I have not had this experience.

Note: ChatGPT has recently been banned for violations of data and youth protection laws in Italy. So, should you be worried? Everyone has to answer that for themselves. ChatGPT itself points out that you should not enter any sensitive data. My advice is to consider all questions to see if they could draw conclusions about you that you don’t want drawn.

How is Bing different?

Currently, ChatGPT works with GPT version 3.5. Bing, on the other hand, uses a customized version of GPT-4. I mainly tested ChatGPT, but asked some of the questions to Bing as well for comparison. Bing’s answers tended to be somewhat shorter, but they contained links to more detailed information more often. Otherwise, the results were similar in both positive and negative aspects.

Bing is conveniently accessible via the Edge browser. Just click on the round, blue Bing logo on the far right of the toolbar. Alternatively, there is a Bing app on Google Play.

A first sketch created by ChatGPT

Enough of the introductory words. Now let’s see what ChatGPT has to offer in terms of Arduino programming:

ChatGPT writes a blink sketch

ChatGPT provides nicely formatted code with comments and additional explanations. With the button “Copy Code” you can easily copy the sketch. A promising start, even if the creation of a Blink sketch doesn’t really require an AI, of course. 

The next level: Blink without millis()

To increase the difficulty a bit, I asked ChatGPT if it could provide me with a version of the sketch without delay(). Here is the result:

const int ledPin = 13;  // defines the LED pin number

unsigned long previousMillis = 0;  // Variable for storing the last milliseconds
const long interval = 1000;        // Blink-Interval in milliseconds

void setup() {
  pinMode(ledPin, OUTPUT);  // Set LED pin as output
}

void loop() {
  unsigned long currentMillis = millis();  // Stores the current milliseconds
  
  if (currentMillis - previousMillis >= interval) {  // Checks if the blink interval has elapsed
    previousMillis = currentMillis;  // Store the new milliseconds
    
    digitalWrite(ledPin, !digitalRead(ledPin));  // Toggles the LED (on/off)
  }
}

Additional comments from ChatGPT:

In this program, the millis() function is used to measure the blink interval. The variable previousMillis stores the time of the last blink, and the variable interval specifies the desired blink interval. In the loop-part, it is checked if the blink interval has elapsed by comparing the difference between the current and the previous milliseconds with the interval. When the flashing interval has been reached, the state of the LED is reversed. This will turn the LED on and off.

Cool! Apart from the fact that ChatGPT has halved the frequency, everything is correct. At this point, I felt a emerging euphoria.

Top level: Timer and PWM

Now we go one step further and check the capabilities of ChatGPT in relation to the Arduino timers and PWM. If you are interested in this not-so-simple topic, you can take a look at my posts about the Timer0/Timer2 and the Timer1.

Now my question about this: Could you please write me an Arduino program that generates a PWM signal with a frequency of 1 kilohertz and a duty cycle of 20 percent?

Answer: Yes, here is an example program that generates a PWM signal at pin 9 with a frequency of 1 kHz and a duty cycle of 20%:

void setup() {
  pinMode(9, OUTPUT);          // Sets pin 9 as output
  TCCR1A = _BV(COM1A1) | _BV(WGM11); // Sets PWM mode
  TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // Sets fast PWM mode and no prescaler
  OCR1A = 156;                 // Sets duty cycle to 20% (156 of 255)
}

void loop() {
  // No code necessary
}

Further comments from ChatGPT:

In this program, the pinMode function is used to set the digital pin 9 as output. Registers TCCR1A and TCCR1B are configured to set Timer1 to Fast PWM mode and invert the output to generate the PWM signal with a duty cycle of 20%. The OCR1A registers are set to 156, which corresponds to a duty cycle of 20% (156 out of 255). Since the PWM signal generation is done in the setup, no code is needed in the loop part.

This sketch does not work! Some aspects are correct:

  • Setting of the Fast PWM mode (14).
  • No prescaler.
  • Output at pin 9 (if there was an output signal!).

But there are also mistakes:

  • The calculation of the frequency and duty cycle.

And the statement that 156 out of 255 would result in a duty cycle of 20% is pretty gross nonsense.

Here we can see a problem with ChatGPT. Its answers sound like irrefutable facts, so you tend to believe everything. So don’t trust the AI blindly!

The correct code would be, by the way:

void setup() {
  pinMode(9, OUTPUT);          
  TCCR1A = _BV(COM1A1) | _BV(WGM11); 
  TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); 
  ICR1 = 15999;
  OCR1A = 3199;
}

void loop() {
  // No code needed
}

Only a small part is missing, but a very crucial one.

Timer and PWM – a bit simpler

Well, let’s make it a little easier for ChatGPT and see if it can help us with the timers and PWM after all.  To that end, I asked the following question: 

The following code produces a PWM signal with a duty cycle of 20% and a frequency of 1 kHz. Do you know how I need to change it to increase the Duty Cycle to 30% and increase the frequency to 8 kHz? <Here I have inserted the code from correct_timer_pwm.ino>.

ChatGPT’s response: Yes, I can help you change the code accordingly. Here is the corrected code with a DutyCycle of 30% and a frequency of 8 kHz:

void setup(){ 
  // Clear OC1A on Compare Match / Set OC1A at Bottom; Wave Form Generator: Fast PWM 14, Top = ICR1
  TCCR1A = (1<<COM1A1) + (1<<WGM11); 
  TCCR1B = (1<<WGM13) + (1<<WGM12) + (1<<CS10); // prescaler = none; 
  ICR1 = 1999; // 8 kHz = 16 MHz / (2 * 1 * 2000)
  OCR1A = 599; // 30% of 1999
  DDRB |= (1<<PB1);
} 

void loop() { 
  // do something else
}

In addition, ChatGPT still gave the following explanation:

The changes that have been made are:

  1. The value of ICR1 was set to 1999 to produce a frequency of 8 kHz. This value was calculated by dividing the desired frequency (8 kHz) by the clock frequency of the Arduino (16 MHz) and then subtracting from this value. The result (1999) was then set to ICR1.
  2. The value of OCR1A was set to 599 to generate a Duty Cycle of 30%. This value was calculated by multiplying the maximum counter value (1999) by the desired Duty Cycle (0.3). The result (599.7) was then rounded to the nearest integer and set to OCR1A.

With these changes, the sketch should generate the desired PWM signal.

The sketch is correct, but the additional explanations are not quite:

  • Not the desired frequency is divided by the clock frequency, but vice versa. And subtracted is only the 1.
  • 599 not the nearest integer value of 599.7. A rather minor flaw.

This example shows that it can be worthwhile to specify or rephrase questions once again.

Timer and PWM – ChatGPT learns!

A few days later, I re-entered the original question (PWM signal, 1 kHz, 20% duty cycle) into a new chat. This time I got:

int outputPin = 9; // PWM-Ausgangspin
int dutyCycle = 20; // Duty cycle in percent

void setup() {
  pinMode(outputPin, OUTPUT); // Set pin to "output"
  TCCR1A = _BV(COM1A1) | _BV(WGM11); // Set PWM mode
  TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS10); // Set prescaler to 1 and phase-correct PWM
  ICR1 = 1999; // Set Top to 1999 (1kHz)
}

void loop() {
  int duty = map(dutyCycle, 0, 100, 0, ICR1); // Calculate duty cycle value
  OCR1A = duty; // Set duty cycle value
}

The PWM frequency is not correct (8 kHz at 16 MHz system frequency), but the duty cycle is. Assigning the value of OCR1A in loop() only makes sense if you want to change it during runtime. But at least, the code is already considerably better than the one I had originally received. 

Debugging

ChatGPT can also debug programs. At least this works relatively well for syntax errors, i.e. incorrect spelling. In the case of semantic errors (code compiles, but the sketch doesn’t do what you wanted) it becomes more difficult because ChatGPT can of course only guess what you actually had in mind.

To test ChatGPT, I took a sketch from the Arduino examples and added four errors:

const int sensorMin = 0;      
const int sensorMax = 600;    

void setup() {
  // initialize serial communication:
  Serial.begin(9700);  // 1
}

void loop() {
  int sensoReading = analogRead(A0); // 2
  imt range = map(sensorReading, sensorMin, sensorMax, 0, 3);  // 3

  switch (range) {
    case 0:  
      Serial.println("dark");
      break;
    case 1:  
      Serial.println("dim");
      break;
    case 2:  
      Serial.println("medium");
      break;
    case 4:  // 4
      Serial.println("bright");
      break;
  }
  delay(1000); 
} 

Then I asked ChatGPT if it could help me find the errors. The answer was:

Yes, I can try to help you with the errors in your Arduino code.

Here are some problems I found in your code:

  1. The Serial.begin command should be 9600 instead of 9700 since this is the default baud rate for Arduino.
  2. “sensoReading” is misspelled. It should be “sensorReading”.
  3. The “int” in “int range” is misspelled. It should be “int” instead of “imt”.
  4. The case “4” should be “3” to match the number of cases in the switch statement.

Not bad! Errors 2 and 3 would be noticeable by an abort of the compilation. However, errors 1 and 4 would not be reported, so ChatGPT would have been a real help here.

Another error: division by zero

In the following sketch, we divide by zero:

void setup() {
  Serial.begin(9600);
  const int a = 2;
  const int b = 4;
  
  int c = 42/(2*a-b);
  Serial.print("c = ");
  Serial.println(c);
}

void loop() {}

I have asked ChatGPT to find the error. ChatGPT’s response:

The program has no obvious error, but it can cause a problem if the value of 2*a-b is zero because then a division by zero occurs and the program crashes. However, since a and b are declared as constants and have fixed values, this should not be a problem.

I.e. basically the problem “division by zero” was identified; however, ChatGPT did not recognize that “2*a – b” is zero in every case. The compiler of the Arduino IDE is smarter and gives a corresponding warning. 

Controlling modules

Using two examples, let’s now see if ChatGPT can also help with programming more complex, external components. For this, I chose two quite common sensor modules, namely the ultrasonic distance sensor HC-SR04 and the 9-axis sensor module MPU9250 (acceleration, gyroscope, magnetometer).

Example 1: HC-SR04

My question: Can you write me an Arduino program that measures the distance with a HC-SR04 once per second? If the distance falls below 1.5 meters, an LED at pin 7 should light up for half a second.

And here is the sketch from ChatGPT:

const int trigPin = 2;    // Definiert die Trig-Pin-Nummer
const int echoPin = 3;    // Defines the echo pin number
const int ledPin = 7;     // Defines the LED pin number

void setup() {
  pinMode(trigPin, OUTPUT);   // Sets the trig pin as OUTPUT
  pinMode(echoPin, INPUT);    // Sets the echo pin as INPUT
  pinMode(ledPin, OUTPUT);    // Sets the LED pin as OUTPUT
  Serial.begin(9600);         
}

void loop() {
  // Sends the ultrasonic impulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads duration of the echo signal
  long duration = pulseIn(echoPin, HIGH);
  
  // Calculates the distance base on the echo signal duration
  float distance = duration * 0.034 / 2;
  
  // Checks, if the distance is below 1.5 meters
  if (distance < 1.5) {
    digitalWrite(ledPin, HIGH);    // LED switched on
    delay(500);                    // Wait 0.5 seconds
    digitalWrite(ledPin, LOW);     // LED switched off
  }
  
  // Outputs the distance on the serial monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" m");
  
  // Wait 1 second
  delay(1000);
}

Not bad! The only mistake is that “distance” according to this calculation is in centimeters and not in meters as indicated. After pointing out the error to ChatGPT and asking for a revised version, I received a correct sketch.

Bing told me it would not be able to create a sketch for the HC-SR04. At least that was an honest answer!

Then I asked ChatGPT if it could supply me with a circuit for the sketch. As usual, ChatGPT started the answer with a confident “Yes, of course“. Here is the result:

                   +5V
                    |
                    |
                    R1
                    |
                    |
Trig --------------/\/\/\/\------------------- Arduino Pin 9
                    |
                    |
Echo --------------/\/\/\/\------------------- Arduino Pin 10
                    |
                    |
                    |                   R2
                    |                   |
                    |                   |
                    |                   LED
                    |                   |
                    |                   |
                    --------------------- Arduino Pin 7
                    |
                    |
                   GND

R1, R2 = ~200 ohms

Hmmm, well, let’s say I know roughly what is meant. Circuits are therefore not a mature feature.

Example 2: MPU9250

Next try, next question: Can you write me a program that determines the acceleration using an MPU9250?

Here is the answer from ChatGPT:

#include <Wire.h>
#include <MPU9250.h>

MPU9250 IMU;    // Creates an object of the MPU9250 class

void setup() {
  Serial.begin(9600);   // Starts serial communication with 9600 Baud
  Wire.begin();         // Starts the I2C communication
  IMU.setup();          // Initializes the MPU9250 sensor
}

void loop() {
  // Reads the accleration values from the MPU9250 sensor
  IMU.updateAccel();
  float ax = IMU.ax;
  float ay = IMU.ay;
  float az = IMU.az;
  
  // Outputs the acceleration values on the serial monitor
  Serial.print("Acceleration: ");
  Serial.print(ax);
  Serial.print(" m/s^2, ");
  Serial.print(ay);
  Serial.print(" m/s^2, ");
  Serial.print(az);
  Serial.println(" m/s^2");
  
  // Waits 100 milliseconds
  delay(100);
}

This is not really useful. The sketch is more of a generic code. I then asked a few follow-up questions, such as which MPU9250 library is meant. I got a concrete answer to this, but the library did not match the code. All further attempts to obtain a working program from ChatGPT by providing assistance also failed. 

SPI interfaces ESP32

Topic change. Question: Can you explain to me how to use both SPI interfaces of an ESP32?

Besides some general explanations, ChatGPT answered with an example sketch:

#include <SPI.h>

// define SPI pins for first interface
#define SCK1 14
#define MISO1 12
#define MOSI1 13
#define SS1 15

// define SPI pins for second interface
#define SCK2 18
#define MISO2 19
#define MOSI2 23
#define SS2 5

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

  // initialize the first SPI interface
  SPI.begin(SCK1, MISO1, MOSI1, SS1);
  SPI.setClockDivider(SPI_CLOCK_DIV2);

  // initialize the second SPI interface
  SPI.begin(SCK2, MISO2, MOSI2, SS2);
  SPI.setClockDivider(SPI_CLOCK_DIV2);
}

void loop() {
  // use the first SPI interface
  digitalWrite(SS1, LOW);
  SPI.transfer(0x55);
  digitalWrite(SS1, HIGH);

  // use the second SPI interface
  digitalWrite(SS2, LOW);
  SPI.transfer(0xAA);
  digitalWrite(SS2, HIGH);
  
  delay(1000);
}

 

Parts of the program are fine, but it also contains numerous errors. At least, it doesn’t work that way. It would take too long to go into the details here. If you’re interested in the topic, check out my post about the ESP32 or this example sketch on GitHub.

More general questions

During the realization of projects, questions may also arise that are not primarily about programming. 

MOSFET recommendation

Question: Can you recommend MOSFETs that I can switch directly with a microcontroller?

Response:

Yes, there are many MOSFETs that can be controlled with a microcontroller. Here are some MOSFETs you can consider:

  1. IRFZ44N – This is a popular N-channel MOSFET with a drain-to-source breakdown voltage of 55V and a maximum drain-source current of 49A. It is suitable for a wide range of applications, including motor control and power control.
  2. IRLZ44N – This is a similar MOSFET to the IRFZ44N, but with a lower resistance and gate voltage. It has a drain-to-source breakdown voltage of 55V and a maximum drain-source current of 47A.
  3. BSS138 – This is a small N-channel MOSFET suitable for low power and voltage applications. It has adrain-to-source breakdown voltage of 50V and a maximum drain-source current of 220mA.
  4. FQP30N06L – This is an N-channel MOSFET with a drain-to-source breakdown voltage of 60V and a maximum drain-source current of 32A. It also has a low on-resistance and is suitable for applications such as switching regulators and motor control.
  5. IRF3205 – This is an N-channel MOSFET with a drain-to-source breakdown voltage of 55V and a maximum drain-source current of 110A. It also has low on-resistance and is suitable for high-power applications such as switching regulators and power converters.

Before selecting a MOSFET, make sure that it meets the required specifications for your application and that it is also compatible with the gate voltage of your microcontroller.

The answer is not bad, but could be even better. Recommendations 2, 3 and 4 are flawless. Recommendations 1 (IRFZ44N) and 5 (IRF3205), on the other hand, are only suitable to a limited extent, since the limit for the gate voltage of 2-4 volts is quite high. For a 5 volt microcontroller this will work, for a 3.3 volt MCU it might fail. The recommendations IRLZ44N (1-2 volts), BSS138 (0.8 volts) and IRF3205 (1-2.5 V) are better. OK, finally, ChatGPT points out the gate voltage issue. But that’s precisely why I asked ChatGPT which MOSFETs are directly controllable with a microcontroller.

When asked what I should take for a 3.3 volt microcontroller, I received the recommendations IRLZ44N, BSS138 and IRF3708 – all good! So you have to ask your question as precisely and in detail as possible. There are fuzzy answers to fuzzy questions.

Miscellaneous

I came up with some more questions:

  • How does the data transmission via SPI work?
  • How much power does an Arduino supply?
  • What is the difference between LGT8F328P and ATmega328P?
  • How do I install an Arduino library?
  • Where can I find the API documentation for the ESP32?
  • How can I invert an electronic signal (High/Low)?

It would be a bit lengthy to go through all the answers in detail. In summary: The answers were all correct! Sometimes they might have been a bit superficial, but in those cases, follow-up questions helped. Many pluses for ChatGPT in this part!

Conclusion

My verdict on ChatGPT’s (and Bing’s) Arduino capabilities is mixed:

  • ChatGPT can be a help for programming, but the results are to be questioned critically. Getting a completely functional and correct program is a matter of luck. But at least you’ll get something to build on with a fairly high probability.
  • For general questions about Arduino you get compact answers from ChatGPT. In comparison, Google search requires you to gather information from multiple matches. In this respect, ChatGPT is extremely convenient. However, diversity is lost as ChatGPT makes a selection for you or gives a kind of “average answer”.
  • Beginners can especially benefit from ChatGPT. However, this group in particular will find it more difficult to identify incorrect answers. In addition, the learning effect is lower.
  • ChatGPT claims it can do everything. A little less self-confidence or overconfidence would be more appropriate.
  • Unlike real intelligence, ChatGPT does not ask queries to get more details. It tries to make the best of a question, even if it is inaccurate. In this way, the impression is created that the answer is correct in all cases. A human would ask for details or start his answer with “It depends on if …”.

But all bugs, limitations and gaps aside: I am quite impressed with what ChatGPT and Bing are already capable of. And I am convinced that we will see significant progress within a short period of time. It will be very exciting to follow the further development.

Appendix: back to the core competencies of ChatGPT

Finally, a bit of fun and the things ChatGPT is great at. I asked ChatGPT to write a funny poem about the Arduino in English. Here is the result:

ChatGPT poetry
ChatGPT poetry

Not 100% perfect, but almost. I couldn’t do that – and certainly not in a few seconds!

4 thoughts on “Using ChatGPT and Bing for Arduino

  1. Notes from Wolfgang on this comment: Since it contained a link to a commercial training offer for AI, I first deleted it. But now I decided to keep it because it’s a good example to show how it sounds when AI creates texts. I am pleased to read positive feedback, but this sounds too nice – sometime less is more. I have only deleted the link to the training. The training might be good, but I don’t want advertisement on my blog. Regards, Wolfgang

    “Your ChatGPT course is an absolute gem for anyone looking to harness the power of AI-driven conversations! 🌐🤖 The depth of knowledge and practical insights you’ve compiled is simply outstanding, making this course a must-have for both beginners and tech-savvy individuals.
    I was truly amazed by the way you’ve demystified the workings of ChatGPT. Your comprehensive modules, from understanding the architecture to optimizing interactions, provide a clear roadmap for anyone eager to create dynamic and engaging conversational agents.
    What sets your course apart is the hands-on approach you’ve taken. The interactive exercises and real-world examples give learners the chance to apply theoretical concepts in a meaningful way. This ‘learn by doing’ method not only accelerates the learning process but also boosts confidence in working with AI models.

    One of the most commendable aspects of your course is the focus on responsible AI use. Your section on addressing biases and ensuring ethical interactions is a testament to your commitment to shaping AI for positive outcomes, and it resonates deeply in an era where AI ethics are paramount.

    Thank you for creating a course that not only imparts knowledge but also empowers individuals to create AI-driven conversations that are meaningful and impactful. I’m thrilled to have gained these skills and can’t wait to see the innovative chatbots and applications that will emerge as a result of your expert guidance! 🚀🤯 https://……

  2. Thank you for your excellent presentation of ChatGPT’s power and limitations. Your limited results matched those of others across a much broader spectrum of tasks. Once you look past the hype about its fear inducing powers, you find a giant “copy-paste machine” with no fundamental understanding of Arduinos or anything else. And like other pseudo experts, it claims infallibility even when generating wrong results.

  3. I was also very impressed with programming capabilities. Not only in Arduino code but also in other languages like PicBasic Pro. I have asked him to make some geometry calculus simulations entering some variables. He wrote the program but when run the result was not valid. Then I asked why the result was invalid. Then he answered that I have not asked that variables requested should give a valid result….

    1. Funny 😊 . Thanks for sharing your experience! Good to see that it’s similar. Everything but perfect yet. However, I had much fun. And imagine what we will be possible in a few years.

Leave a Reply

Your email address will not be published. Required fields are marked *