Skip to content

Instantly share code, notes, and snippets.

@Sasszem
Created November 10, 2024 23:05
Show Gist options
  • Save Sasszem/350c24559f6b5410c9badfe4fb3cebd6 to your computer and use it in GitHub Desktop.
Save Sasszem/350c24559f6b5410c9badfe4fb3cebd6 to your computer and use it in GitHub Desktop.
Generate a CW signal on a HackRF One with set frequency and gain settings
#include <cstdio>
#include <cstring>
extern "C" {
#include <libhackrf/hackrf.h>
}
#include <pthread.h>
#include <unistd.h>
#include <complex>
#include <cstdint>
#include <numbers>
#include <signal.h>
const uint64_t SAMPLE_RATE = 2000000;
volatile int should_stop = 0;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int transfer_callback(hackrf_transfer *transfer) {
int8_t *signed_buffer = (int8_t*)transfer->buffer;
memset(signed_buffer, 127, transfer->buffer_length);
transfer->valid_length = transfer->buffer_length;
if (should_stop) {
return 1;
}
return 0;
}
void flush_callback(void* transfer_ptr, int x) {
pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
uint32_t CURRENT_GAIN = 0;
uint32_t MAX_GAIN = 47;
uint64_t FREQ = 10000000;
int main(int nargs, char** args) {
if (nargs != 3) {
printf("Usage: \"%s <freq> <gain>\", where freq is in Hz and gain is 0-47.\nTransmits CW with maximum amplitude (I=Q=127) and amp off.\n", args[0]);
return -1;
}
sscanf(args[1], "%ld", &FREQ);
sscanf(args[2], "%d", &CURRENT_GAIN);
if (CURRENT_GAIN > MAX_GAIN) {
printf("Invalid gain setting: %d\n", CURRENT_GAIN);
return -1;
}
printf("Freq: %.06lf MHz\n", (double)FREQ/1000000.0);
printf("Gain: %d dB\n", CURRENT_GAIN);
hackrf_init();
hackrf_device *device = NULL;
if (hackrf_open(&device)) {
printf("Could not open any devices...\n");
return -1;
}
hackrf_set_freq(device, FREQ);
hackrf_set_sample_rate(device, SAMPLE_RATE);
//hackrf_set_amp_enable(device, 1);
hackrf_set_txvga_gain(device, CURRENT_GAIN);
// hackrf_set_tx_underrun_limit(device, 100000);
//hackrf_enable_tx_flush(device, flush_callback, NULL);
hackrf_start_tx(device, transfer_callback, NULL);
getchar();
should_stop = 1;
//pthread_mutex_lock(&mutex);
//pthread_cond_wait(&cond, &mutex);
hackrf_stop_tx(device);
hackrf_close(device);
hackrf_exit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment