You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

67 lines
2.4 KiB

/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Dan Chokola, KD2HSG
*
* The smallest complete use of the library: transmit a frame at an SDR's
* rate, add noise, and receive it with the streaming receiver.
*
* cc loopback.c $(pkg-config --cflags --libs chirpmodem) -lm -o loopback && ./loopback
*/
#include <chirpmodem.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void on_frame(void *user, const chirpmodem_frame *f)
{
(void)user;
printf("[%.3f s] %s: %.*s (SNR %+.1f dB, offset %+.1f Hz)\n", f->t, f->src,
f->body_len, (const char *)f->body, f->snr_db, f->offset_hz);
}
int main(void)
{
/* transmitter: SF9, 62.5 kHz, 1 MS/s output, signal 250 kHz above 0 Hz */
chirpmodem_tx_config tc;
chirpmodem_tx_config_init(&tc);
tc.fs = 1e6;
tc.if_offset = 250e3;
int err;
chirpmodem_tx *tx = chirpmodem_tx_new(&tc, &err);
if (!tx) {
fprintf(stderr, "%s\n", chirpmodem_strerror(err));
return 1;
}
const char *msg = "hello de KD2HSG";
long n = chirpmodem_tx_frame(tx, "KD2HSG", NULL, (const uint8_t *)msg, (int)strlen(msg), 0,
NULL, 0); /* size first */
long lead = 200000, total = lead + n + 200000;
float *iq = calloc(2 * (size_t)total, sizeof(float)); /* interleaved I, Q */
chirpmodem_tx_frame(tx, "KD2HSG", NULL, (const uint8_t *)msg, (int)strlen(msg), 0,
iq + 2 * lead, n);
/* a little noise: about -5 dB SNR in the signal's 62.5 kHz */
unsigned s = 1;
double sd = 0.7 * sqrt(pow(10, 0.5) * 1e6 / 62.5e3 / 2);
for (long k = 0; k < 2 * total; k++) {
double u1 = ((s = s * 1103515245u + 12345u) >> 8) / 16777216.0 + 1e-9;
double u2 = ((s = s * 1103515245u + 12345u) >> 8) / 16777216.0;
iq[k] += (float)(sd * sqrt(-2 * log(u1)) * cos(6.283185307179586 * u2));
}
/* receiver: same parameters; frames arrive through the callback */
chirpmodem_rx_config rc;
chirpmodem_rx_config_init(&rc);
rc.fs = 1e6;
rc.if_offset = 250e3;
rc.on_frame = on_frame;
chirpmodem_rx *rx = chirpmodem_rx_new(&rc, &err);
for (long k = 0; k < total; k += 4096) /* any block size */
chirpmodem_rx_push(rx, iq + 2 * k, total - k < 4096 ? total - k : 4096, CHIRPMODEM_CF32);
chirpmodem_rx_finish(rx);
chirpmodem_rx_free(rx);
chirpmodem_tx_free(tx);
free(iq);
return 0;
}