Posted on — Leave a comment

How to Use C SDK to Create UF2 file which Interface Ultrasonic Sensor with Raspberry Pi Pico

Hardware setup

HC-SR04Raspberry Pi Pico
VCCVSYS
GNDGND
TrigGP2
ECHOGP3

I am using raspberry pi model 3 b+ for the code compilation.

  1. Create the folder named “distance” inside the pico folder
  1. Then Create the test.c and CMakeLists.txt files using touch command.
touch test.c CMakeLists.txt
  1. Copy the pico_sdk_import.cmake file from pico/pico-sdk/external
  2. make the build directory using mkdir command
mkdir build
  1. Here is the CMakeLists.txt code
# Set the minimum required version of CMake
cmake_minimum_required(VERSION 3.13)

# Import the Pico SDK CMake configuration file
include(pico_sdk_import.cmake)

# Set the project name and languages
project(test_project C CXX ASM)

# Set the C and C++ language standards
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# Initialize the Pico SDK
pico_sdk_init()

# Create an executable target called "test" from the source file "test.c"
add_executable(test
    test.c
)

# Enable USB stdio for the "test" target (used for serial communication)
pico_enable_stdio_usb(test 1)

# Disable UART stdio for the "test" target
pico_enable_stdio_uart(test 0)

# Add extra outputs for the "test" target (e.g., UF2 file)
pico_add_extra_outputs(test)

# Link the "test" target with the pico_stdlib library
target_link_libraries(test pico_stdlib)
  1. Here is the c code that you put inside the test.c file
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/timer.h"

#define TRIG_PIN 2
#define ECHO_PIN 3

float measure_distance() {
    gpio_put(TRIG_PIN, 1);
    sleep_us(10);
    gpio_put(TRIG_PIN, 0);

    uint32_t start_ticks = 0;
    uint32_t end_ticks = 0;

    while (gpio_get(ECHO_PIN) == 0) {
        start_ticks = time_us_32();
    }

    while (gpio_get(ECHO_PIN) == 1) {
        end_ticks = time_us_32();
    }

    uint32_t elapsed_time_us = end_ticks - start_ticks;
    float distance_cm = elapsed_time_us * 0.0343 / 2;

    return distance_cm;
}

int main() {
    stdio_init_all();
    sleep_ms(2000);  // Wait for sensor to stabilize

    gpio_init(TRIG_PIN);
    gpio_set_dir(TRIG_PIN, GPIO_OUT);

    gpio_init(ECHO_PIN);
    gpio_set_dir(ECHO_PIN, GPIO_IN);

    while (1) {
        float distance = measure_distance();
        printf("Distance: %.2f cm\n", distance);
        sleep_ms(1000);
    }

    return 0;
}
  1. after this you need to execute this line of code in the terminal
export PICO_SDK_PATH=../../pico
  1. then execute the following code in the given order
cd build
cmake ..
make

If everything worked, you will have your ulf2 file in your build directory

Posted on — Leave a comment

How to Perform Discrete Fourier Transform on N-Point Sequence using STM32L476G

x(n) = { 0, 1, 0, 1}

Here x(n) is a 4 point sequence

Now to perform Fourier transform on this sequence.

DFT Formula

Here X(k) is the DFT of x(n)

‘k’ is the index representing individual frequency component

‘N’ is the Length of the sample sequence

‘n’ is an index of the element of the sequence in x(n)

For example: if we calculate the value for k =1

This will give us the X(1)

So, if the sequence is sampled at 4Hz and the sampling frequency is equal to two times the max frequency. Then X(1) gives us the 1 Hz frequency component.

To calculate Euler identity

Here is the code:

/*
* Author: ABHAY KANT
* Discrete Fourier Transform using STM32L476vg on STM32L476g-Disco board.
* computes N point DFT
* computes magnitude of N/2 Points of dft
* computes phase of N/2 points of dft
* NOTE: DFT array is named xfft. It DOES NOT Calcultes DFT using FFT algo.
* Limitations: for a 2000 point sequence it takes a lot of time.
               And as the number of points increase the computational time also increases.
a rough estimate of time for a 2000 point dft it takes roughly ~ 60 seconds. 
*/
asm("nop");
//int xn[6] = {1,1,2,2,3,3};

int16_t Len = 1024; 
float xn[Len];

float xfft[Len * 2];

/*
 * calculating phase and mag for only N/2 since the value generated after N/2 are conjugate 
 */
float phase[Len/2], mag[Len/2];
int	k = 1;
int	N = 0;
int	n = 0;
float	real = 0;
float	imag = 0;
float	param = 0;
int	freq = 10;
int i;

/*
 * These two "for loops" are used to initalize the array with zero's
 */
for(n=0;n<=Len;n++){xn[n] = 0;}
for(n=0;n<=Len*2;n++){xfft[n] = 0;}



/*
 * Generating a sine Wave 
 */

	for(i=0; i<Len/2; i++){
		xn[i+512] = sin((2 * 3.1415926 * i * freq)/Len);
	}

N = Len;				
/* Note: if Len/8 then it will only calculate the 1/8 th term from 0 only.*/
/*
 * This loop calculates the x[n].e^(-j2.PI.n.k/N)
 */

	for(k=0 ; k<N ; k++){

		for(n=0 ; n<N; n++){
		param = ((2 * M_PI * n * k)/N);
		real = real + ( xn[n] * cos(param) );
		imag = imag + ((-1) * xn[n] * sin(param) );
		}
		xfft[2 * k] = real;
		xfft[(2 * k) + 1] = imag;
		real = 0;
		imag = 0;
	}



/*
 * Calculate phase angle of each frequency component
 */
float temp;
for(k=0; k<N/2;k++)
{
	temp = xfft[(2 * k ) + 1] / xfft[2 * k];
	phase[k] = atan(temp);
}

