Let’s make a very simple tutorial on how to use Zig for cypress STM32 boards. You’ll be surprised how easy it is.
Making a Zig library usable in PSoC Creator
Let’s start by making a new project in PSoC Creator, Cypress' IDE. I’m using a CY8CKIT-059 board here.
We first are going to leverage PSoC Creator’s tools to add a controllable pin to our software. This pin will drive the LED on our kit.
This should be enough. Let’s build the project as it is right now, so PSoC Creator can generate for us all the code that will allow us to use this pin.
We will start with something very basic: we’re going to make our pin blink on a timer, and the value of the timer will be obtained from a Zig library.
Let’s start with the code in the
main.c source file.
Now we just have to make the
zig_get_delay function in a zig library. Let’s set up a simple build.zig file.
Our cross-target options will make something that PSoC Creator can use. Now let’s make the zig source file itself.
Nothing fantastic here. I’m assuming these 2 files are at the root of your PSoC Creator project.
Now let’s make PSoC Creator build the zig library and link it.
First, add a custom pre-build user command in your build settings.
And a step to get the resulting library file and link it to our project.
And at this point, everything should be fine already! Just clean and build.
Calling Cypress methods from zig
What if we want to run cypress methods from our zig sources?
It’s simple, just ask for them! The
extern keyword is enough for the linker to make his magic.
Let’s change our source code so our core loop is inside zig.
And… That’s it. That’s all you need.
The good, the bad and the ugly hack
Ok, here’s a quick hack for fun.
main is a method like any other. You can actually link to main from a library.
That’s not pretty, but now you can do everything from zig!
Leveraging zig in this environment
You now have access to all the zig language, but also to a good part of the zig std lib. Most of the zig std doesn’t rely on c libraries, and can now be easily used.
Let’s make our blinking random, using zig’s random functions.
The sky is the limit at this point. And you can leverage zig’s allocator pattern to use dynamically allocated memory too: just have to write the allocator for your board.