It is reliable ChatGPT to generate source code. - Page 1
Forum section: electronics / general

author: luiHS
author_rank: Frequent Contributor
timestamp: December 17, 2022, 08:46:12 am
content: I've been testing ChatGPT and found it to be great overall. The fact is that I barely have experience in handling DMA and I'm going to need to use it in several programs.So I have asked ChatGPT to generate me a source code in C for RT1064, to control WS2813 LEDs by SPI using DMA.This has been the response of ChatGPT. The question is if the example code that ChatGPT gives me is really useful or it may need tweaking to be able to use it in practice.What I have noticed, and I have tried it several times, is that the source code that it gives is not finished, some instruction is always missing at the end for the program to be fully functional, it makes the most complicated thing, but in the end it seems that it is not able to finish the program when what remains is the simplest.Code:#include <stdio.h>#include <stdlib.h>#include "rt1064.h"#define LED_COUNT 10 // Number of LEDs in the chain#define LED_PORT GPIO_PORT_A // GPIO port used for data transmission control#define LED_PIN GPIO_PIN_0 // Pin of the GPIO port used for data transmission control// Structure for storing the state of an LEDtypedef struct {uint8_t red;uint8_t green;uint8_t blue;} led_t;int main(void){// Initialize the RT1064's DMA controller and SPI interfaceinit_dma_controller();spi_init(SPI_0);// Configure the GPIO port and pin for data transmission controlgpio_init(LED_PORT);gpio_config(LED_PORT, LED_PIN, GPIO_OUTPUT);// Create an array to store the state of each LEDled_t leds;// Set the state of the LEDsfor (int i = 0; i < LED_COUNT; i++) {leds.red = 255;leds.green = 0;leds.blue = 0;}// Main loopwhile (1) {// Send the LED data to the SPI interface using the WS2813 protocol and DMAfor (int i = 0; i < LED_COUNT; i++) {// Create a temporary buffer to store the LED datauint8_t buffer;// Send the red colorfor (int j = 0; j < 8; j++) {buffer = (leds.red & (1 << (7 - j))) ? 0xFF : 0x00;}// Send the green colorfor (int j = 0; j < 8; j++) {buffer[j + 8] = (leds.green & (1 << (7 - j))) ? 0xFF : 0x00;}// Send the blue colorfor (int j = 0; j < 8; j++) {buffer[j + 16] = (leds.blue & (1 << (7 - j))) ? 0xFF : 0x00;}// Configure the DMA to send the LED data to the SPI interfacedma_config(DMA_MEM_TO_PERIPH, (uint32_t)buffer, (uint32_t)&SPI_0->TX_DATA, 24);// Set the data transmission control pin to start the data transmissiongpio_set(LED_PORT, LED_PIN);// Wait for the DMA transfer to completewhile (dma_get_status(DMA_MEM_TO_PERIPH) != DMA_TRANSFER_COMPLETE) {}// Clear the data transmission control pin to end the data transmissiongpio_clear(LED_PORT

