Root/tools/atrf-xtal/atusb.c

Source at commit 49e7c83796bc04941e9dbcec69bc0751563ff4d4 created 2 years 6 months ago.
By Werner Almesberger, atusb/: use ""VDD" symbol from kicad-libs
1/*
2 * atrf-xtal/atusb.c - ATUSB-specific driver and evaluation
3 *
4 * Written 2011 by Werner Almesberger
5 * Copyright 2011 Werner Almesberger
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13
14#include <stdlib.h>
15#include <stdio.h>
16#include <sys/time.h>
17
18#include <usb.h>
19#include <gsl/gsl_fit.h>
20
21#include "at86rf230.h"
22#include "atusb/ep0.h"
23#include "atrf.h"
24
25#include "atrf-xtal.h"
26
27
28#define FROM_DEV ATUSB_FROM_DEV(0)
29
30#define F_NOMINAL_Hz 8000000 /* nominal frequency, in Hz */
31
32
33static uint64_t get_sample(struct atrf_dsc *dsc, double *t0, double *t1)
34{
35    struct timeval tod0, tod1;
36    uint64_t cnt;
37    int res;
38
39    gettimeofday(&tod0, NULL);
40    res = usb_control_msg(atrf_usb_handle(dsc),
41        FROM_DEV, ATUSB_TIMER, 0, 0, (void *) &cnt, sizeof(cnt), 1000);
42    gettimeofday(&tod1, NULL);
43    if (res < 0) {
44        fprintf(stderr, "ATUSB_TIMER: %s\n", usb_strerror());
45        exit(1);
46    }
47    *t0 = tod0.tv_sec+tod0.tv_usec/1000000.0;
48    *t1 = tod1.tv_sec+tod1.tv_usec/1000000.0;
49    return cnt;
50}
51
52
53void do_atusb(struct atrf_dsc *dsc, int trim, int dump_raw, double ppm,
54     int n)
55{
56    double t0[n], t1[n], cnt[n], w[n];
57    double c0, c1, cov00, cov01, cov11, chisq;
58    double d;
59    double tz = 0, cntz = 0;
60    double rel;
61    int i;
62
63    atrf_reg_write(dsc, REG_XOSC_CTRL,
64        (XTAL_MODE_INT << XTAL_MODE_SHIFT) | trim);
65
66    for (i = 0; i != n; i++) {
67        cnt[i] = get_sample(dsc, t0+i, t1+i);
68        if (!i) {
69            tz = t0[0];
70            cntz = cnt[0];
71        }
72        t0[i] -= tz;
73        t1[i] -= tz;
74        cnt[i] -= cntz;
75
76        /*
77         * see http://en.wikipedia.org/wiki/
78         * Uniform_distribution_(continuous)
79         */
80        d = (t1[i]-t0[i])*F_NOMINAL_Hz;
81        w[i] = 12/(d*d);
82    }
83
84    if (dump_raw) {
85        for (i = 0; i != n; i++)
86            printf("%.6f %.6f %.0f\n", t0[i], t1[i], cnt[i]);
87        return;
88    }
89
90    gsl_fit_wlinear (t0, 1, w, 1, cnt, 1, n,
91        &c0, &c1, &cov00, &cov01, &cov11, &chisq);
92
93    rel = (c1/F_NOMINAL_Hz-1)*1000000;
94    printf("%+.2f ppm", rel);
95    if (ppm && fabs(rel) > ppm) {
96        printf(" (outside bounds)\n");
97        exit(1);
98    }
99    putchar('\n');
100}
101

Archive Download this file



interactive