Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 16:52 24 Nov 2024 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : PicoMite C-Subs...Does a tutorial exist?

     Page 1 of 3    
Author Message
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 01:40pm 16 Sep 2024
Copy link to clipboard 
Print this post

Did I see one or did I dream it?  
 
Volhout
Guru

Joined: 05/03/2018
Location: Netherlands
Posts: 4222
Posted: 01:50pm 16 Sep 2024
Copy link to clipboard 
Print this post

https://www.thebackshed.com/forum/ViewTopic.php?FID=16&TID=14126#174926

Volhout
PicomiteVGA PETSCII ROBOTS
 
JohnS
Guru

Joined: 18/11/2011
Location: United Kingdom
Posts: 3800
Posted: 03:18pm 16 Sep 2024
Copy link to clipboard 
Print this post

You may need the PicoCFunctions.h from https://github.com/UKTailwind/PicoMiteAllVersions

John
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 04:29pm 16 Sep 2024
Copy link to clipboard 
Print this post

Thanks guys; got all excited about the possibility of running a CSUB on the other core   (but that was dated 2021)

OK, question; Assuming that I am able to get to the point of creating the actual CSUB, I'm not a C programmer (although not afraid to get into it)....

For the core logic, do you think that this could be a help?

I just installed it and looks pretty darned impressive.
 
twofingers
Guru

Joined: 02/06/2014
Location: Germany
Posts: 1240
Posted: 07:09pm 16 Sep 2024
Copy link to clipboard 
Print this post

Because I find it difficult to gather the information together, I asked ChatGPT (edited) to write an overview for the first development of CSubs.
I'm sure there are still small errors, but I think it is useful as a first overview:

  Quote  It's crucial to include the current header file, such as PicoCFunctions.h, in the C code when developing CSUBs for MMBasic on the PicoMite.

Here's an updated guide, incorporating these important points.

---

### Guide to Creating CSUBs for Geoff Graham's MMBasic on PicoMite

CSUBs allow you to write functions in C and use them within the MMBasic environment on the PicoMite. This is particularly useful for tasks requiring higher performance than MMBasic can provide on its own.

---