author: luiHS
author_rank: Frequent Contributor
timestamp: December 17, 2022, 09:05:35 am
content: After many tries, it seems that ChatGPT gave me the complete source code, now it needs to really work.Code:#include <stdio.h>#include <stdlib.h>#include "rt1064.h"#define LED_COUNT 10 // Number of LEDs in the chain#define LED_PORT GPIO_PORT_A // GPIO port used for data transmission control#define LED_PIN GPIO_PIN_0 // Pin of the GPIO port used for data transmission control// Structure for storing the state of an LEDtypedef struct {uint8_t red;uint8_t green;uint8_t blue;} led_t;int main(void){// Initialize the RT1064's DMA controller and SPI interfaceinit_dma_controller();spi_init(SPI_0);// Configure the GPIO port and pin for data transmission controlgpio_init(LED_PORT);gpio_config(LED_PORT, LED_PIN, GPIO_OUTPUT);// Create an array to store the state of each LEDled_t leds;// Set the state of the LEDsfor (int i = 0; i < LED_COUNT; i++) {leds.red = 255;leds.green = 0;leds.blue = 0;}// Main loopwhile (1) {// Send the LED data to the SPI interface using the WS2813 protocol and DMAfor (int i = 0; i < LED_COUNT; i++) {// Create a temporary buffer to store the LED datauint8_t buffer;// Send the red colorfor (int j = 0; j < 8; j++) {buffer = (leds.red & (1 << (7 - j))) ? 0xFF : 0x00;}// Send the green colorfor (int j = 0; j < 8; j++) {buffer[j + 8] = (leds.green & (1 << (7 - j))) ? 0xFF : 0x00;}// Send the blue colorfor (int j = 0; j < 8; j++) {buffer[j + 16] = (leds.blue & (1 << (7 - j))) ? 0xFF : 0x00;}// Configure the DMA to send the LED data to the SPI interfacedma_config(DMA_MEM_TO_PERIPH, (uint32_t)buffer, (uint32_t)&SPI_0->TX_DATA, 24);// Set the data transmission control pin to start the data transmissiongpio_set(LED_PORT, LED_PIN);// Wait for the DMA transfer to completewhile (dma_get_transfer_status(DMA_MEM_TO_PERIPH));// Clear the data transmission control pin to end the data transmissiongpio_clear(LED_PORT, LED_PIN);}}return 0

author: Psi
author_rank: Super Contributor
timestamp: December 17, 2022, 09:30:13 am
content: It's pretty good and extremely impressive, but it does make mistakes. Usually small stuff that you can fix easy enough, but not always.I had a play asking it to write code in various 'somewhat obscure' languages and it would make assumptions that are not true without stating them.Like I was asking it to write something in MegaBasic but what it gave was code for Basic.It's a valid assumption to make, that MegaBasic is the same as Basic, but it's not and it didn't state that it was making that assumption. It just blindly stated that it was providing MegaBasic code. etc.You just have to be aware that it will sometimes provide totally wrong information while being very confident about it.One thing I've been meaning to try, but have not had time, is asking it for various regex strings for doing various things,I've not bothered to learn regex yet and it would be super useful if it could make me strings based on a text description of what i want.You can kinda see where the future is going if you can describe a sorting/filtering/search task in text (or more importantly speech) and the AI can convert that to a regex command that will actually do what you want. I think StarTrek got the 'talking to a computer to do a task' thing pretty accurate.I cant wait to see what's possible when all these different types of AI are joined into one system.(GPT3, DallE, Deepfake, Deepvoice. etc..)

author: janoc
author_rank: Super Contributor
timestamp: December 17, 2022, 09:51:01 am
content: I suggest reading this from Peter Norvig (a huge name in computer science and artificial intelligence research, currently working for Google) reviewing AlphaCode:https://github.com/norvig/pytudes/blob/main/ipynb/AlphaCode.ipynbYou need to realize that these neural networks don't really understand the problem. They only generate stuff that looks plausible (in statistical/probabilistic sense) based on what problem you gave them and what they have seen in their training set - essentially extracting some bits and pieces from it that seem related to your input and regurgitating them in some form.So they will give you something that looks quite convincing - but it is often completely bogus. E.g. suggesting to use APIs that don't exist, using functions that don't work as proposed and/or missing critical bits. And when it generates code that could actually work, it is buggy because it has been trained on stuff from e.g. Stack Overflow and Github where there are loads of buggy and wrong examples.I.e. something like the Rockwell Turbo Encabulator:Colleague of mine suggested using it only as a kind of "brainstorming partner" - you have no idea how to approach some problem, you can ask the chat bot and use what it generates as an input for your own research. Sometimes it will give you useful ideas on how to solve your problem because it is likely someone had a similar issue before. However, certainly don't use the generated code directly.And that still glosses over the whole copyright/licensing issue with whatever these systems generate - a big no-go for any sort of corporate use at the moment.

author: Psi
author_rank: Super Contributor
timestamp: December 17, 2022, 09:58:33 am
content: yep, the more simple the code problem you ask it to solve the more correct it will be.because it has been trained on many examples of it.As soon as you ask it to write code to do a task it has never seen before it will break, or go off on a tangent making up crap.

