.st0{fill:#FFFFFF;}

Technology

ChatGPT, my new lab assistant 

 April 27, 2023

By  Peter

Join Our Mailing List

We publish fresh content each week. Read how-to's on Arduino, ESP32, KiCad, Node-RED, drones and more. Listen to interviews. Learn about new tech with our comprehensive reviews. Get discount offers for our courses and books. Interact with our community.

One email per week, no spam, unsubscribe at any time.

There is a lot of excitement around artificial intelligence, but none is more talked about than the ChatGPT chatbox from OpenAI.

What is so amazing, exciting, and even scary about GPT (OpenAI’s artificial intelligence system) and ChatGPT (an implementation of GPT as a chatbot with which you can have a conversation) is that GPT can deal with a very wide range of topics.

Most people are familiar with narrow AI, which can recognise a face in a video feed or detect spam in your email.

But GPT, and ChatGPT as one of its implementations, is more like Star Trek’s computer that can have normal conversations with a human, understand requests, and provide expert-level responses and actions.

I have been playing with the freely available ChatGPT chatbot for several weeks, and last week I decided to upgrade to the paid version to try out GPT-4.

Table of contents

Jump to a section of this post…

I have been using ChatGPT to help me with everyday research tasks, especially with Ruby programming. I have been using Ruby for many years, but not recently. My Ruby knowledge is a bit rusty, and I needed help. ChatGPT quickly filled the blanks in my memory so I could continue with my tasks.

I have also been using ChatGPT to:

  1. Help me write poetry, and give me a critique of Homer’s Odyssey.
  2. Help me study for my RPL (Recreational Pilots License), especially with meteorological topics.
  3. Help me write some Arduino code (I’ll show you later).
  4. Figure out some C-language issues.
  5. Improve the quality of my pizza recipe.
  6. Re-wrap my tennis racket handle.
  7. Much more.

Every answer was correct (except for one, see below).

The quality of the responses and the speed blows me away. Yes, I could potentially use a search engine to find this information. However, the GPT model is next level because it can synthesise an answer that matches my question, rework that answer to improve it based on my responses and learn. A search engine, on the other hand, is simply a list of hits.

In this post, I want to share some of my conversations with ChatGPT. Most of the conversations are generated using GPT-3.5. In the end, I have a conversation about Arduino programming in which I compare GPT-3.5 with GPT-4 so you can see the difference.

Admitting a mistake

Something I have never seen a search engine do is admit a mistake. ChatGPT did this, as you can see below (using GPT-3.5, I have added bold emphasis to highlight GPT learning from its mistake):

Peter

What is the difference between ChatGPT and ChatGPT Plus?

ChatGPT

I'm sorry, but as an AI language model, I am not aware of a product called ChatGPT Plus. The GPT architecture has different versions, such as GPT-2 and GPT-3, with different capabilities and improvements in terms of language generation, but there is no official product or version called ChatGPT Plus. Can you provide more information or context about what you are referring to?

Peter

Yes, please see this: https://openai.com/blog/chatgpt-plus

ChatGPT

I apologize for my earlier response. You are correct, OpenAI has released a product called ChatGPT Plus.
ChatGPT Plus is an AI language model that is built on top of the GPT-3 architecture, with several enhancements that improve its conversational capabilities. These enhancements include a larger model size with more parameters, improved efficiency and speed, better multi-turn conversation handling, and improved control over the content and tone of the generated responses.
In summary, ChatGPT Plus is an advanced version of the GPT-3 language model that is specifically designed for conversational AI applications. It aims to provide more natural and engaging conversations by improving the model's ability to understand context, generate more human-like responses, and maintain longer and more coherent conversations.

Generating poetry

I asked ChatGPT to write a poem about God and the Word of God. This is something that I would never attempt myself as my brain is not wired for God stuff. However, my father (the poet in the family) is participating in a poetry competition, and this is the topic he was given to work on.

I posed this question to ChatGPT, and here is the answer (generated in around 5 seconds):

Peter

Can you write me a poem about God and the Word of God?

ChatGPT

In the beginning was the Word, 
A powerful force that stirred 
The void of nothingness to life, 
And set the universe in strife.

This Word was with God from the start,
A part of Him, yet set apart,
A perfect expression of His will,
Through whom all things were made to fill.

And so this Word became our guide,
A lamp unto our feet to bide,
A light to lead us through the night,
And keep us from the path of blight.

In every page of Holy Writ,
The Word of God does always sit,
A living, breathing testament,
To the love that He has sent.

And as we read each sacred line,
We find our souls in grace entwine,
With the One who spoke the Word,
And all of life's sweetest chords.

So let us heed the Word of God,
And let it guide our every nod,
For in its pages we will find,
A love that's always true and kind.

I don’t know much about poetry.

However, when I compare ChatGPT’s poem to other poetry about God, I can’t say I see much difference.

It seems that the AI can write abstract poetry at least at a level that the layperson (like me) can recognise as such.

Critiquing literature

While I was having a cultured conversation with ChatGPT, I asked it about its opinion on Homer’s Odyssey. I read the book as a kid, and I was curious to know what my new lab assistant thought about it.

Peter

Can you give me a critique of the Odyssey by Homer?

ChatGPT

The Odyssey, an epic poem by the ancient Greek poet Homer, is a timeless work of literature that continues to captivate readers to this day. It tells the story of the hero Odysseus and his ten-year journey home after the Trojan War. Here are some of the key elements that make The Odyssey a remarkable work of literature:

1. Narrative Structure: The Odyssey is structured as a series of episodic adventures, as Odysseus travels through various lands and encounters a wide range of characters, gods, and monsters. This episodic structure creates a sense of suspense and adventure, and keeps the reader engaged throughout the lengthy poem.

2. Characterization: Homer is a master of characterization, and the characters in The Odyssey are richly drawn and complex. Odysseus himself is a flawed hero, with strengths and weaknesses that make him relatable and compelling. Other characters, such as the seductive Circe and the loyal swineherd Eumaeus, are also well-developed and memorable.

3. Themes: The Odyssey explores a number of important themes, including the nature of heroism, the power of temptation, and the importance of hospitality. The poem also grapples with the relationship between mortals and the gods, and the role of fate and destiny in human life.

4. Language: Homer's use of language is one of the most striking elements of The Odyssey. His vivid descriptions of landscapes, characters, and action create a vivid and immersive world for the reader. His use of repetition, epithets, and other poetic devices also contributes to the poem's musicality and beauty.

Overall, The Odyssey is a masterpiece of epic poetry that has stood the test of time. Its rich characters, exciting adventures, and profound themes continue to inspire and entertain readers today.

Blown. Away. Movie and literature critics should retrain.

Studying meteorology

I am studying for a Recreational Pilots License (a lifelong obsession with flight) and asked ChatGPT for some help with meteorology. Here are a few questions and answers from the relevant discussion. As you can see, my questions are straightforward, and so are the answers from my assistant. I had to do zero scrolling through lists.

Peter

Are you familiar with meteorology?

ChatGPT

Yes, I am familiar with meteorology. Meteorology is the scientific study of the atmosphere and its phenomena, with a primary focus on weather forecasting. Meteorologists use a combination of observation, data collection, and computer models to analyze and predict weather patterns. They study various atmospheric properties, such as temperature, humidity, air pressure, and wind patterns, to better understand how weather systems develop and change over time. If you have any questions about meteorology or related topics, feel free to ask!

Peter

What is virga?

ChatGPT

Virga is a meteorological term referring to precipitation, usually rain or snow, that evaporates or sublimates before reaching the ground. This phenomenon often occurs when precipitation falls from a cloud into a layer of dry air below. As the precipitation descends through the drier air, it evaporates or sublimates (in the case of snow), creating streaks or wispy trails extending downward from the cloud base.

Virga is typically visible from a distance and can be a sign of unstable atmospheric conditions. It is often associated with localized downdrafts, which can lead to the formation of microbursts, sudden, intense gusts of wind that pose a hazard to aviation.

Peter

What is Advection fog?

ChatGPT

Advection fog is a type of fog that forms when warm, moist air moves horizontally over a cooler surface, such as land or water. The temperature difference between the warm air and the cold surface causes the air to cool down to its dew point, resulting in the condensation of water vapor and the formation of fog.

Advection fog is common in coastal areas where warm, moist air from the ocean moves over colder landmasses. It can also form over cold ocean currents when warm air moves over the colder water. Advection fog differs from radiation fog, which forms when the ground cools down due to radiative heat loss during clear, calm nights, causing the air above it to cool down and reach its dew point.

Advection fog can be quite persistent, especially when there is little to no wind to disperse it, and it can lead to reduced visibility, posing a hazard to transportation, including aviation, maritime, and road traffic.

My lab assistant’s straight and detailed answers helped me complete the module much faster than if I had to use Google to find answers to the same questions.

Making a pizza

I believe that my pizzas are amazing. However, I recognise that there is always room for improvement. So, I asked my lab assistant for its recommendation. My only complaint is that ChatGPT did not include a recipe for the dough (although I didn’t ask for it). The “secret” of Napolitana pizza is in the quality of the dough, the oven, and, of course, the tomato paste.

Peter

I'm planning to have pizza Napolitana for lunch. Can you recommend a simple recipe?

ChatGPT

Sure! Here's a simple recipe for Pizza Napolitana. This recipe makes a classic Margherita pizza, which is the base for the Napolitana style.

Ingredients:

   - 1 pizza dough (store-bought or homemade)
   - 1/2 cup tomato sauce (preferably San Marzano tomatoes)
   - 1 tablespoon extra-virgin olive oil
   - 1/2 teaspoon salt
   - 1/4 teaspoon freshly ground black pepper
   - 1/2 teaspoon dried oregano (optional)
   - 1 clove garlic, minced (optional)
   - 1 cup fresh mozzarella cheese, thinly sliced
   - A handful of fresh basil leaves
   - 1 tablespoon grated Parmesan cheese (optional)

Instructions:

    1. Prepare the pizza dough: If you're using store-bought dough, follow the instructions on the package for preparation. If you're making your own pizza dough, prepare and let it rise according to your preferred recipe.

    2. Preheat your oven to 500°F (260°C) or as high as it will go. If you have a pizza stone or baking steel, place it in the oven while it preheats.

    3. Make the tomato sauce: In a small bowl, mix together the tomato sauce, olive oil, salt, black pepper, oregano (if using), and minced garlic (if using). Set aside.

    4. Shape the pizza dough: On a lightly floured surface, roll out the pizza dough into a thin, round shape, about 12 inches (30 cm) in diameter.

    5. Assemble the pizza: If you're using a pizza stone or baking steel, transfer the rolled-out dough onto a piece of parchment paper. If you're using a baking sheet, transfer the dough onto the greased sheet. Spread the tomato sauce evenly over the dough, leaving a small border around the edges. Distribute the mozzarella slices over the sauce.

    6. Bake the pizza: Transfer the pizza (with the parchment paper, if using a pizza stone or baking steel) onto the preheated pizza stone or baking sheet. Bake for 8-12 minutes, or until the crust is golden and the cheese is melted and bubbly.

    7. Finish and serve: Remove the pizza from the oven and let it cool for a couple of minutes. Scatter the fresh basil leaves over the pizza and sprinkle with grated Parmesan cheese, if desired. Slice and enjoy your Pizza Napolitana!

Keep in mind that the Napolitana style pizza is known for its simple ingredients and flavors. Feel free to add other toppings if you like, but the classic Margherita pizza is a great starting point.

I find GPT’s last statement intriguing. Not only did it explain how to make the pizza, but it also drew my attention to the need for simplicity. Do not overstuff your pizza with stuff!

My pizza is top-class. But how long before AI can make the best pizza on the planet?

Ruby playground

Ruby is my favourite programming language. Unfortunately, I don’t have the opportunity to use it much. Python and Arduino C dominate my programming.

However, I am working on an internal project using Ruby. In this project, I have to write several Ruby scripts to help me move and transform data between several remote applications. Being a “rusty” Rubyist, I asked ChatGPT for some assistance. I needed a quick refresher in parsing JSON documents, doing HTTP requests, working with hashes, iterating, working with remote APIs, and much more.

My assistant wrote functioning code for me and provided details about how that code worked. When using GPT-4, this code was also fully annotated.

Here are some examples of our conversations.

Peter

In ruby, how can I search for a string inside another string?

ChatGPT

In Ruby, you can search for a string inside another string using the String#include? method or regular expressions. Here are examples of both methods:
# Using the String#include? method
string1 = "The quick brown fox"
string2 = "brown"

if string1.include?(string2)
  puts "String2 is found in string1"
else
  puts "String2 is not found in string1"
end
In this example, we define two string variables string1 and string2. We then use the String#include? method to check if string2 is included in string1. If string2 is found inside string1, the message "String2 is found in string1" is printed to the console. Otherwise, the message "String2 is not found in string1" is printed.

Alternatively, you can use regular expressions to search for a string inside another string. Here is an example:
# Using regular expressions
string1 = "The quick brown fox"
string2 = /brown/

if string1 =~ string2
  puts "String2 is found in string1"
else
  puts "String2 is not found in string1"
end
In this example, we define two string variables string1 and string2. We create a regular expression string2 that matches the string "brown". We then use the =~ operator to check if string2 is found inside string1. If string2 is found inside string1, the message "String2 is found in string1" is printed to the console. Otherwise, the message "String2 is not found in string1" is printed.

Note that using regular expressions provides more flexibility in searching for a pattern inside a string, but it is also more complex than using the String#include? method.

Wow, that’s incredible. I feel like I’m working with a human Rubyist who patiently explains to me how the language works for my specific needs. See some more:

Peter

In Ruby, how can I convert an email address into a user name that does not contain special characters?

ChatGPT

In Ruby, you can convert an email address into a username without special characters by using regular expressions and string manipulation methods. Here is an example:
email = "[email protected]"

# Extract the username from the email address
username = email.split("@")[0]

# Remove all non-alphanumeric characters from the username
username = username.gsub(/[^0-9a-zA-Z]/, '')

puts username  # Output: "johndoe"
In this example, we start by defining an email address string email. We then extract the username from the email address by splitting the string at the "@" character using the String#split method and taking the first element of the resulting array.

Next, we use the String#gsub method to remove all non-alphanumeric characters from the username. The regular expression /[^0-9a-zA-Z]/ matches any character that is not a number or letter, and the gsub method replaces all instances of this pattern with an empty string.

The resulting username string contains only alphanumeric characters and can be used as a clean and safe username.

Note that this method may not work correctly for all email addresses, as some email providers allow special characters in the username part of the address. It is always a good idea to test your code with a variety of input data to ensure that it behaves correctly in all cases.

Peter

How can i create a random string in ruby?

ChatGPT

In Ruby, you can create a random string using a combination of the SecureRandom module and the Array#sample method. Here is an example:
require 'securerandom'

# Generate a random string of length n
def generate_random_string(n)
  chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
  Array.new(n) { chars.sample }.join
end

# Usage example: generate a random string of length 10
random_string = generate_random_string(10)
puts random_string
In this example, we define a method called generate_random_string that takes an integer parameter n specifying the desired length of the string. Inside the method, we create an array chars that contains all the characters we want to include in the random string. We then use the Array#sample method to randomly select n characters from this array and join them together into a string using the Array#join method.

The SecureRandom module provides a way to generate random numbers and strings using a cryptographically secure random number generator. It is recommended to use SecureRandom instead of the built-in rand method for generating random strings when security is a concern.

Note that you can customize the characters that are included in the chars array to generate a string with specific requirements, such as including only uppercase letters or digits.

Peter

In Ruby, how can I search for a key anywhere inside a Hash?

ChatGPT

In Ruby, if you want to search for a key anywhere inside a Hash (including nested hashes), you can create a recursive function to traverse the hash structure. Here's a function that searches for a key and returns its value if found:
def deep_find_key(hash, key_to_find)
  hash.each do |key, value|
    return value if key == key_to_find
    if value.is_a?(Hash)
      result = deep_find_key(value, key_to_find)
      return result if result
    elsif value.is_a?(Array)
      value.each do |item|
        if item.is_a?(Hash)
          result = deep_find_key(item, key_to_find)
          return result if result
        end
      end
    end
  end
  nil
end
This deep_find_key function accepts a hash and a key to find. It iterates through the hash, checking each key-value pair. If the key matches the key you're searching for, it returns the corresponding value. If the value is another hash or an array containing hashes, the function calls itself recursively to continue the search.

Here's an example of how to use the deep_find_key function:
nested_hash = {
  a: 1,
  b: {
    c: 2,
    d: {
      e: 3,
      f: 4
    }
  },
  g: [
    { h: 5 },
    { i: 6 }
  ]
}

puts deep_find_key(nested_hash, :a) # Output: 1
puts deep_find_key(nested_hash, :e) # Output: 3
puts deep_find_key(nested_hash, :h) # Output: 5
puts deep_find_key(nested_hash, :z) # Output: (nothing, as the key was not found)
This example demonstrates searching for various keys in a nested hash. The deep_find_key function returns the value associated with the key if found, or nil if the key is not found.

This code, mostly without modification, is now part of my project. I would have written this code without GPT’s assistance, but it would have taken much longer as I needed to look up the details in books and Google.

But the best of my (so far) interactions with ChatGPT was when I asked it to write some Arduino C code for me. See below.

Iterate through Arduino code – GPT-3.5 & GPT-4

Already positively impressed what ChatGPT, I decided to use it to write some Arduino code. But unlike my Ruby questions, I was going to ask ChatGPT to write and improve code with each of my questions this time. The idea is to start with a simple program and then add features.

Also, I wanted to ask GPT about hardware wiring instead of only programming questions.

In the first set of examples, I’m using GPT-3.5. Then, I repeated the same questions with GPT-4.

(To the right, you can see my interaction with ChatGPT in its native UI. Click to see a full-size image).

Peter

Hello, are you familiar with the Arduino platform?

ChatGPT (GPT-3.5)

Yes, I am familiar with the Arduino platform. The Arduino is an open-source electronics platform based on easy-to-use hardware and software that is designed for artists, designers, hobbyists, and anyone interested in creating interactive objects or environments. The platform consists of a microcontroller board, an integrated development environment (IDE) for programming the board, and a community of users who share their projects and code. Arduino boards are widely used in DIY projects, robotics, home automation, and many other fields.

ChatGPT (GPT-4)

Yes, I am familiar with the Arduino platform. Arduino is an open-source electronics platform based on easy-to-use hardware and software. It is designed for hobbyists, artists, designers, and anyone interested in creating interactive objects or environments. Arduino boards are microcontroller-based development boards that can be programmed using the Arduino Integrated Development Environment (IDE) and the Arduino programming language, which is a simplified version of C/C++. The platform has a large community that develops and shares libraries, making it easier for beginners to get started with various projects, including robotics, home automation, and more.

Peter

Can you give me a simple example of an Arduino program that controls an LED?

ChatGPT (GPT-3.5)

Certainly! Here's an example program that uses an Arduino to control an LED connected to pin 13:
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}
In this program, the setup() function sets pin 13 to be an output pin using the pinMode() function. Then, in the loop() function, the LED is turned on by setting pin 13 to HIGH using the digitalWrite() function. After a delay of 1000 milliseconds (1 second), the LED is turned off by setting pin 13 to LOW using digitalWrite() again. Another delay of 1000 milliseconds is added before the process repeats. This creates a simple blinking effect.