/*
 * Calculate Magnitude of each frequency 
 */

for(k=0; k<N/2;k++)
{
	temp = sqrt( (xfft[(2 * k ) + 1] * xfft[(2 * k ) + 1] ) + ( xfft[2 * k] * xfft[2 * k] ) );
	mag[k] = temp;
}
asm("nop");  //added to support for creating breakpoint during debug
Posted on — Leave a comment

Union

Union is another user defined data type.

The difference between union and struct is that; struct uses a contagious memory allocation for each individual item inside it; whereas union uses the size of biggest element for allocation of memory.

union segment1 {
int x1;
char y2;
};

// sizeof segement1 union is 4 bytes 

struct segment2{
int x1;
char y2;
};

// sizeof segement1 union is 8 bytes 

Posted on — Leave a comment

Convert program written in C into assembly

Sometimes to understand code , you need to look into assembly language. I write mostly using C. So sometimes to better understand the program i converte the program into assembly. The syntax changes from machine to machine.

Here is the program that i will use to convert to assembly using two different machine. One is ARM based and the other is x86_64.

#include <stdio.h>

struct CarDetail{
int CarNumber;
char CarOptions;
};

int main() {
struct CarDetail maruti_alto;

maruti_alto.CarNumber = 123;
maruti_alto.CarOptions = 'L';

printf("Maruti Alto Details\nNumber = \t%d\nOptions = \t%c",maruti_alto.CarNumber,maruti_alto.CarOptions);
return 0;
}

ARM

If i convert the above program using ARM based machine using command

gcc main.c -S -o main.s
        .arch armv6
	.file	"main.c"
	.text
	.section	.rodata
	.align	2
.LC0:
	.ascii	"Maruti Alto Details\012Number = \011%d\012Options ="
	.ascii	" \011%c\000"
	.text
	.align	2
	.global	main
	.arch armv6
	.syntax unified
	.arm
	.fpu vfp
	.type	main, %function
main:
	@ args = 0, pretend = 0, frame = 8
	@ frame_needed = 1, uses_anonymous_args = 0
	push	{fp, lr}
	add	fp, sp, #4
	sub	sp, sp, #8
	mov	r3, #123
	str	r3, [fp, #-12]
	mov	r3, #76
	strb	r3, [fp, #-8]
	ldr	r3, [fp, #-12]
	ldrb	r2, [fp, #-8]	@ zero_extendqisi2
	mov	r1, r3
	ldr	r0, .L3
	bl	printf
	mov	r3, #0
	mov	r0, r3
	sub	sp, fp, #4
	@ sp needed
	pop	{fp, pc}
.L4:
	.align	2
.L3:
	.word	.LC0
	.size	main, .-main
	.ident	"GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
	.section	.note.GNU-stack,"",%progbits

If we want to remove relative addressing modes and make it very simple you can use -fomit-frame-pointer option

gcc main.c -S -fomit-frame-pointer -o main-omit-fp.s
        .arch armv6
	.file	"main.c"
	.text
	.section	.rodata
	.align	2
.LC0:
	.ascii	"Maruti Alto Details\012Number = \011%d\012Options ="
	.ascii	" \011%c\000"
	.text
	.align	2
	.global	main
	.arch armv6
	.syntax unified
	.arm
	.fpu vfp
	.type	main, %function
main:
	@ args = 0, pretend = 0, frame = 8
	@ frame_needed = 0, uses_anonymous_args = 0
	str	lr, [sp, #-4]!
	sub	sp, sp, #12
	mov	r3, #123
	str	r3, [sp]
	mov	r3, #76
	strb	r3, [sp, #4]
	ldr	r3, [sp]
	ldrb	r2, [sp, #4]	@ zero_extendqisi2
	mov	r1, r3
	ldr	r0, .L3
	bl	printf
	mov	r3, #0
	mov	r0, r3
	add	sp, sp, #12
	@ sp needed
	ldr	pc, [sp], #4
.L4:
	.align	2
.L3:
	.word	.LC0
	.size	main, .-main
	.ident	"GCC: (Raspbian 8.3.0-6+rpi1) 8.3.0"
	.section	.note.GNU-stack,"",%progbits

X86_64

gcc main.c -S -o main.s
	.file	"main.c"
	.text
	.section	.rodata
	.align 8
.LC0:
	.string	"Maruti Alto Details\nNumber = \t%d\nOptions = \t%c"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
	subq	$16, %rsp
	movl	$123, -8(%rbp)
	movb	$76, -4(%rbp)
	movzbl	-4(%rbp), %eax
	movsbl	%al, %edx
	movl	-8(%rbp), %eax
	movl	%eax, %esi
	leaq	.LC0(%rip), %rdi
	movl	$0, %eax
	call	printf@PLT
	movl	$0, %eax
	leave
	.cfi_def_cfa 7, 8
	ret
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (Debian 8.3.0-6) 8.3.0"
	.section	.note.GNU-stack,"",@progbits
gcc main.c -S -fomit-frame-pointer -o main-omit-fp.s
	.file	"main.c"
	.text
	.section	.rodata
	.align 8
.LC0:
	.string	"Maruti Alto Details\nNumber = \t%d\nOptions = \t%c"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	subq	$24, %rsp
	.cfi_def_cfa_offset 32
	movl	$123, 8(%rsp)
	movb	$76, 12(%rsp)
	movzbl	12(%rsp), %eax
	movsbl	%al, %edx
	movl	8(%rsp), %eax
	movl	%eax, %esi
	leaq	.LC0(%rip), %rdi
	movl	$0, %eax
	call	printf@PLT
	movl	$0, %eax
	addq	$24, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (Debian 8.3.0-6) 8.3.0"
	.section	.note.GNU-stack,"",@progbits