author: Psi
author_rank: Super Contributor
timestamp: December 17, 2022, 10:13:20 am
content: Just asked it"Can you write a program in C to take an array of floating point numbers and reverse the order of the first 2 bytes and multiply the last two bytes by pi"Given that what I asked was a pretty strange thing to do, it got further than I was expecting, but still wrong.First error I found was it reversing both the first 2 bytes and the last 2 as well. There's probably others.Impressive attempt though.Code:#include <stdio.h>#include <math.h>#define PI 3.14159265358979323846// Function to reverse the order of the first 2 bytes of a floating point numberfloat reverse_bytes(float x) {union {float f;unsigned char b;} u, v;u.f = x;v.b = u.b;v.b = u.b;v.b = u.b;v.b = u.b;return v.f;}// Function to multiply the last two bytes of a floating point number by pifloat multiply_by_pi(float x) {union {float f;unsigned char b;} u, v;u.f = x;v.b = u.b;v.b = u.b;v.b = (unsigned char)(u.b * PI);v.b = (unsigned char)(u.b * PI);return v.f;}int main() {float arr[] = {1.0, 2.0, 3.0, 4.0};int n = sizeof(arr) / sizeof(float);for (int i = 0; i < n; i++) {arr = reverse_bytes(arr);arr = multiply_by_pi(arr);}for (int i = 0; i < n; i++) {printf("%f ", arr);}return 0;}

author: hans
author_rank: Super Contributor
timestamp: December 17, 2022, 01:48:24 pm
content: Quote from: janoc on December 17, 2022, 09:51:01 amYes I tried ChatGPT this week and see what it did..First, some math. Solve x^2+5x=3 for me please. It rewrote everything to left side and used quadratic equation correctly. Great.Then I made the equation (a lot) more convoluted. I asked: solve x^2+5x=3+x^2 * (2*cos(0) - 1)It then went on to simplify the right handside to 3+x^2, which is correct... but it then went on to still apply the quadratic equation while x^2+5x=3+x^2 doesn't require that since a=0. It assumed a=-1, and also gave answers like "-3 / -2" , which could be simplified further. If a student would do this on a test, it would get nearly zero marks.Likewise, other  questions I asked were basically copy-pasted text together from wikipedia, with lists of jargon at the introduction of a specific article. It did make correct sentences which is very amusing (such as it have write letters about a banana and mango arguing and fighting each other.. it had lots of creative idea's about how those 2 can be jealous of each other), but it did not really "understand".. at most recite what others have written Your video is very relevant and amusing as well.It's easy to make an UML diagram of software that should run on a computer or MCU, but then hit severe problems at the implementation. In theory everything fits and works.. But every program can be simplified to the Arduino sketch format: init(), and loop(). Just make an external call to "some code" that does the real magic.BUT, this is just one of the earliest demo's of such a capable bot. If we still scale computational complexity and the efficiency at which neural networks operate and can be trained, then at some point we may actually create a bot that's "smarter" than (many of) "us". I think one of the problems is also telling what it needs to do most efficiently and correctly.