ChatGPT (GPT-4)

Certainly! Here's a simple Arduino program (sketch) that controls an LED connected to digital pin 13, which is typically the built-in LED on most Arduino boards. This example will blink the LED on and off with a 1-second interval.
// Pin number for the LED
const int ledPin = 13;

// The setup function runs once when the board is powered on or reset
void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
}

// The loop function runs continuously after setup()
void loop() {
  // Turn the LED on (HIGH is the voltage level)
  digitalWrite(ledPin, HIGH);
  // Wait for 1 second (1000 milliseconds)
  delay(1000);
  // Turn the LED off by making the voltage LOW
  digitalWrite(ledPin, LOW);
  // Wait for another second
  delay(1000);
}
To use this code:

    1. Open the Arduino IDE.
    2. Create a new sketch and copy-paste the code above.
    3. Connect your Arduino board to your computer via USB.
    4. In the IDE, go to the "Tools" menu and select the correct board and port.
    5. Click the "Upload" button (arrow icon) to compile and upload the code to your Arduino board.

Once the code is uploaded, the LED connected to pin 13 should start blinking on and off every second.

Peter

Can you modify the example so I can control the LED on/off period using a potentiometer?

ChatGPT (GPT-3.5)

Sure! Here's an example program that uses a potentiometer connected to analog pin A0 to control the on/off period of an LED connected to pin 13:
int potPin = A0;  // the analog pin the potentiometer is connected to
int ledPin = 13;  // the digital pin the LED is connected to
int potVal;       // variable to store the potentiometer value
int onTime;       // variable to store the LED on time
int offTime;      // variable to store the LED off time