### Prerequisites:
1. PicoMite running MMBasic.
2. ARM C Compiler (e.g., gcc-arm-none-eabi).
(https://www.thebackshed.com/forum/ViewTopic.php?FID=16&TID=14126#174926)
3. ArmCfGenV144.bas or CFGEN.bas to convert compiled ELF files to CSUBs (likely developed by TassyJim ?).
4. The PicoCFunctions.h header file.
5. A text editor or IDE for writing C code.
6. A batch script for automating the compilation and conversion process (optional).

---

### Step 1: Write the C Code

When writing the C code for a CSUB, you need to include the PicoCFunctions.h header file. This file contains the necessary definitions for interfacing with the MMBasic environment.

Example: `add_numbers.c`

```c
#include "PicoCFunctions.h"  // Include the MMBasic PicoMite header

void add_numbers(long long  *a, long long  *b, long long  *result) {
   *result= *a + *b;
}
```

The CSUB`add_numbers` adds two integers and returns the result. The use of `ARMCFunctions.h` ensures compatibility with the PicoMite’s architecture.

---

### Step 2: Batch Script for Compilation and Conversion

You can automate the process of compiling the C code, linking it, and converting the resulting ELF file into a CSUB using a batch script.

Here’s an example batch script (`compile_csub.bat`):

```batch
@ECHO OFF

REM Compile the C code to an object file (.o)
bin\arm-none-eabi-gcc -c -mcpu=cortex-m0 -mfloat-abi=soft -mthumb -Wall -Wno-main -ffunction-sections -Ofast -fPIC -I. %1.c -o %1.o
IF ERRORLEVEL 1 Goto Done
pause

REM Link the object file to create an ELF file
bin\arm-none-eabi-ld -nostartfiles -T arm-gcc-link.ld -o %1.elf %1.o

IF ERRORLEVEL 1 Goto Done
pause

REM Convert the ELF file to a CSUB using ArmCfGenV144.bas (or CFGEN.bas)
MMBasic ArmCfGenV144.bas %1.elf %2
del %1.elf
del %1.o
rem Notepad %1.bas

:Done
```

This script automates the following steps:
1. Compiles the C code into an object file (`.o`).
2. Links the object file into an ELF file (`.elf`).
3. Converts the ELF file into a CSUB using ArmCfGenV144.bas or CFGEN.bas.

---

### Step 3: Run the Batch Script

To use the batch script, place your C file in the same directory as the script and run the following command:

```batch
compile_csub add_numbers add_numbers
```

This will generate a `add_numbers.bas` file containing the CSUB code, ready for use in MMBasic.

---

### Step 4: Insert the CSUB in MMBasic

Open the `.bas` file that was generated, and copy the CSUB code into your MMBasic program.

Example MMBasic program:

```basic
CSUB Add_Numbers
[Paste the content of the generated add_numbers.bas here]
END CSUB
```

To use the CSUB in your MMBasic code, call it as follows:

```basic
Dim result As INTEGER

add_Numbers 10, 20, result

Print "The result is: "; result
End

'File add_Numbers.bas written 16-09-2024 20:38:53 v1.44
CSub add_numbers integer, integer, integer
 00000000
 6841000B B5306800 685D681C 41691900 60516010 46C0BD30
End CSub

---

### Additional Notes:

1. Header File: Always include the latest version of ARMCFunctions.h in your C code. This file provides the necessary hooks and interfaces to work with MMBasic on the PicoMite.
 
2. Tool Versions: The conversion tool ArmCfGenV144.bas (or CFGEN.bas) is essential for converting the compiled ELF file into a CSUB. Ensure you have the latest version of the tool to avoid compatibility issues.

3. Performance Considerations: CSUBs significantly improve performance over pure MMBasic code, especially for computationally heavy tasks, but be mindful of the limited resources on the PicoMite.

---

### Conclusion

By following this guide, you can create powerful CSUBs in C and integrate them into your MMBasic projects on the PicoMite. Remember to include the correct header files and use the ArmCfGenV144.bas tool for converting your C code into a CSUB.


To open the command window, press the shift key and the right mouse button in the window containing the batch file:
https://www.thebackshed.com/forum/ViewTopic.php?TID=12289&P=2#151042

Important: You can't write a CFunction for Picomites!

from CMM2 manual:
  Quote  The type of each parameter can be specified in the definition. For example:
CSub MySub integer, integer, string.
This specifies that there will be three parameters, the first two being integers
and the third a string.
Note:
* Up to ten arguments can be specified ('arg1', 'arg2', etc).
* If a variable or array is specified as an argument the C routine will
receive a pointer to the memory allocated to the variable or array and
the C routine can change this memory to return a value to the caller. In
the case of arrays, they should be passed with empty brackets e.g.
arg(). In the CSUB the argument will be supplied as a pointer to the
first element of the array.
* Constants and expressions will be passed to the embedded C routine
as pointers to a temporary memory space holding the value.

* CSUBs must call routinechecks() every millisecond or so both to keep
the USB keyboard active and also ensure the watchdog doesn't trigger.
CSUBs that run to completion within a couple of milliseconds can
ignore this.

causality ≠ correlation ≠ coincidence
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 07:35pm 16 Sep 2024
Copy link to clipboard 
Print this post

This is looking better and better (ChatGPT)

Many thanks  
 
twofingers
Guru

Joined: 02/06/2014
Location: Germany
Posts: 1240
Posted: 07:52pm 16 Sep 2024
Copy link to clipboard 
Print this post

Anyway: I would recommend reading a textbook for the C language to understand the differences from Basic.  

By the way, this might also be helpful: Ch Professional Edition - an interpreter for the C language - for ARM and Raspberry PI is free for non-commercial use ...

I think it's such a shame that CSUBs are so little used ... I would like to see CSUBs become more popular. Good luck!
Edited 2024-09-17 06:23 by twofingers
causality ≠ correlation ≠ coincidence
 
Mixtel90

Guru

Joined: 05/10/2019
Location: United Kingdom
Posts: 6778
Posted: 09:53pm 16 Sep 2024
Copy link to clipboard 
Print this post

[rant]
I rarely have a serious rant that I genuinely feel strongly about but...

For <Deity>'s sake Why?

You have one of the most powerful home computer BASIC language machines with loads of facilities that people used to dream of in the 1980s this is what we are supposed to be emulating, remember? ANSI C didn't appear until 1989). And you want to corrupt it by adding C? It was fair game adding short machine code routines to a 4MHz Z80 to do things like sprite handling and fast screen switching but that's taken care of now. Adding C, even if you think it's the best thing since sliced bread, ruins BASIC and makes it totally incomprehensible to anyone attempting to learn. BASIC is supposed to be an instructional language.
You may as well abandon MMBasic and write everything in C++ - I think you can do that via the Arduino front end now. Have fun with your library based programming.
If the challenge of writing fast, efficient BASIC is to be replaced by CSUBs then we may as well give up.
[/rant]
Mick

Zilog Inside! nascom.info for Nascom & Gemini
Preliminary MMBasic docs & my PCB designs
 
phil99

Guru

Joined: 11/02/2018
Location: Australia
Posts: 2135
Posted: 10:11pm 16 Sep 2024
Copy link to clipboard 
Print this post

Another problem is lack of compatibility with any other version of MMBasic than the one for which they were compiled.

Eg. Csub LOG is an excellent PicoMite time stamp recorder but has to be re-compiled every time the firmware core is updated.

I fail at this every time and rely on the charity @Disco4now to do it for me.
 
EDNEDN
Senior Member

Joined: 18/02/2023
Location: United States
Posts: 118
Posted: 03:42am 17 Sep 2024
Copy link to clipboard 
Print this post

  Quote  If the challenge of writing fast, efficient BASIC is to be replaced by CSUBs then we may as well give up.


  Quote  Another problem is lack of compatibility with any other version of MMBasic than the one for which they were compiled.


Yes...   But it is really cool that the capability is there.   I wouldn't mind seeing a thread that explored how well the Basic to C translator does its job.   It is a very interesting topic.  

The web page says:

  Quote  BCX is programmed entirely using BCX BASIC and it is FAST!   BCX translates its own source code, over 31,000 lines of code, in under 1 second on a modest Intel i5 desktop computer running Windows 10 Pro.


I didn't see an obvious link to download the source code.  The BCX IDE is just an executable but it kind of sounds like BCX is written in Basic.   If the download link for the source code was easier to find I probably would have pulled it down and started perusing the source code.

Any interpretive language suffers a performance hit.   Having an easy way to speed up a routine that needs a 2x speed bump is always of interest.

Mostly...   I was curious because I wanted to see what kind of optimizations BCX knew about.   My guess is, with the speed it is doing its work, it is just doing a brute force, template based, translation.   But I don't know that and I certainly would read every post in a thread discussing it.


PS.  I think I found the BCX source code.  I've attached it to this post in case anybody else wants to play with it.   It is 1.2 MB big...  So it won't be straight forward to get it to run on a PicoMite.   But it will keep me amused for a few days.


Bcx790.zip
Edited 2024-09-17 15:48 by EDNEDN
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 06:01am 17 Sep 2024
Copy link to clipboard 
Print this post

Back when I discovered QuickBasic, some things were still a bit sluggish and I read that it was for GW-BASIC compatibility reasons.
Ethan Winer of Crescent Software produced a library of subs/functions that supplemented or replaced the QuickBasic routines. They were all pure MASM and source was provided.
Ethan encouraged his customers to use his code as templates for their own developments and he even came-up with a small cartoon-like tutorial.

Well the "DOS doesn't do real time" thing didn't apply to me anymore because I was able to adapt some print-spooler code to handle my high-priority I/O, @1ms in the background and it shared variables with the QuickBasic code. It even ran in a QLB (quick library) so that; even when I was pausing or single-stepping QB code in the IDE, the background task kept on running. This was a huge dev/debug time-saver.
I could never dream of developing an app in 100% MASM and would never want to because QB enabled RAD (rapid application development).

MMBasic is today's equivalent and on the Pico, we have the option of using ASM for the PIO. Incredible! If one relies on PIO then compatibility with other devices is already out-the-window.

Having the option to further boost the performance of certain procedures takes MMBasic up a notch.

Ethan's site is always interesting and he's also an audio expert
 
Volhout
Guru

Joined: 05/03/2018
Location: Netherlands
Posts: 4222
Posted: 06:05am 17 Sep 2024
Copy link to clipboard 
Print this post

Phenix,

I have no idea where you diversion to CSUB comes from, but if this is driven from a technical challenge that cannot be done in MMBasic, you may also ask the forum to help you.

For someone who has grown up in basic, C is a different cookie. And yes, it is worth learning how to code in C since that is the basis under most, if not all, embedded code in the world. But it will take time, maybe years before you can write code like Tom, Peter, Geoff, and whoever is coding C at the moment. They also have gone through the learning curve, and depending how talented you are, you grow (and how good your teacher is).

And yes, we have chatgpt as a teacher.

I, for myself, am in this learning curve. Have played around (copying, altering some Arduino code) in C, and do not find it easy. But YMMV. The most anoying about C is that it is very strickt in the way the text is formatted. A space, or semicolumn, can alter the code completely. And not alway easy to spot the error, since the misaligned text is completely valid. Not error messages from the compiler.

The good thing about C is that you will have to plan and think, becuase you will have to pre-define variables exactly right.

If you need speed in MMBasic, use the CMM2. It is roughly 5x faster than the RP2350 pico at 252MHz, and near 10x faster than the RP2040.

Volhout
Edited 2024-09-17 16:11 by Volhout
PicomiteVGA PETSCII ROBOTS
 
Mixtel90

Guru

Joined: 05/10/2019
Location: United Kingdom
Posts: 6778
Posted: 06:48am 17 Sep 2024
Copy link to clipboard 
Print this post

I'm sorry about last night's rant, but it really is something that winds me up. :)

BBC BASIC got it right, I think, where the assembler listing is part of the BASIC program and you list through it together with the BASIC. That was clever as you could see what was happening more easily. But of course those programs were never intended to be run on any other platform (especially Z80 ones!) so compatibility didn't matter.

I also used to get Z80 code poked into strings then execute the string. It was neat and  extremely useful on the Tandy TRS80 which was no speed demon, but you could never do anything with that code. If you didn't have the printed assembly listing it was completely incomprehensible - and didn't list properly as the command codes in the strings screwed up the screen.

Both of the above were things of their time though. We all put up with them because moving stuff around on screens was more than the processor could handle.

(One of my pet sidelines. After the Nascom machines came the Gemini series. One of the cards was dedicated to video handling and had its own Z80 and RAM (no video chip - this was before those) to do some clever stuff. You handled it using some of the Z80 ports, which live outside the address space, so it took up zero system RAM.)
Mick

Zilog Inside! nascom.info for Nascom & Gemini
Preliminary MMBasic docs & my PCB designs
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 06:50am 17 Sep 2024
Copy link to clipboard 
Print this post

Hi Harm,

  Quote  If you need speed in MMBasic, use the CMM2. It is roughly 5x faster than the RP2350 pico at 252MHz, and near 10x faster than the RP2040.


CMM2 doesn't have PIO. I use high resolution/frequency incremental encoders.

I am only talking about code snippets, nothing major. Just like Pete created Math routines. In fact, Pete once created a PID in MMBasic but for another device. I don't expect him to do it for me because it won't be widely used.

Here's what I put in BCX:


CLS

DIM i, j, k, q

j = 10
k =  1
q = -1

FOR i = j TO k STEP q
  PRINT i
NEXT

PRINT

j =  1
k = 10
q =  1

FOR i = j TO k STEP q
  PRINT i
NEXT

KEYPRESS


And here's what it output:

int main(int argc, char *argv[])
{
 hConsole=GetStdHandle(STD_OUTPUT_HANDLE);
 cls();
 j=10;
 k=1;
 q=-1;
 for(i=j; (q>=0 ? i<=k : i>=k); i+=q)
   {
     printf("% d\n",(int)i);
   }
 printf("\n");
 j=1;
 k=10;
 q=1;
 for(i=j; (q>=0 ? i<=k : i>=k); i+=q)
   {
     printf("% d\n",(int)i);
   }
 keypress();
 return EXIT_SUCCESS;   // End of main program
 }

 
Mixtel90

Guru

Joined: 05/10/2019
Location: United Kingdom
Posts: 6778
Posted: 07:52am 17 Sep 2024
Copy link to clipboard 
Print this post

The PIO is somewhat different to CSUBs. It's a device that's natively in the Pico version of MMBasic now and its code isn't really hidden. You are actually embedding code for a completely different processor and setting up the links for MMBasic to talk to it.

IMHO CSUBs are a cop-out every bit as much as embedding Z80 code in strings on the TRS-80 was and their use should be discouraged wherever possible, even if that reduces the speed to that of interpreted BASIC. If the C source was in-line in the MMBasic program I wouldn't be going on about it (well, not as much anyway! Seeing the source and being able to make changes is a good way to learn. It's still pretty anachronistic to run C within BASIC. No computer around that period could have done it as C wasn't really around at that time.).

I know, I'm an old moaner. But I'm old enough to qualify to be one. :)
Mick

Zilog Inside! nascom.info for Nascom & Gemini
Preliminary MMBasic docs & my PCB designs
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 07:59am 17 Sep 2024
Copy link to clipboard 
Print this post

Hi Mick,

But if the "guts" of what BCX generates can be utilized, the actual code-logic is still authored in Basic. One would still make changes in Basic (at least I would).

For time critical routines, that portion of Basic can be compiled.

Look at the benchmarks where we see examples of compiled C compared to Basic  

Imagine if we could automate the process of MMBasic->BCX->CSub.
Edited 2024-09-17 18:00 by PhenixRising
 
matherp
Guru

Joined: 11/12/2012
Location: United Kingdom
Posts: 9105
Posted: 08:11am 17 Sep 2024
Copy link to clipboard 
Print this post

  Quote  And here's what it output:


How many reasons would you like for why it couldn't run as a CSUB?
The concept is impracticable CSUB code must be position independent and cannot use any C library calls
 
PhenixRising
Guru

Joined: 07/11/2023
Location: United Kingdom
Posts: 857
Posted: 08:33am 17 Sep 2024
Copy link to clipboard 
Print this post

  matherp said  
  Quote  And here's what it output:


How many reasons would you like for why it couldn't run as a CSUB?
The concept is impracticable CSUB code must be position independent and cannot use any C library calls


I understand that. That code was generated to immediately execute on the PC. I am referring to things like the structure of the FOR-NEXT loop. I would never work that out in a million years  

  Quote  But if the "guts" of what BCX generates can be utilized

Edited 2024-09-17 18:39 by PhenixRising
 
matherp
Guru

Joined: 11/12/2012
Location: United Kingdom
Posts: 9105
Posted: 09:10am 17 Sep 2024
Copy link to clipboard 
Print this post

  Quote   I am referring to things like the structure of the FOR-NEXT loop.


This is an example where the c code generated is unnecessarily complicated in order to cope with two simple cases: step >0 and step <0

for(i=j;  i<=k ; i=i+q) // positive step
  {
  }


for(i=j;  i>=k ; i=i-q) // negative step
  {
  }


Note that now the parameters map exactly onto the Basic. In fact for the simple Basic control statements the conversion to C is trivial.
e.g.

if blah then
endif

becomes

if(blah){
}

etc.

You can learn enough C to do this in less than a couple of hours.
The bits of writing/using a CSUB that are hard are precisely the things that BCX can't possibly do.
 
twofingers
Guru

Joined: 02/06/2014
Location: Germany
Posts: 1240
Posted: 09:40am 17 Sep 2024
Copy link to clipboard 
Print this post

  Mixtel90 said  [rant]
I rarely have a serious rant that I genuinely feel strongly about but...

For <Deity>'s sake Why? ...

With respect. I think it's nice to see that Mick (Mixtel) is the guardian of the holy grail, but I see it differently than he does. I want to try - as a black knight - to defend CSUBs here.

His arguments would also apply to PIO programming (incompatibility) as well and LOG (PicoMite time stamp recorder) would be hard to imagine in pure Basic. Actually, a lot of Peter's work - which I really appreciate! - consists of writing functions that could just as easily be written in Basic or C code (CSUBs). Why does an RTC or sensor query have to be integrated into Basic? There is little compatibility with earlier versions of MMBasic. This could easily be implemented in Basic.

I have worked with many programming languages ​​in my life. I think each had its justification and advantages.
For me, CSUBs are an additional option that allows us to do things that would not otherwise be possible. (E.g. Ruben's excellent text editor for CMM2). I am grateful that this option exists! We should be grateful for ANY freedom. Yes, and I think C is not easy to master, but it's only about tiny pieces of code when it comes to making something up to 100x faster.

I can't really see any reason to argue.

Regards
Michael
Edited 2024-09-17 19:46 by twofingers
causality ≠ correlation ≠ coincidence
 
     Page 1 of 3    
Print this page
© JAQ Software 2024