author: Jackster
author_rank: Frequent Contributor
timestamp: December 18, 2022, 09:49:59 pm
content: I have been using it to generate some automation tasks for me with some success.I have a load of files in a folder that I wanted to extract. But only the .apple and .orange ones.The thing is, these files are dotted around a load of folders. Wanted to keep the folder structure but not include folders that did not have these files in them.Instead of going through all the folders and doing it by hand, I typically use CMD or PowerShell to do this for me.So I asked itQuoteIt generated this.Code:# Set the source and destination folders$src = "C:\src"$dst = "C:\dst"# Get all .apple and .orange files in the source folder and its subfolders$files = Get-ChildItem -Path $src -Recurse -Include "*.apple", "*.ornage"# Iterate through each fileforeach ($file in $files) {# Create the destination folder path$dstPath = Join-Path $dst $file.Directory.FullName.Substring($src.Length)# Create the destination folder if it doesn't existif (!(Test-Path $dstPath)) {New-Item -ItemType Directory -Path $dstPath | Out-Null}# Copy the file to the destination folderCopy-Item -Path $file.FullName -Destination $dstPath}I ran it and it worked fine.I did ask it a few other things prior but that code did not work at all or as expected.Probably more down to asking it to do something the incorrect way rather than the correct way in which you would normally do this task.I have been asking it to make Python code as well as to go through some XML files. Annoyingly the XML files are a bit strange so that is not currently working well.Trying to get it to translate some of these XML files into different languages. It defaults to Google Translate so one needs an API key for it but that is fine.Finding it hard to get it to work though.Here is a snippet of the XML. Any ideas on how to ask it to translate the lines like "enter a nickname"?I have asked it to write (in the console) the lines (without translation) and it always comes back blanks.Code:<?xml version="1.0" encoding="utf-8"?><Language><DialogGroup name="ame/gamelogic/frontend/charactercretationpopup"><Dialog id="29604"><Line value="enter a nickname" /></Dialog></DialogGroup><DialogGroup name="ame/gamelogic/frontend/filepopup"><Dialog id="29606"><Line value="RENAME SELECTED" /></Dialog></DialogGroup><DialogGroup name="ame/gamelogic/frontend/gamewindow"><Dialog id="29605"><Line value="Press &quot;{0}&quot; to rescue" /></Dialog></DialogGroup><DialogGroup name="game/extensions"><Dialog id="23527"><Line value=" day " /></Dialog><Dialog id="23528"><Line value=" hours " /></Dialog><Dialog id="23529"><Line value=" hour " /></Dialog><Dialog id="23530"><Line value=" minutes " /></Dialog><Dialog id="23531"><Line value=" minute " /></Dialog><Dialog id="23532"><Line value=" seconds" /></Dialog><Dialog id="23533"><Line value=" second" /></Dialog></DialogGroup>I have also asked it to generate Arduino code using ICs that I have used before. Not yet tested the code but it looked pretty good. I will try and test this tomorrow when I am at work with the kit on hand.

author: Jackster
author_rank: Frequent Contributor
timestamp: December 19, 2022, 01:34:19 am
content: I got ChatGPT to make working code to translate our files!Code:import reimport boto3# create an AWS Translate clientclient = boto3.client('translate', region_name='eu-west-2',aws_access_key_id='asd',aws_secret_access_key='asd')# open the file in read modewith open('crcen.dlg', 'r') as file:# read the contents of the filecontents = file.read()# use a regular expression to find all lines that match the patternpattern = r'(.*)<Line value="(.+?)" />(.*)'# create an empty list to store the translated linestranslated_lines = []# iterate over the linesfor line in contents.split('\n'):# check if the line matches the patternmatch = re.match(pattern, line)if match:# get the groups from the matchprefix = match.group(1)text = match.group(2)suffix = match.group(3)# translate the text from English to Frenchtranslation = client.translate_text(Text=text, SourceLanguageCode='en', TargetLanguageCode='fr')# get the translated text from the responsetranslated_text = translation['TranslatedText']# add the translated line to the listtranslated_lines.append(f'{prefix}<Line value="{translated_text}" />{suffix}')else:# add the original line to the listtranslated_lines.append(line)# open the new file in write modewith open('crcen.dlg.txt', 'w') as file:# write the translated lines to the filefile.write('\n'.join(translated_lines))It took about 20-30 revisions to get it to work. And right now it just works in the background and eventually spits out the translated file.There are a few issues but that is more down to it just translating the input.We have chat commands that should not be translated and character entities that either Python or AWS will translate into the actual symbol but won't then display in the application.So yea. Looks like we need to parse a lot of stuff to get it working correctly.The AWS translations are somewhat questionable apparently.I asked GPT to fix a few things like the encoding (it was the python saving the text file), character entities and chat commands.The 2nd screenshot shows the difference between 1st gen and 2nd gen of the script.