void setup() {
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // read the potentiometer value and map it to a range of 0-2000 milliseconds
  potVal = analogRead(potPin);
  onTime = map(potVal, 0, 1023, 0, 2000);
  offTime = 2000 - onTime;

  // turn on the LED for the specified on time
  digitalWrite(ledPin, HIGH);
  delay(onTime);

  // turn off the LED for the specified off time
  digitalWrite(ledPin, LOW);
  delay(offTime);
}
In this modified program, the potPin variable is set to the analog pin the potentiometer is connected to (A0 in this case), and the ledPin variable is set to the digital pin the LED is connected to (pin 13). In the setup() function, pin 13 is set to be an output pin using pinMode().

In the loop() function, the value of the potentiometer is read using analogRead() and stored in the potVal variable. The map() function is used to convert the potentiometer value from the range 0-1023 to a range of 0-2000 milliseconds, which is the maximum on/off period of the LED.

The onTime variable is set to the mapped potentiometer value, and the offTime variable is set to the remaining time (2000 milliseconds minus onTime).

The LED is turned on for the specified onTime using digitalWrite() and a delay, and then turned off for the specified offTime using digitalWrite() and another delay. The process then repeats with the updated on/off times.

ChatGPT (GPT-4)

Sure! In this modified example, we'll use a potentiometer to control the LED on/off period. Connect the potentiometer's middle pin (wiper) to an analog input pin (e.g., A0), and its other two pins to 5V and GND.

Here's the code for this setup:
// Pin number for the LED
const int ledPin = 13;
// Pin number for the potentiometer
const int potPin = A0;

// The setup function runs once when the board is powered on or reset
void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
}

// The loop function runs continuously after setup()
void loop() {
  // Read the potentiometer value (0 to 1023)
  int potValue = analogRead(potPin);
  // Map the potentiometer value to a range of 0 to 5000 milliseconds
  int delayTime = map(potValue, 0, 1023, 0, 5000);

  // Turn the LED on (HIGH is the voltage level)
  digitalWrite(ledPin, HIGH);
  // Wait for the mapped delay time
  delay(delayTime);
  // Turn the LED off by making the voltage LOW
  digitalWrite(ledPin, LOW);
  // Wait for the mapped delay time
  delay(delayTime);
}
This code reads the potentiometer value and maps it to a range of 0 to 5000 milliseconds, which is then used as the delay time for the LED on/off periods. As you turn the potentiometer, the LED blinking rate will change accordingly.

Follow the same steps as before to upload the code to your Arduino board, and you should be able to control the LED blinking rate using the potentiometer.

Peter

In the example above, can you change replace the delay function with a non-blocking alternative?

ChatGPT (GPT-3.5)

Yes, instead of using the delay() function, we can use a non-blocking timing approach using the millis() function. Here's an example program that uses a potentiometer connected to analog pin A0 to control the on/off period of an LED connected to pin 13, without using the delay() function:
int potPin = A0;     // the analog pin the potentiometer is connected to
int ledPin = 13;     // the digital pin the LED is connected to
int potVal;          // variable to store the potentiometer value
int onTime;          // variable to store the LED on time
int offTime;         // variable to store the LED off time
unsigned long prevTime; // variable to store the previous time