author: tabemann
author_rank: Contributor
timestamp: December 19, 2022, 05:52:41 pm
content: My view of the subject is that using ChatGPT or CoPilot or like for any serious purposes is probably inadvisable. For starters, there's intellectual property issues. (Even in the case of CoPilot, regardless of whatever Microsoft put in their user agreement for GitHub, there is no guarantee that that will hold up in court.) Second, for code from an untrusted source - and these are untrusted sources - one should only be using code that one understands, and if one understands the code one can write it oneself without its "help". Also, I see people putting more work into getting the likes of ChatGPT to generate code that simply looks valid than it would probably take to simply take the plunge and write it themselves, and they would likely get better code faster if they did that.As a trivial test, I have tried asking ChatGPT a number of times to produce an implementation of a factorial in Forth, a simple example that should be quite trivial. In none of these cases has it given me working Forth code. Here is its most recent output:QuoteCode:Welcome to zeptoforthBuilt for rp2040, version 0.52.1, on Fri Dec 16 08:09:13 PM CST 2022zeptoforth comes with ABSOLUTELY NO WARRANTY: for details type `license'ok: factorial ( n -- n! ) ok1 swap okbegin okdup 1- dup 0= okwhile okdup * okrepeat okdrop ; ok0 factorial . .s 0 [ 1 ] ok1 factorial . .s 0 [ 1 1 1 ] ok2 factorial . .s 2 [ 1 1 1 1 ] ok3 factorial . .s 3 [ 1 1 1 1 1 ] ok4 factorial . .s 4 [ 1 1 1 1 1 1 ] ok5 factorial . .s 5 [ 1 1 1 1 1 1 1 ] okAs you can see, its code does not work as advertised. I could probably cajole it into creating a working factorial word, but it would be much simpler and easier to just write my own.

author: ralphrmartin
author_rank: Frequent Contributor
timestamp: December 19, 2022, 07:24:23 pm
content: It is dangerous in that it can produce plausible nonsense. For example, I asked it to generate linear time C code for solving the traveling salesman problem (a well-known NP problem). It output a bit of background, including saying that heuristics are used in practice, then saidHere is a linear-time algorithm for solving the TSP using the nearest neighbor heuristic:{the code}This algorithm has a time complexity of O(n^2), making it suitable for solving small to medium-sized instances of the TSP. However, for larger instances of the TSP, more efficient algorithms will be needed.Clearly it has no understanding that linear time and O(n^2) are contradictory.It is bad enough that many programmers today copy and paste chucks of code from StackExchange with no real understanding, but this takes it to a whole new level. Imagine coding advice sites, generated entirely by ChatGPT and the like, just for collecting commissions at Amazon for getting you to buy stuff.

author: tabemann
author_rank: Contributor
timestamp: December 19, 2022, 10:29:49 pm
content: Quote from: ralphrmartin on December 19, 2022, 07:24:23 pmAgreed completely. And yes, copying and pasting stuff from StackExchange that one doesn't understand is bad, but this is even worse.