void setup() {
  pinMode(ledPin, OUTPUT);
  prevTime = millis();
}

void loop() {
  // read the potentiometer value and map it to a range of 0-2000 milliseconds
  potVal = analogRead(potPin);
  onTime = map(potVal, 0, 1023, 0, 2000);
  offTime = 2000 - onTime;

  // check if it's time to turn on the LED
  if (millis() - prevTime >= onTime) {
    digitalWrite(ledPin, HIGH);
    prevTime = millis();
  }

  // check if it's time to turn off the LED
  if (millis() - prevTime >= offTime) {
    digitalWrite(ledPin, LOW);
    prevTime = millis();
  }
}
In this modified program, the prevTime variable is used to keep track of the previous time that the LED state was changed. In the setup() function, prevTime is initialized to the current time using millis().

In the loop() function, the value of the potentiometer is read and mapped to the on/off time ranges as before. Instead of using delay(), we check whether it's time to turn the LED on or off by subtracting prevTime from millis() and comparing the result to the corresponding on/off time.

If the elapsed time since the last LED state change is greater than or equal to the onTime, the LED is turned on using digitalWrite() and prevTime is updated to the current time. Similarly, if the elapsed time since the last LED state change is greater than or equal to the offTime, the LED is turned off and prevTime is updated again. This process repeats indefinitely, allowing the program to run without blocking.

ChatGPT (GPT-4)

Certainly! You can replace the delay() function with a non-blocking alternative using the millis() function, which returns the number of milliseconds since the Arduino board started running the current program. This approach allows the program to continue running other tasks while waiting for the LED to turn on/off.

Here's the modified code:
// Pin number for the LED
const int ledPin = 13;
// Pin number for the potentiometer
const int potPin = A0;

// Variables for non-blocking delay
unsigned long previousMillis = 0;
unsigned long interval = 0;
bool ledState = false;

// The setup function runs once when the board is powered on or reset
void setup() {
  // Initialize the LED pin as an output
  pinMode(ledPin, OUTPUT);
}

// The loop function runs continuously after setup()
void loop() {
  // Read the potentiometer value (0 to 1023)
  int potValue = analogRead(potPin);
  // Map the potentiometer value to a range of 0 to 5000 milliseconds
  interval = map(potValue, 0, 1023, 0, 5000);

  // Get the current time
  unsigned long currentMillis = millis();

  // Check if it's time to change the LED state
  if (currentMillis - previousMillis >= interval) {
    // Save the last time the LED state was changed
    previousMillis = currentMillis;
    // Toggle the LED state
    ledState = !ledState;
    // Set the LED to the new state
    digitalWrite(ledPin, ledState ? HIGH : LOW);
  }

  // Other tasks can be performed here without being affected by the LED timing
}
In this code, we use the millis() function to track time and change the LED state without blocking other tasks. This allows you to run additional code in the loop without affecting the LED blinking rate controlled by the potentiometer.

Peter

In the program above, can you add a second LED that is on when the first LED is off and vice-versa?

ChatGPT (GPT-3.5)

Sure, we can modify the previous program to add a second LED that is on when the first LED is off and vice-versa. Here's an example program that uses a potentiometer connected to analog pin A0 to control the on/off period of two LEDs connected to pins 13 and 12:
int potPin = A0;     // the analog pin the potentiometer is connected to
int ledPin1 = 13;    // the digital pin the first LED is connected to
int ledPin2 = 12;    // the digital pin the second LED is connected to
int potVal;          // variable to store the potentiometer value
int onTime;          // variable to store the LED on time
int offTime;         // variable to store the LED off time
unsigned long prevTime; // variable to store the previous time
boolean led1State = true; // variable to store the state of the first LED

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  prevTime = millis();
}

void loop() {
  // read the potentiometer value and map it to a range of 0-2000 milliseconds
  potVal = analogRead(potPin);
  onTime = map(potVal, 0, 1023, 0, 2000);
  offTime = 2000 - onTime;

  // check if it's time to change the state of the LEDs
  if (millis() - prevTime >= (led1State ? onTime : offTime)) {
    digitalWrite(ledPin1, led1State ? HIGH : LOW);
    digitalWrite(ledPin2, led1State ? LOW : HIGH);
    led1State = !led1State;
    prevTime = millis();
  }
}
In this modified program, we added a second LED connected to pin 12, and a led1State boolean variable to keep track of the state of the first LED.

In the loop() function, we check whether it's time to change the state of the LEDs by subtracting prevTime from millis() and comparing the result to the corresponding on/off time for the current state of led1State. If the elapsed time since the last LED state change is greater than or equal to the current state's corresponding time, we update the state of both LEDs, toggle the led1State variable, and update prevTime to the current time. This allows the first LED to turn on/off while the second LED turns off/on accordingly. The process repeats indefinitely, allowing the program to run without blocking.

ChatGPT (GPT-4)

Sure! In this modified example, we'll add a second LED that turns on when the first LED is off and vice-versa. Connect the second LED's anode (positive) pin to a digital pin (e.g., 12) and its cathode (negative) pin to GND through a suitable resistor (220-ohm to 1k-ohm).

Here's the code for this setup:
// Pin numbers for the LEDs
const int ledPin1 = 13;
const int ledPin2 = 12;
// Pin number for the potentiometer
const int potPin = A0;

// Variables for non-blocking delay
unsigned long previousMillis = 0;
unsigned long interval = 0;
bool ledState = false;

// The setup function runs once when the board is powered on or reset
void setup() {
  // Initialize the LED pins as outputs
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
}