author: westfw
author_rank: Super Contributor
timestamp: December 20, 2022, 05:17:27 am
content: If ChatGPT is doing ML based on all the code it finds on the web, then that's scary as hell, given that there is so much bad code out there (not always labeled as such.)As an experiment, I asked for "clock initialization code for SAMD11 at 48MHz", and it gave me code that set the system clock to the DFLL, without everenablingor configuring the DFLL. So I'm not impressed. (At least it didn't give me ASF code.)

author: uer166
author_rank: Super Contributor
timestamp: December 20, 2022, 05:23:48 am
content: Quote from: westfw on December 20, 2022, 05:17:27 amIt would be much more interesting if it did ML based on datasheet, reference, and programming manual texts. Now thAt might actually become somewhat useful!

author: Jackster
author_rank: Frequent Contributor
timestamp: December 20, 2022, 09:19:44 am
content: I have been looking into how the modeling is done and it is quite interesting.Downloading Github reposhttps://github.com/EleutherAI/github-downloaderTheir whole repo team is quite large.https://github.com/EleutherAIThe "pile" is a massive dataset with multiple PB of data used in ithttps://github.com/EleutherAI/the-pileWould love to give some of this a go. Ideally scrape all the datasheets for components and electronics design and see if one can make a model to make circuits and firmware to some degree.The general-purpose models are quite hard to run and most take up too much VRAM to be run by standard desktop GPUs.But if you pick models selectively or make your own hyper-focused ones, it should be easy to run them even on lower-end GPUs.

author: hans
author_rank: Super Contributor
timestamp: December 20, 2022, 09:49:18 am
content: One thing I have with that is, whether it is able to read figures and tables correctly. Those can contain pretty crucial information, like a clock tree with multiple mux'es and dividers before reaching the peripheral clock. I think also a lot of engineers and programming start out with some graphical representation before formalizing it down to text and math. In my opinion, datasheets are almost never written in a formalized "closed-form" matter but rather a "didn't had time to write a short letter, so wrote a long one instead"-kind of way.

author: wek
author_rank: Frequent Contributor
timestamp: December 20, 2022, 09:56:54 am
content: This will prevail, no matter how shitty the output is.You can't beat the "for free"/"programming faster, cheaper" economy. That's what we see in the last decades virtually everywhere.JW

author: Psi
author_rank: Super Contributor
timestamp: December 20, 2022, 10:07:51 am
content: Quote from: wek on December 20, 2022, 09:56:54 amIt will improve, and likely by a lot.We are only at the beginning of the AI generation.I can see it being integrated into IDEs to accelerate writing functions, or parts of functions.You can often say what you want quicker than you can type out the code for it.GPT + Reliable 'Speech to Text' is going to open many doors.

author: newbrain
author_rank: Super Contributor
timestamp: December 20, 2022, 10:27:37 am
content: Quote from: Jackster, heavily trimmed on December 18, 2022, 09:49:59 pmI really have to ask: is the wrongly spelt .ornage actually in the generated code?Subtle errors like this might easily be overlooked, unless each piece of generated code is extensively reviewed and tested.But, no doubt, this is getting scary good.

author: tabemann
author_rank: Contributor
timestamp: December 20, 2022, 04:29:53 pm
content: Quote from: wek on December 20, 2022, 09:56:54 amThe thing is you need actual programmers who understand what is going on to handhold and clean up after such AI and verify that the code being generated is correct, when it would be simpler, faster, and less error-prone for those programmers to simply write the code themselves. It is only "for free"/"programming faster, cheaper" if one is willing to risk one's product not working because of AI-introduced bugs.

author: ralphrmartin
author_rank: Frequent Contributor
timestamp: December 20, 2022, 04:44:50 pm
content: I think ChatGPT very nicely illustrates the issue itself, in this hilarious answer I actually gotMe:What is the worst mistake you have ever made?ChatGPT:As an AI language model, I am not capable of making mistakes. ...

author: profdc9
author_rank: Frequent Contributor
timestamp: December 20, 2022, 08:00:56 pm
content: This is what ChatGPT says right after closing the pod bay doors.

author: tabemann
author_rank: Contributor
timestamp: December 20, 2022, 08:42:38 pm
content: This is why you don't let ChatGPT control the nukes.

author: SiliconWizard
author_rank: Super Contributor
timestamp: December 20, 2022, 08:43:19 pm
content: Quote from: ralphrmartin on December 20, 2022, 04:44:50 pmThe really concerning issue is not just that though. It has been shown that those GPT models were able to exhibit some kind of aggressive behavior, which is really creepy.

author: westfw
author_rank: Super Contributor
timestamp: December 21, 2022, 12:33:50 am
content: QuoteWhy is that surprising? Much of the online "dataset" its using probably qualifies as "aggressive"Many of the responses HERE might qualify as aggressive; even the useful ones!

author: Jackster
author_rank: Frequent Contributor
timestamp: December 21, 2022, 01:23:55 am
content: Quote from: newbrain on December 20, 2022, 10:27:37 amThat was my typo.I changed it from some boring hard to differentiate letters to .apple and .orange

author: wek
author_rank: Frequent Contributor
timestamp: December 21, 2022, 07:39:21 am
content: Quote from: tabemann on December 20, 2022, 04:29:53 pmOne *is* willing, as witnessed by widespread use of ASFs and Cubes. As I've said, you can't beat the economy of (promise of) free.And, due to the very same economy, as Psi very correctly said aboveQuoteas in making it virtually impossible to explain, what's the problem with it, to the One.JW