// The loop function runs continuously after setup()
void loop() {
  // Read the potentiometer value (0 to 1023)
  int potValue = analogRead(potPin);
  // Map the potentiometer value to a range of 0 to 5000 milliseconds
  interval = map(potValue, 0, 1023, 0, 5000);

  // Get the current time
  unsigned long currentMillis = millis();

  // Check if it's time to change the LED state
  if (currentMillis - previousMillis >= interval) {
    // Save the last time the LED state was changed
    previousMillis = currentMillis;
    // Toggle the LED state
    ledState = !ledState;
    //
This code adds a second LED and sets its state opposite to the first LED by swapping the HIGH and LOW values in the digitalWrite() function. When the first LED is on, the second LED is off and vice-versa. The potentiometer still controls the blinking rate of both LEDs.

Peter

Can you show me the wiring that will work with the program?

ChatGPT (GPT-3.5)

Sure! Here's a diagram that shows how to wire the Arduino board, potentiometer, and two LEDs for the program we just wrote:
               +5V
                |
                \
                /  10KΩ
                \
                |
               A0
                |
                .
                .
                .
                |
                |
               LED1 (pin 13)
                |
               220Ω
                |
               GND
                |
                |
               LED2 (pin 12)
                |
               220Ω
                |
               GND
In this diagram, the potentiometer is connected between the +5V and GND pins of the Arduino board, with its center pin connected to analog input pin A0. The two LEDs are connected to pins 13 and 12, each through a 220Ω resistor to limit the current. The program we wrote earlier will control the on/off periods of these two LEDs according to the potentiometer value. Make sure to double-check the wiring before uploading the program to your Arduino board!

ChatGPT (GPT-4)

Here's a simple wiring guide for the program with two LEDs and a potentiometer. I'll use an Arduino Uno as an example, but the wiring should be similar for other Arduino boards.

Components:

    1. Arduino Uno board
    2. LED 1 (connected to pin 13)
    3. LED 2 (connected to pin 12)
    4. Two resistors (220-ohm to 1k-ohm) for the LEDs
    5. Potentiometer (10k-ohm is common, but other values will also work)
    6. Breadboard
    7. Jumper wires

Wiring instructions:

    1. Connect the anode (longer leg) of LED 1 to digital pin 13 on the Arduino board, and its cathode (shorter leg) to one leg of a resistor.
    2. Connect the other leg of the resistor to a GND pin on the Arduino board.
    3. Connect the anode (longer leg) of LED 2 to digital pin 12 on the Arduino board, and its cathode (shorter leg) to one leg of another resistor.
    4. Connect the other leg of the resistor to a GND pin on the Arduino board.
    5. Connect one of the outer pins of the potentiometer to the 5V pin on the Arduino board.
    6. Connect the other outer pin of the potentiometer to another GND pin on the Arduino board.
    7. Connect the middle pin (wiper) of the potentiometer to the analog input pin A0 on the Arduino board.

With this setup, the Arduino board can control the two LEDs based on the potentiometer input. When LED 1 is on, LED 2 will be off, and vice-versa. The potentiometer controls the on/off period of both LEDs.

Peter

In the program above, can you add an LCD using the I2C backpack, so that the display shows the offTime value?

ChatGPT (GPT-3.5)

Sure! Here's an example program that uses a potentiometer connected to analog pin A0 to control the on/off period of two LEDs connected to pins 13 and 12, and displays the offTime value on an LCD connected to the I2C bus:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int potPin = A0;              // the analog pin the potentiometer is connected to
int ledPin1 = 13;             // the digital pin the first LED is connected to
int ledPin2 = 12;             // the digital pin the second LED is connected to
int potVal;                   // variable to store the potentiometer value
int onTime;                   // variable to store the LED on time
int offTime;                  // variable to store the LED off time
unsigned long prevTime;       // variable to store the previous time
boolean led1State = true;     // variable to store the state of the first LED
LiquidCrystal_I2C lcd(0x3F, 16, 2);  // initialize the LCD with the I2C address and dimensions

void setup() {
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  lcd.init();                // initialize the LCD
  lcd.backlight();           // turn on the LCD backlight
  prevTime = millis();
}

void loop() {
  // read the potentiometer value and map it to a range of 0-2000 milliseconds
  potVal = analogRead(potPin);
  onTime = map(potVal, 0, 1023, 0, 2000);
  offTime = 2000 - onTime;

  // check if it's time to change the state of the LEDs
  if (millis() - prevTime >= (led1State ? onTime : offTime)) {
    digitalWrite(ledPin1, led1State ? HIGH : LOW);
    digitalWrite(ledPin2, led1State ? LOW : HIGH);
    led1State = !led1State;
    prevTime = millis();
  }

  // update the LCD with the offTime value
  lcd.setCursor(0, 0);
  lcd.print("Off Time: ");
  lcd.print(offTime);
}
In this modified program, we added an #include directive to include the LiquidCrystal_I2C library for controlling the LCD via the I2C bus.

In the setup() function, we initialize the LCD with the I2C address (0x3F for the most common backpack) and dimensions (16 columns and 2 rows), and turn on the LCD backlight. We also initialize prevTime to the current time using millis().

In the loop() function, we update the LCD with the current offTime value by calling lcd.setCursor() to position the cursor to the first column of the first row, and then printing the string "Off Time: " and the value of offTime.

The rest of the program works the same way as before, with the on/off periods of the LEDs controlled by the potentiometer. The process repeats indefinitely, allowing the program to run without blocking.

ChatGPT (GPT-4)

Sure! To display the offTime value on an LCD with an I2C backpack, you'll need to use the "LiquidCrystal_I2C" library. If you don't have it already, you can install it from the Arduino Library Manager:

    1. Open the Arduino IDE.
    2. Go to Sketch > Include Library > Manage Libraries...
    3. Search for "LiquidCrystal I2C" by Frank de Brabander.
    4. Click Install.

Now, let's modify the code to display the offTime value on the LCD:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Pin numbers for the LEDs
const int ledPin1 = 13;
const int ledPin2 = 12;
// Pin number for the potentiometer
const int potPin = A0;

// Variables for non-blocking delay
unsigned long previousMillis = 0;
unsigned long interval = 0;
bool ledState = false;

// Initialize the LCD with the I2C address and dimensions (usually 0x27 for address and 16 columns x 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);

// The setup function runs once when the board is powered on or reset
void setup() {
  // Initialize the LED pins as outputs
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);

  // Initialize the LCD
  lcd.init();
  // Turn on the backlight
  lcd.backlight();
  // Print a static text on the first row
  lcd.setCursor(0, 0);
  lcd.print("OffTime: ");
}

// The loop function runs continuously after setup()
void loop() {
  // Read the potentiometer value (0 to 1023)
  int potValue = analogRead(potPin);
  // Map the potentiometer value to a range of 0 to 5000 milliseconds
  interval = map(potValue, 0, 1023, 0, 5000);

  // Get the current time
  unsigned long currentMillis = millis();

  // Check if it's time to change the LED state
  if (currentMillis - previousMillis >= interval) {
    // Save the last time the LED state was changed
    previousMillis = currentMillis;
    // Toggle the LED state
    ledState = !ledState;
    // Set the LEDs to the new state
    digitalWrite(ledPin1, ledState ? HIGH : LOW);
    digitalWrite(ledPin2, ledState ? LOW : HIGH);
  }

  // Update the offTime value on the LCD
  lcd.setCursor(8, 0);
  lcd.print(interval);
  lcd.print(" ms    "); // Optional: Clear any previous characters

  // Other tasks can be performed here without being affected by the LED timing
}
Make sure to connect the I2C backpack's SDA and SCL pins to the Arduino board's SDA (A4) and SCL (A5) pins, respectively, for an Arduino Uno. Also, connect the VCC and GND pins of the I2C backpack to the 5V and GND pins of the Arduino board.

This code initializes the LCD with the I2C backpack and displays the offTime value (interval) in milliseconds on the screen. The LCD will update the displayed value whenever the potentiometer is adjusted.

Peter

Thank you, you have been very helpful.

Conclusions (?)

I’m blown away by how GPT could accurately understand my intention and improve on its previous responses.

As an educational tool, I find GPT amazing.

While there may be errors in the code, its quality, combined with the detailed explanation and comments (especially in GPT-4), is probably better than any content I would produce on this topic. And, of course, let’s not forget that human educators and instructors always make mistakes. In my books and courses, I have to spend at least a quarter of my time fixing those mistakes.

What is (also) amazing about GPT and the new crop of general intelligence systems is that they can learn. They can learn faster and better than humans.

Let that sink in…

This means that perhaps it is time to move on in life and find something different to do.

It seems that GPT will be a better author of blog articles, tweets, and books. Perhaps it is just a matter of time before it is a better teacher than me (and most teachers, dare I say).

ChatGPT is patient, descriptive, and detailed.

It will not get tired. It will not judge. It will adapt to your needs as a student, as a human.

I am thinking about my interactions with ChatGPT. I can only compare them to one other similar tech experience: when I first interacted with the Internet and the Web in 1992, using a Sun Spark computer in my engineering school’s lab.

The Internet blew my mind then.

A world of information had opened up, even though I had to rely on paper publications of lists of new websites (this was before even Yahoo appeared). The pre-historic Internet impressed me because, intuitively, I felt it represented an inflection point in the story of the human race on this planet.

ChatGPT blew my mind in 2023, 30 years after my first encounter with the Internet.

For the same reason.

I strongly believe that in the next few years, we will see a proliferation of general Artificial Intelligence in every aspect of our lives, especially in education, business, and medicine (and yes, surveillance and the military).

ChatGPT or one of its competitors (let’s call it HAL) will be my teaching assistant, and perhaps it will take over my teaching.

My kids have used ChatGPT to write emails to their grandparents; these emails were extremely funny and creative. They convinced me that ChatGPT could also be a hilarious comedic author (without the profanities).

Once these tools connect with the rest of the Internet through plugins and connectors, their real power will be unleashed.

HAL will be my developer (I hope I can give it the specs for a new app, and it will do it).

HAL will be my brainstorming assistant for my business and my legal advisor.

HAL will be my doctor, psychologist, tennis coach, travel advisor, and marketer.

HAL will be my assistant, booking appointments, replying to emails, alerting me to opportunities, and fixing bugs in my books and courses. Heck, HAL might be able to create my books and courses based on my specs.

While DALLE-E2 can generate photorealistic images based on user specifications today, a (near) future version will be able to do the same for video. HAL will be able to not only edit my videos but also create them.

I am not ready to get into a philosophical introspection and discussion about what it means to be human; I still need to think more about all this. I, we, will have to do it sooner rather than later.

For the entire human history, creating things, thinking, writing, and communicating have been thought of as the attributes that made us human.

We are now beginning a new era where we share the world with another intelligence that can do the above and, arguably, many of them better than us.

I strongly doubt that it is possible to retract the dominant trend in AI, which is that it will continue to get smarter at an accelerating pace. No matter what will do, this trend will continue.

This means that we, humans, will have to find something else that makes us who we are (who are we, by the way?).

Well, I asked ChatGPT (GPT-4), and it gave me this answer (GPT-4):

The question of what it means to be human has been a topic of philosophical and scientific inquiry for centuries. At its core, being human is characterized by a range of attributes and behaviors that are unique to our species. 

Some of the defining characteristics of being human include:

1. Rationality: Humans are capable of higher-level thinking, abstract reasoning, and logical deduction.

2. Consciousness: Humans possess an awareness of their own existence and the ability to experience a wide range of emotions.

3. Creativity: Humans have a unique ability to create art, music, literature, and other forms of expression.

4. Sociality: Humans are social animals, living in complex communities and forming close relationships with others.

5. Language: Humans have a complex and highly developed system of communication, allowing for the transmission of knowledge and ideas across generations.

6. Morality: Humans have a sense of right and wrong, and are capable of making moral judgments.

7. Self-awareness: Humans have a sense of self, and are able to reflect on their own thoughts and feelings.

Ultimately, being human is a multifaceted and complex concept that defies easy definition. It is the combination of these various attributes and behaviors that make us uniquely human.

Much of that I see in the new wave of general artificial intelligence technologies. This is squeezing humans into a smaller niche. Hopefully, this niche will represent a much higher value for humans, so humans are still worth being around.

I am excited about the future in which human potential is further extended with the help of AI, just like the inventions of the Internet and the printing press did in previous centuries. I acknowledge that the stakes are much higher now because the new technology can think, and (soon) it will be able to do (perhaps with intent??).

Nothing like this has existed until now.

We should be careful.

But we should first strive to truly and deeply understand what AI is, what it can do for us, with and against us, and who we are as individuals and species.

Join the discussion

Have you been using an AI-powered chatbot?

What are your thoughts? Please elaborate!


Tags


You may also like

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Capacitors are fundamental components in electronic circuits, and understanding how they work is crucial for anyone looking to build and design their own circuits. In this segment, we’ll explore the various kinds of capacitors you

Read More
Introduction to Capacitors and RC Circuits

The Khadas VIM1S is a high-quality yet affordable single-board computer well suited to hobbyists’ needs. While it doesn’t have the power of its siblings, such as the Edge2, it strikes a fine balance between performance

Read More
Khadas VIM1S: Unbox, Set Up, and Review