| \1<\/td> | \2<\/td><\/tr>/' >>$HTML
64 |
65 | cat >>$HTML <
67 |
68 | IP_TABLE_FOOTER
69 |
70 | # Table: username/password
71 |
72 | cat >>$HTML <
74 |
75 | | Username/password |
76 | Attempts |
77 |
78 | USER_TABLE_HEADER
79 |
80 | <$LOG awk '/login attempt/ {
81 | user_password[$4]++
82 | }
83 |
84 | END {
85 | for (i in user_password) {
86 | count = user_password[i]
87 | gsub(/&/, "\\&", i)
88 | gsub(/>/, "\\>", i)
89 | gsub(/, "\\<", i)
90 | gsub(/"/, "\\"", i)
91 | print i ":" count
92 | }
93 | }' | tr -d '[]' | sort -nr -k 2,2 -t ':' | sed 's/\(.*\):\(.*\)/| \1<\/td> | \2<\/td><\/tr>/' >>$HTML
94 |
95 | cat >>$HTML <
97 |
98 | USER_TABLE_FOOTER
99 |
100 | # Table: remote SSH versions
101 |
102 | cat >>$HTML <
104 |
105 | | Remote SSH version |
106 | Count |
107 |
108 | VERSION_TABLE_HEADER
109 |
110 | <$LOG awk '/Remote SSH version/ {
111 | ssh_version[$5]++
112 | }
113 |
114 | END {
115 | for (i in ssh_version)
116 | print i ":" ssh_version[i]
117 | }' | sort -nr -k 2,2 -t ':' | sed 's/\(.*\):\(.*\)/| \1<\/td> | \2<\/td><\/tr>/' >>$HTML
118 |
119 | cat >>$HTML <
121 | VERSION_TABLE_FOOTER
122 |
123 | # HTML footer
124 |
125 | DATE=`date`
126 |
127 | cat >>$HTML <
129 | Generated on ${DATE}
130 |
131 |
132 | HTML_FOOTER
133 |
--------------------------------------------------------------------------------
/nbody/nbody_cpu/nbody_cpu.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 |
6 | typedef struct {
7 | float x, y, z;
8 | } float3;
9 |
10 | typedef struct {
11 | float x, y, z, w;
12 | } float4;
13 |
14 | /* #bodies */
15 | long N;
16 |
17 | /* #timesteps */
18 | static const long TIMESTEPS = 100;
19 | /* softening factor (square), G, \Delta t */
20 | static const float EPS = 0.1, G = 2., DELTA_T = 0.01;
21 |
22 | /* acceleration */
23 | float3 *a;
24 | /* mass */
25 | float *m;
26 | /* position */
27 | float3 *r;
28 | /* velocity */
29 | float3 *v;
30 |
31 | /* random number in [0,1] */
32 | static inline float rnd()
33 | {
34 | return (float)rand() / RAND_MAX;
35 | }
36 |
37 | void init();
38 |
39 | int main(int argc, char *argv[])
40 | {
41 | clock_t start, stop;
42 | double time;
43 | long i, j, timestep;
44 |
45 | float3 rij, ai;
46 | float dst_sqr, cube, inv_sqrt;
47 |
48 | if (argc != 2) {
49 | printf("usage: nbody_cpu #bodies\n");
50 | exit(1);
51 | }
52 |
53 | N = atol(argv[1]);
54 |
55 | /* alloc host memory */
56 | a = (float3 *)malloc(N*sizeof(float3));
57 | m = (float *)malloc(N*sizeof(float));
58 | r = (float3 *)malloc(N*sizeof(float3));
59 | v = (float3 *)malloc(N*sizeof(float3));
60 |
61 | srand(1);
62 | init();
63 |
64 | /* measure execution time */
65 | start = clock();
66 |
67 | /* integration steps */
68 | for (timestep = 0; timestep < TIMESTEPS; ++timestep) {
69 | /* update accelerations */
70 | for (i = 0; i < N; ++i) {
71 | ai.x = 0;
72 | ai.y = 0;
73 | ai.z = 0;
74 |
75 | for (j = 0; j < N; ++j) {
76 | /* distance vector */
77 | rij.x = r[j].x - r[i].x;
78 | rij.y = r[j].y - r[i].y;
79 | rij.z = r[j].z - r[i].z;
80 | /* compute acceleration */
81 | dst_sqr = rij.x * rij.x +
82 | rij.y * rij.y + rij.z * rij.z + EPS;
83 | cube = dst_sqr * dst_sqr * dst_sqr;
84 | inv_sqrt = 1. / sqrtf(cube);
85 | inv_sqrt *= m[j];
86 | /* acceleration a_i */
87 | ai.x += rij.x * inv_sqrt;
88 | ai.y += rij.y * inv_sqrt;
89 | ai.z += rij.z * inv_sqrt;
90 | }
91 |
92 | /* store result */
93 | a[i].x = G * ai.x;
94 | a[i].y = G * ai.y;
95 | a[i].z = G * ai.z;
96 | }
97 |
98 | /* leap frog */
99 | for (i = 0; i < N; ++i) {
100 | /* step with constant coordinates */
101 | v[i].x = v[i].x + a[i].x * DELTA_T;
102 | v[i].y = v[i].y + a[i].y * DELTA_T;
103 | v[i].z = v[i].z + a[i].z * DELTA_T;
104 | /* step with constant velocities */
105 | r[i].x = r[i].x + v[i].x * DELTA_T;
106 | r[i].y = r[i].y + v[i].y * DELTA_T;
107 | r[i].z = r[i].z + v[i].z * DELTA_T;
108 | }
109 | /*printf("#1: x: %f, y: %f, z: %f\n", r[0].x, r[0].y, r[0].z);
110 | printf("#2: x: %f, y: %f, z: %f\n", r[1].x, r[1].y, r[1].z);*/
111 | }
112 |
113 | stop = clock();
114 | time = (double)(stop - start) / CLOCKS_PER_SEC;
115 | /*printf("elapsed time: %f\n", time);
116 | printf("interactions/second: %f\n", (TIMESTEPS*(N*N))/time);*/
117 | printf("%li\t%f\n", N, (TIMESTEPS*(N*N))/time);
118 |
119 | /* free host memory */
120 | free(a);
121 | free(m);
122 | free(r);
123 | free(v);
124 |
125 | return 0;
126 | }
127 |
128 | /* generate initial configuration */
129 | void init()
130 | {
131 | long i;
132 |
133 | for (i = 0; i < N; ++i) {
134 | /* mass */
135 | m[i] = rnd()>0.5 ? 1. : 10.;
136 |
137 | /* velocity */
138 | v[i].x = 3.;
139 | v[i].y = rnd() * 10;
140 | v[i].z = -5.;
141 |
142 | /* position */
143 | r[i].x = rnd() * 50;
144 | r[i].y = rnd() * 50;
145 | r[i].z = rnd() * 50;
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/python/scipy.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | @author: m-thu
5 | """
6 |
7 | # (1, 2, 3): tuple (immutable)
8 | # [1, 2, 3]: list (mutable)
9 | # {"key": value}: dictionary (mutable)
10 |
11 |
12 |
13 | import numpy as np
14 |
15 | # help: np.array?
16 | # np.con*?
17 | # np.lookfor("create array")
18 |
19 |
20 |
21 | # 1D array
22 |
23 | a = np.array([0, 1, 2, 3])
24 | print("a:", a)
25 | print("a.ndim:", a.ndim)
26 | print("a.shape:", a.shape)
27 | print("len(a):", len(a), "\n\n")
28 |
29 |
30 |
31 | # 2D array
32 |
33 | b = np.array([[0, 1, 2], [3, 4, 5]])
34 | print("b:", b)
35 | print("b.ndim:", b.ndim)
36 | print("b.shape:", b.shape)
37 | print("len(b):", len(b), "\n\n") # first dimension
38 |
39 |
40 |
41 | # Creating arrays
42 |
43 | a = np.arange(10) # 0, 1, ..., n-1
44 | print("arange(10):", a, "\n")
45 |
46 | b = np.arange(1, 10, 2) # start, start+2, ..., stop-1
47 | print("arange(1, 10, 2):", b, "\n")
48 |
49 | c = np.linspace(0, 1, 10) # start; stop; number of points
50 | print("linspace(0, 1, 10):\n", c, "\n")
51 |
52 | d = np.ones((4, 4)) # all ones
53 | print("ones((4, 4)):\n", d, "\n")
54 |
55 | e = np.zeros((3, 3)) # all zeros
56 | print("zeros((3, 3)):\n", e, "\n")
57 |
58 | f = np.eye(2) # unity matrix (nxn)
59 | print("eye((2, 2)\n", f, "\n")
60 |
61 | g = np.diag(np.array([1, 2, 3, 4])) # diagonal matrix
62 | print("diag(np.array([1, 2, 3, 4])):\n", g, "\n\n")
63 |
64 |
65 |
66 | # Data types
67 |
68 | a = np.array([1, 2, 3])
69 | print("[1, 2, 3] dtype:", a.dtype, "\n")
70 |
71 | b = np.array([1., 2., 3.])
72 | print("[1., 2., 3.] dtype:", b.dtype, "\n")
73 |
74 | c = np.array([1, 2, 3], dtype=float) # specify type
75 | print("[1, 2, 3], dtype=float dtype:", c.dtype, "\n")
76 |
77 | d = np.array([1+1j, 2+2j, 3+3j]) # complex numbers
78 | print("[1+1j, 2+2j, 3+3j] dtype:", d.dtype, "\n\n")
79 |
80 |
81 |
82 | # pyplot: procedural interface
83 | import matplotlib.pyplot as plt
84 |
85 | # 1D plots
86 |
87 | x = np.linspace(0., 10., 20)
88 | y = x**2
89 | plt.figure()
90 | plt.plot(x, y)
91 | plt.plot(x, y, 'o')
92 | #plt.show()
93 |
94 | x = np.linspace(0., 2*np.pi)
95 | y1 = np.sin(x)
96 | y2 = np.cos(x)
97 | plt.figure()
98 | plt.plot(x, y1)
99 | plt.plot(x, y2)
100 | #plt.show()
101 |
102 |
103 |
104 | # Indexing, slicing
105 |
106 | a = np.arange(5)
107 | print("a:", a, "\n")
108 | print("a[0]:", a[0], "a[1]:", a[1], "a[-1]:", a[-1], "\n")
109 |
110 | print("a[::-1]: ", a[::-1], "\n\n") # reverse
111 |
112 |
113 |
114 | # Operations on arrays
115 |
116 | a = np.eye(3)
117 | a += 1
118 | print("a:", a, "\n")
119 |
120 | a = np.arange(5)
121 | b = a[::-1]
122 | c = b-a
123 | print("c:", c, "\n")
124 |
125 | d = a*a # elementwise multiplication
126 | print("d:", d, "\n")
127 |
128 | e = np.ones((2,2))
129 | print("e*e:\n", e*e, "\n") # elementwise
130 | print("e.dot(e):\n", e.dot(e), "\n") # matrix multiplication
131 |
132 | f = np.array([[0, -1j], [1j, 0]])
133 | print("f:\n", f, "\n")
134 | print("f^t:\n", f.T, "\n") # transpose (view of the original array)
135 |
136 | a = np.array([1, 2, 3, 4])
137 | print(np.sum(a), end="\n")
138 |
139 | b = np.array([[1, 2], [3, 4]])
140 | print("b:\n", b, "\n")
141 | print("sum of columns: ", np.sum(b, axis=0), "\n")
142 | print("sum of rows:", np.sum(b, axis=1), "\n")
143 | print("min:", np.min(b), "\tmax:", np.max(b), "\n")
144 | print("b.ravel():\n", b.ravel(), "\n") # flatten array
145 |
146 |
147 |
148 | # Polynomials
149 |
150 | # x^2 + 2*x + 3
151 | p = np.poly1d([1, 2, 3])
152 |
153 | print("p(0) =", p(0))
154 | print("order:", p.order)
155 | print("roots:", p.roots)
156 | print("p(root1) =", p(p.roots[0]))
157 | print("p(root2) =", p(p.roots[1]), "\n")
--------------------------------------------------------------------------------
/tempcontrol/README.md:
--------------------------------------------------------------------------------
1 | Temperature control (Raspberry Pi 2)
2 | ====================================
3 |
4 | ### raspi-config
5 | * 3 Boot Options -> Wait for network at boot -> No
6 | * 5 Interfacing Options -> P5 I2C -> Yes
7 | * 5 Interfacing Options -> P7 1-Wire -> Yes
8 |
9 | ### DS1307 module
10 | Remove `R2` and `R3` pullups (3K3)
11 |
12 | Wiring:
13 | ```
14 | 5 V ------ VCC (DS1307)
15 | I2C1 SCL <----> SCL (DS1307)
16 | I2C1 SDA <----> SDA (DS1307)
17 | GND ------ GND (DS1307)
18 | ```
19 |
20 | Test module with `sudo i2cdetect -y 1`:
21 | ```
22 | 0 1 2 3 4 5 6 7 8 9 a b c d e f
23 | 00: -- -- -- -- -- -- -- -- -- -- -- -- --
24 | 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
25 | 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
26 | 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
27 | 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
28 | 50: 50 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
29 | 60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- --
30 | 70: -- -- -- -- -- -- -- --
31 | ```
32 |
33 | `/etc/rc.local`:
34 | ```sh
35 | /bin/echo ds1307 0x68 >/sys/class/i2c-adapter/i2c-1/new_device
36 | hwclock -s
37 | ```
38 |
39 | ```sh
40 | sudo sh -c 'echo rtc-ds1307 >>/etc/modules'
41 | ```
42 |
43 | ### GPIOs
44 | `/etc/rc.local`:
45 | ```sh
46 | # GPIO 27: Heater 1 (output)
47 | /bin/echo 27 >/sys/class/gpio/export
48 | /bin/echo out >/sys/class/gpio/gpio27/direction
49 |
50 | # GPIO 22: Heater 2 (output)
51 | /bin/echo 22 >/sys/class/gpio/export
52 | /bin/echo out >/sys/class/gpio/gpio22/direction
53 |
54 | # GPIO 16: Status LED (output)
55 | /bin/echo 16 >/sys/class/gpio/export
56 | /bin/echo out >/sys/class/gpio/gpio16/direction
57 |
58 | # GPIO 26: Shutdown switch (input, active low)
59 | /bin/echo 26 >/sys/class/gpio/export
60 | /bin/echo in >/sys/class/gpio/gpio26/direction
61 | ```
62 |
63 | `/etc/rc.local`:
64 | ```sh
65 | nohup /home/pi/shutdown.sh &
66 | date >>/root/startup.log
67 | ```
68 |
69 | ### DS18B20
70 | Wiring:
71 | ```
72 | 3.3 V --o---- VDD (DS18B20)
73 | |
74 | ---
75 | | | 4K7
76 | | | Pullup
77 | | |
78 | ---
79 | |
80 | GPIO 4 <-o---> DQ (DS18B20)
81 | GND ------- GND (DS18B20)
82 | ```
83 |
84 | Test sensors:
85 | ```sh
86 | pi@raspberrypi:~ $ ls -l /sys/bus/w1/devices/
87 | total 0
88 | lrwxrwxrwx 1 root root 0 May 12 20:52 28-0416927dcdff -> ../../../devices/w1_bus_master1/28-0416927dcdff
89 | lrwxrwxrwx 1 root root 0 May 12 20:52 28-051691e2c3ff -> ../../../devices/w1_bus_master1/28-051691e2c3ff
90 | lrwxrwxrwx 1 root root 0 May 12 20:52 28-051691e533ff -> ../../../devices/w1_bus_master1/28-051691e533ff
91 | lrwxrwxrwx 1 root root 0 May 12 20:52 w1_bus_master1 -> ../../../devices/w1_bus_master1
92 | pi@raspberrypi:~ $ cat /sys/bus/w1/devices/28-0416927dcdff/
93 | driver/ id name power/ subsystem/ uevent w1_slave
94 | pi@raspberrypi:~ $ cat /sys/bus/w1/devices/28-0416927dcdff/w1_slave
95 | 6e 01 4b 46 7f ff 0c 10 ad : crc=ad YES
96 | 6e 01 4b 46 7f ff 0c 10 ad t=22875
97 | pi@raspberrypi:~ $ cat /sys/bus/w1/devices/28-051691e2c3ff/w1_slave
98 | 6e 01 4b 46 7f ff 0c 10 ad : crc=ad YES
99 | 6e 01 4b 46 7f ff 0c 10 ad t=22875
100 | pi@raspberrypi:~ $ cat /sys/bus/w1/devices/28-051691e533ff/w1_slave
101 | 69 01 4b 46 7f ff 0c 10 7d : crc=7d YES
102 | 69 01 4b 46 7f ff 0c 10 7d t=22562
103 | ```
104 |
105 | ### tempcontrol.c
106 | `/etc/rc.local`:
107 | ```sh
108 | nohup /home/pi/tempcontrol 0.5 &
109 | ```
110 |
111 | ### References
112 | [DS1307 datasheet](https://datasheets.maximintegrated.com/en/ds/DS1307.pdf)
113 |
114 | [DS18B20 datasheet](https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf)
115 |
--------------------------------------------------------------------------------
/icestick/ws2812/ws2812_tx.v:
--------------------------------------------------------------------------------
1 | // Lint with: verilator --lint-only ws2812_tx.v
2 |
3 | `default_nettype none
4 | `timescale 1ns / 1ps
5 |
6 | module ws2812_tx #(
7 | // Clock frequency / Hz
8 | parameter F_CLK = 48e6
9 | )(
10 | input [23:0] data,
11 | input clk, rst, start,
12 | output reg dout,
13 | output wire bsy
14 | );
15 | // FSM states
16 | localparam IDLE = 5'b00001,
17 | T0H = 5'b00010,
18 | T0L = 5'b00100,
19 | T1H = 5'b01000,
20 | T1L = 5'b10000;
21 |
22 | localparam
23 | // Bit 0, high time
24 | T_T0H = 350e-9, // s
25 | // Bit 0, low time
26 | T_T0L = 800e-9, // s
27 | // Bit 1, high time
28 | T_T1H = 700e-9, // s
29 | // Bit 1, low time
30 | T_T1L = 600e-9; // S
31 |
32 | localparam
33 | // Bit 0, cycles high time
34 | N_T0H = 17,//$ceil(T_T0H * F_CLK),
35 | // Bit 0, cycles low time
36 | N_T0L = 39,//$ceil(T_T0L * F_CLK),
37 | // Bit 1, cycles high time
38 | N_T1H = 34,//$ceil(T_T1H * F_CLK),
39 | // Bit 1, cycles low time
40 | N_T1L = 29;//$ceil(T_T1L * F_CLK);
41 |
42 | // Counter width for delay
43 | localparam CNT = $clog2($rtoi($ceil(T_T0L * F_CLK)));
44 |
45 | reg [4:0] state, next_state;
46 | reg [4:0] n, next_n;
47 | reg [CNT-1:0] cnt, next_cnt;
48 |
49 | // State register
50 | always @(posedge clk, negedge rst) begin
51 | if (!rst)
52 | state <= IDLE;
53 | else begin
54 | state <= next_state;
55 | n <= next_n;
56 | cnt <= next_cnt;
57 | end
58 | end
59 |
60 | // Next state logic
61 | always @* begin
62 | // Defaults
63 | next_state = state;
64 | next_n = n;
65 | next_cnt = cnt;
66 | dout = 1'b0;
67 |
68 | /* verilator lint_off CASEINCOMPLETE */
69 | case (state)
70 | IDLE: begin
71 | // Begin transmission when start signal gets asserted
72 | if (start)
73 | // MSB is transmitted first
74 | if (data[23] == 1'b1)
75 | next_state = T1H;
76 | else
77 | next_state = T0H;
78 | next_n = 5'd23;
79 | next_cnt = 0;
80 | dout = 1'b0;
81 | end
82 |
83 | T0H: begin
84 | if (cnt < N_T0H)
85 | next_cnt = cnt + 1'b1;
86 | else begin
87 | // Reset counter
88 | next_cnt = 0;
89 | next_state = T0L;
90 | end
91 |
92 | dout = 1'b1;
93 | end
94 |
95 | T0L: begin
96 | if (cnt < N_T0L)
97 | next_cnt = cnt + 1'b1;
98 | else begin
99 | // Reset counter
100 | next_cnt = 0;
101 |
102 | // Jump to idle state if this was the last bit
103 | if (n == 0)
104 | next_state = IDLE;
105 | else begin
106 | // Determine if next bit is 1 or 0
107 | next_n = n - 1'b1;
108 | if (data[next_n] == 1'b1)
109 | next_state = T1H;
110 | else
111 | next_state = T0H;
112 | end
113 |
114 | end
115 |
116 | dout = 1'b0;
117 | end
118 |
119 | T1H: begin
120 | if (cnt < N_T1H)
121 | next_cnt = cnt + 1'b1;
122 | else begin
123 | // Reset counter
124 | next_cnt = 0;
125 | next_state = T1L;
126 | end
127 |
128 | dout = 1'b1;
129 | end
130 |
131 | T1L: begin
132 | if (cnt < N_T1L)
133 | next_cnt = cnt + 1'b1;
134 | else begin
135 | // Reset counter
136 | next_cnt = 0;
137 |
138 | // Jump to idle state if this was the last bit
139 | if (n == 0)
140 | next_state = IDLE;
141 | else begin
142 | // Determine if next bit is 1 or 0
143 | next_n = n - 1'b1;
144 | if (data[next_n] == 1'b1)
145 | next_state = T1H;
146 | else
147 | next_state = T0H;
148 | end
149 | end
150 |
151 | dout = 1'b0;
152 | end
153 | endcase
154 | /* verilator lint_on CASEINCOMPLETE */
155 | end
156 |
157 | assign bsy = !(state == IDLE);
158 | endmodule
159 |
--------------------------------------------------------------------------------
/libnfc/list-tags.c:
--------------------------------------------------------------------------------
1 | /* Lists all tags in vicinity of reader */
2 |
3 | /* for sigaction */
4 | #define _POSIX_SOURCE
5 |
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 |
13 | static const int MAX_DEVICES = 32;
14 | static const int MAX_TARGETS = 32;
15 |
16 | /* global, so signal handler can access those */
17 | nfc_context *context;
18 | nfc_device *dev;
19 |
20 | static void handler_sigint(int);
21 |
22 | int main()
23 | {
24 | struct sigaction sa;
25 | nfc_connstring connstrings[MAX_DEVICES];
26 | int err = EXIT_SUCCESS;
27 |
28 | /* Init libnfc */
29 | nfc_init(&context);
30 | if (context == NULL) {
31 | printf("Error initializing libnfc!\n");
32 | err = EXIT_FAILURE;
33 | goto error;
34 | }
35 | printf("libnfc version: %s\n", nfc_version());
36 |
37 | /* Install signal handler for SIGINT */
38 | sigemptyset(&sa.sa_mask);
39 | sa.sa_handler = handler_sigint;
40 | if (sigaction(SIGINT, &sa, NULL) < 0) {
41 | perror("sigaction");
42 | err = EXIT_FAILURE;
43 | goto error;
44 | }
45 |
46 | /* Find supported device */
47 | for (size_t i = 0; i < nfc_list_devices(context, connstrings, MAX_DEVICES); ++i) {
48 | if ((dev = nfc_open(context, connstrings[i])) == NULL) {
49 | printf("Failed to open device '%s'!\n", connstrings[i]);
50 | continue;
51 | } else {
52 | printf("Opened device '%s'\n", connstrings[i]);
53 | break;
54 | }
55 | }
56 | if (dev == NULL) {
57 | printf("No supported device found!\n");
58 | err = EXIT_FAILURE;
59 | goto error;
60 | }
61 |
62 | const nfc_modulation_type *supported_mt;
63 |
64 | /* Get supported modulation types as initiator */
65 | if (nfc_device_get_supported_modulation(dev, N_INITIATOR, &supported_mt) < 0) {
66 | nfc_perror(dev, "nfc_device_get_supported_modulation");
67 | err = EXIT_FAILURE;
68 | goto error;
69 | }
70 |
71 | /* Initialize NFC device as initiator */
72 | if (nfc_initiator_init(dev) < 0) {
73 | nfc_perror(dev, "nfc_initiator_init");
74 | err = EXIT_FAILURE;
75 | goto error;
76 | }
77 | /* Disable forced ISO 14443-A mode (enabled by default) */
78 | if (nfc_device_set_property_bool(dev, NP_FORCE_ISO14443_A, false) < 0) {
79 | nfc_perror(dev, "nfc_device_set_property");
80 | err = EXIT_FAILURE;
81 | goto error;
82 | }
83 | /* Disable forced speed of 106 kbps (enabled by default) */
84 | if (nfc_device_set_property_bool(dev, NP_FORCE_SPEED_106, false) < 0) {
85 | nfc_perror(dev, "nfc_device_set_property");
86 | err = EXIT_FAILURE;
87 | goto error;
88 | }
89 |
90 | /* List all targets for each modulation type */
91 | while (*supported_mt) {
92 | const nfc_baud_rate *supported_br;
93 |
94 | printf("\nListing tags with modulation type %s, ", str_nfc_modulation_type(*supported_mt));
95 |
96 | /* Get supported baud rates for mod. type and find the slowest */
97 | if (nfc_device_get_supported_baud_rate(dev, *supported_mt, &supported_br) < 0) {
98 | nfc_perror(dev, "nfc_device_get_supported_baud_rate");
99 | err = EXIT_FAILURE;
100 | goto error;
101 | }
102 | while (*supported_br)
103 | ++supported_br;
104 | --supported_br;
105 | printf("baud rate: %s\n", str_nfc_baud_rate(*supported_br));
106 |
107 |
108 | nfc_modulation mod;
109 | mod.nmt = *supported_mt;
110 | mod.nbr = *supported_br;
111 |
112 | int tags;
113 | nfc_target targets[MAX_TARGETS];
114 |
115 | /* List passive targets */
116 | if ((tags = nfc_initiator_list_passive_targets(dev, mod, targets, MAX_TARGETS)) < 0) {
117 | nfc_perror(dev, "nfc_initiator_list_passive_targets");
118 | err = EXIT_FAILURE;
119 | goto error;
120 | }
121 |
122 | for (int i = 0; i < tags; ++i) {
123 | char *target_info;
124 |
125 | if (str_nfc_target(&target_info, &targets[i], true) < 0) {
126 | nfc_perror(dev, "str_nfc_target");
127 | err = EXIT_FAILURE;
128 | goto error;
129 | }
130 |
131 | printf("\n=====\nTag %i\n=====\n%s\n", i, target_info);
132 | nfc_free(target_info);
133 | }
134 |
135 | ++supported_mt;
136 | }
137 |
138 | error:
139 | if (dev)
140 | nfc_close(dev);
141 | if (context)
142 | nfc_exit(context);
143 | return err;
144 | }
145 |
146 | static void handler_sigint(int signal)
147 | {
148 | (void)signal;
149 |
150 | if (dev != NULL) {
151 | nfc_abort_command(dev);
152 | } else {
153 | if (context)
154 | nfc_exit(context);
155 | exit(EXIT_FAILURE);
156 | }
157 | }
158 |
--------------------------------------------------------------------------------
/openscad/parallela.scad:
--------------------------------------------------------------------------------
1 | // Baseplate for Parallela board with fan
2 |
3 | $fa = 1;
4 | $fs = 0.4;
5 |
6 | eps = 0.01;
7 |
8 | // Dimensions rectangular plate
9 | // with standoff holes
10 | length = 110.0;
11 | width = 95.0;
12 | height = 4.0;
13 | standoff_diameter = 3.0;
14 | standoff_x_dist = length - 4*standoff_diameter;
15 | standoff_y_dist = width - 4*standoff_diameter;
16 | standoff_counterbore = 2.0;
17 | standoff_counterbore_r = 3.0;
18 |
19 | // Parallela board mounting holes
20 | parallela_hole_diameter = 3.0;
21 | parallela_hole_x_dist = 83.0 - 2*parallela_hole_diameter;
22 | parallela_hole_y_dist = 51.4 - 2*parallela_hole_diameter;
23 | parallela_counterbore = 2.0;
24 | parallela_counterbore_r = 6.0 / 2;
25 |
26 | // Fan mounting holes (rectangular)
27 | fan_hole_diameter = 3.0;
28 | fan_hole_dist = 76.0 - 2*fan_hole_diameter;
29 | fan_counterbore_r = 6.0 / 2;
30 | fan_counterbore = 2.0;
31 |
32 | difference() {
33 | cube([length,width,height], center=true);
34 |
35 | union() {
36 | // Standoff holes
37 | union() {
38 | // Screw holes
39 | translate([standoff_x_dist/2,standoff_y_dist/2,0]) cylinder(h=height+2*eps, r=standoff_diameter/2, center=true);
40 | translate([-standoff_x_dist/2,standoff_y_dist/2,0]) cylinder(h=height+2*eps, r=standoff_diameter/2, center=true);
41 | translate([standoff_x_dist/2,-standoff_y_dist/2,0]) cylinder(h=height+2*eps, r=standoff_diameter/2, center=true);
42 | translate([-standoff_x_dist/2,-standoff_y_dist/2,0]) cylinder(h=height+2*eps, r=standoff_diameter/2, center=true);
43 |
44 | // Counterbore
45 | translate([standoff_x_dist/2,standoff_y_dist/2,0]) cylinder(r=standoff_counterbore_r, h=standoff_counterbore+eps, $fn=6);
46 | translate([-standoff_x_dist/2,standoff_y_dist/2,0]) cylinder(r=standoff_counterbore_r, h=standoff_counterbore+eps, $fn=6);
47 | translate([standoff_x_dist/2,-standoff_y_dist/2,0]) cylinder(r=standoff_counterbore_r, h=standoff_counterbore+eps, $fn=6);
48 | translate([-standoff_x_dist/2,-standoff_y_dist/2,0]) cylinder(r=standoff_counterbore_r, h=standoff_counterbore+eps, $fn=6);
49 | }
50 |
51 | // Parallela board mounting holes
52 | union() {
53 | // Screw holes
54 | translate([parallela_hole_x_dist/2,parallela_hole_y_dist/2,0]) cylinder(h=height+2*eps, r=parallela_hole_diameter/2, center=true);
55 | translate([-parallela_hole_x_dist/2,parallela_hole_y_dist/2,0]) cylinder(h=height+2*eps, r=parallela_hole_diameter/2, center=true);
56 | translate([parallela_hole_x_dist/2,-parallela_hole_y_dist/2,0]) cylinder(h=height+2*eps, r=parallela_hole_diameter/2, center=true);
57 | translate([-parallela_hole_x_dist/2,-parallela_hole_y_dist/2,0]) cylinder(h=height+2*eps, r=parallela_hole_diameter/2, center=true);
58 |
59 | // Counterbore
60 | translate([parallela_hole_x_dist/2,parallela_hole_y_dist/2,-height/2-eps]) cylinder(r=parallela_counterbore_r, h=parallela_counterbore);
61 | translate([-parallela_hole_x_dist/2,parallela_hole_y_dist/2,-height/2-eps]) cylinder(r=parallela_counterbore_r, h=parallela_counterbore);
62 | translate([parallela_hole_x_dist/2,-parallela_hole_y_dist/2,-height/2-eps]) cylinder(r=parallela_counterbore_r, h=parallela_counterbore);
63 | translate([-parallela_hole_x_dist/2,-parallela_hole_y_dist/2,-height/2-eps]) cylinder(r=parallela_counterbore_r, h=parallela_counterbore);
64 | }
65 |
66 | // Fan mounting holes
67 | union() {
68 | // Screw holes
69 | translate([fan_hole_dist/2,fan_hole_dist/2,0]) cylinder(h=height+2*eps, r=fan_hole_diameter/2, center=true);
70 | translate([-fan_hole_dist/2,fan_hole_dist/2,0]) cylinder(h=height+2*eps, r=fan_hole_diameter/2, center=true);
71 | translate([fan_hole_dist/2,-fan_hole_dist/2,0]) cylinder(h=height+2*eps, r=fan_hole_diameter/2, center=true);
72 | translate([-fan_hole_dist/2,-fan_hole_dist/2,0]) cylinder(h=height+2*eps, r=fan_hole_diameter/2, center=true);
73 |
74 | // Counterbore
75 | translate([fan_hole_dist/2,fan_hole_dist/2,-height/2-eps]) cylinder(r=fan_counterbore_r, h=fan_counterbore);
76 | translate([-fan_hole_dist/2,fan_hole_dist/2,-height/2-eps]) cylinder(r=fan_counterbore_r, h=fan_counterbore);
77 | translate([fan_hole_dist/2,-fan_hole_dist/2,-height/2-eps]) cylinder(r=fan_counterbore_r, h=fan_counterbore);
78 | translate([-fan_hole_dist/2,-fan_hole_dist/2,-height/2-eps]) cylinder(r=fan_counterbore_r, h=fan_counterbore);
79 | }
80 | }
81 | }
--------------------------------------------------------------------------------
/libnfc/dump-girogo.c:
--------------------------------------------------------------------------------
1 | /* Dumps girogo cards */
2 |
3 | /* for sigaction */
4 | #define _POSIX_SOURCE
5 |
6 | #include
7 | #include
8 | #include
9 | #include
10 | #include
11 | #include
12 | #include
13 |
14 | static const int MAX_DEVICES = 32;
15 | static const int MAX_TARGETS = 32;
16 |
17 | static const size_t MAX_RX_LENGTH = 64;
18 |
19 | /* girogo commands */
20 | static const uint8_t DF_BOERSE[] = {0x00, 0xa4, 0x04, 0x0c, 0x09, 0xd2, 0x76, 0x00, 0x00, 0x25, 0x45, 0x50, 0x02, 0x00};
21 | static const uint8_t EF_BETRAG[] = {0x00, 0xb2, 0x01, 0xc4, 0x00};
22 | static const uint8_t EF_ID[] = {0x00, 0xb2, 0x01, 0xbc, 0x00};
23 | static const uint8_t EF_BOERSE[] = {0x00, 0xb2, 0x01, 0xcc, 0x00};
24 |
25 | /* Global, so signal handler can access those */
26 | nfc_context *context;
27 | nfc_device *dev;
28 |
29 | static void handler_sigint(int);
30 | static void dump_girogo(void);
31 | static void dump_buffer(char *, uint8_t *, int);
32 |
33 | int main()
34 | {
35 | struct sigaction sa;
36 | nfc_connstring connstrings[MAX_DEVICES];
37 | int err = EXIT_SUCCESS;
38 |
39 | /* Init libnfc */
40 | nfc_init(&context);
41 | if (context == NULL) {
42 | printf("Error initializing libnfc!\n");
43 | err = EXIT_FAILURE;
44 | goto error;
45 | }
46 | printf("libnfc version: %s\n", nfc_version());
47 |
48 | /* Install signal handler for SIGINT */
49 | sigemptyset(&sa.sa_mask);
50 | sa.sa_handler = handler_sigint;
51 | if (sigaction(SIGINT, &sa, NULL) < 0) {
52 | perror("sigaction");
53 | err = EXIT_FAILURE;
54 | goto error;
55 | }
56 |
57 | /* Find supported device */
58 | for (size_t i = 0; i < nfc_list_devices(context, connstrings, MAX_DEVICES); ++i) {
59 | if ((dev = nfc_open(context, connstrings[i])) == NULL) {
60 | printf("Failed to open device '%s'!\n", connstrings[i]);
61 | continue;
62 | } else {
63 | printf("Opened device '%s'\n", connstrings[i]);
64 | break;
65 | }
66 | }
67 | if (dev == NULL) {
68 | printf("No supported device found!\n");
69 | err = EXIT_FAILURE;
70 | goto error;
71 | }
72 |
73 | /* Initialize NFC device as initiator */
74 | if (nfc_initiator_init(dev) < 0) {
75 | nfc_perror(dev, "nfc_initiator_init");
76 | err = EXIT_FAILURE;
77 | goto error;
78 | }
79 |
80 | /* Set modulation type */
81 | nfc_modulation mod;
82 | mod.nmt = NMT_ISO14443A;
83 | mod.nbr = NBR_106;
84 |
85 | int tags;
86 | nfc_target target;
87 |
88 | /* Poll for targets */
89 | printf("\nPolling for tags ...\n");
90 | if ((tags = nfc_initiator_poll_target(dev, &mod, 1, 10, 0x01, &target)) < 0) {
91 | nfc_perror(dev, "nfc_initiator_poll_target");
92 | err = EXIT_FAILURE;
93 | goto error;
94 | }
95 | printf("... %i tag%s found.\n", tags, tags==1?"":"s");
96 |
97 | if (tags > 0)
98 | dump_girogo();
99 |
100 | error:
101 | if (dev)
102 | nfc_close(dev);
103 | if (context)
104 | nfc_exit(context);
105 | return err;
106 | }
107 |
108 | static void dump_girogo(void)
109 | {
110 | uint8_t rx_buf[MAX_RX_LENGTH];
111 | int rx;
112 |
113 | /* Select DF_BOERSE */
114 | if ((rx = nfc_initiator_transceive_bytes(dev, DF_BOERSE, sizeof DF_BOERSE, rx_buf, MAX_RX_LENGTH, 1000)) < 0) {
115 | nfc_perror(dev, "nfc_initiator_transceive_bytes");
116 | return;
117 | }
118 | if (rx >= 2 && rx_buf[0] == 0x90 && rx_buf[1] == 0x00) {
119 | printf("\nGeldKarte found!\n\n");
120 | } else {
121 | printf("\nCard not supported!\n\n");
122 | return;
123 | }
124 |
125 | /* EF_BETRAG */
126 | if ((rx = nfc_initiator_transceive_bytes(dev, EF_BETRAG, sizeof EF_BETRAG, rx_buf, MAX_RX_LENGTH, 1000)) < 0) {
127 | nfc_perror(dev, "nfc_initiator_transceive_bytes");
128 | return;
129 | }
130 | dump_buffer("EF_BETRAG", rx_buf, rx);
131 |
132 | /* EF_ID */
133 | if ((rx = nfc_initiator_transceive_bytes(dev, EF_ID, sizeof EF_ID, rx_buf, MAX_RX_LENGTH, 1000)) < 0) {
134 | nfc_perror(dev, "nfc_initiator_transceive_bytes");
135 | return;
136 | }
137 | dump_buffer("EF_ID", rx_buf, rx);
138 |
139 | /* EF_BOERSE */
140 | if ((rx = nfc_initiator_transceive_bytes(dev, EF_BOERSE, sizeof EF_BOERSE, rx_buf, MAX_RX_LENGTH, 1000)) < 0) {
141 | nfc_perror(dev, "nfc_initiator_transceive_bytes");
142 | return;
143 | }
144 | dump_buffer("EF_BOERSE", rx_buf, rx);
145 | }
146 |
147 | static void handler_sigint(int signal)
148 | {
149 | (void)signal;
150 |
151 | if (dev != NULL) {
152 | nfc_abort_command(dev);
153 | } else {
154 | if (context)
155 | nfc_exit(context);
156 | exit(EXIT_FAILURE);
157 | }
158 | }
159 |
160 | static void dump_buffer(char *buf_name, uint8_t *buf, int size)
161 | {
162 | printf("%s, length: %i\n\t", buf_name, size);
163 | for (int i = 0; i < size; ++i)
164 | printf("%02x%s", buf[i], i
26 | * [Yosys Manual](http://www.clifford.at/yosys/files/yosys_manual.pdf)
27 |
28 | Dialog Semiconductors Resources:
29 | * [GreenPAK](https://www.dialog-semiconductor.com/products/greenpak)
30 |
31 | Development Board (old name: GreenPAK 4 Dev Board):
32 | * [GreenPAK Advanced Development
33 | Board](https://www.dialog-semiconductor.com/products/greenpak/slg4dvkadv)
34 |
35 | Dialog Datasheets:
36 | * [SLG46140V](https://www.dialog-semiconductor.com/products/greenpak/slg46140):
37 |
38 | * [SLG46620](https://www.dialog-semiconductor.com/products/greenpak/slg46620):
39 |
40 |
41 | Go Configure Software Hub (includes GreenPAK Designer) 6.27.001:
42 | * Windows 32 bit:
43 |
44 | * Windows 64 bit:
45 |
46 | * Ubuntu 18.04/20.04 64 bit:
47 |
48 | * Debian-testing 32 bit:
49 |
50 | * Debian-testing 64 bit:
51 |
52 | * macOS:
53 |
54 | Ubuntu 20.04:
55 |
56 | Openfpga project:
57 |
58 | ```
59 | openfpga/src/gpcosim/gpcosim.cpp:20:10: fatal error: vpi_user.h: No
60 | such file or directory
61 | 20 | #include
62 | | ^~~~~~~~~~~~
63 | compilation terminated.
64 | make[2]: *** [src/gpcosim/CMakeFiles/gpcosim.dir/build.make:63:
65 | src/gpcosim/CMakeFiles/gpcosim.dir/gpcosim.cpp.o] Error 1
66 | make[1]: *** [CMakeFiles/Makefile2:582:
67 | src/gpcosim/CMakeFiles/gpcosim.dir/all] Error 2
68 | make: *** [Makefile:141: all] Error 2
69 | ```
70 |
71 | Install Icarus Verilog:
72 | ```sh
73 | git clone git://github.com/steveicarus/iverilog.git
74 | sudo apt-get install build-essential autoconf gperf flex bison
75 | cd iverilog && sh autoconf.sh
76 | ./configure && make && sudo make install
77 | ```
78 |
79 | ```
80 | yosys -p 'read_verilog counter.v' \
81 | -p 'synth_greenpak4 -part SLG46620V -json counter.json'
82 | make: yosys: Command not found
83 | make: *** [../../Makefile.common:9: counter.json] Error 127
84 | ```
85 |
86 | Install Yosys:
87 | ```sh
88 | git clone https://github.com/YosysHQ/yosys.git
89 | sudo apt-get install build-essential clang bison flex \
90 | libreadline-dev gawk tcl-dev libffi-dev git \
91 | graphviz xdot pkg-config python3 libboost-system-dev \
92 | libboost-python-dev libboost-filesystem-dev zlib1g-dev
93 | cd yosys && make && sudo make install
94 | ```
95 |
96 | Compile counter example:
97 | ```sh
98 | cd primitives/counter_inference
99 | make
100 |
101 | ...
102 |
103 | 2.29. Executing JSON backend.
104 |
105 | End of script. Logfile hash: 7ad2fcd95c, CPU: user 0.13s system 0.03s,
106 | MEM: 16.83 MB peak
107 | Yosys 0.11+52 (git sha1 UNKNOWN, clang 10.0.0-4ubuntu1 -fPIC -Os)
108 | Time spent: 60% 4x abc (0 sec), 12% 7x read_verilog (0 sec), ...
109 | gp4par counter.json -o counter.txt -p SLG46620V
110 | GreenPAK 4 place-and-route by Andrew D. Zonenberg.
111 |
112 | License: LGPL v2.1+
113 | This is free software: you are free to change and redistribute it.
114 | There is NO WARRANTY, to the extent permitted by law.
115 |
116 | Loading Yosys JSON file "counter.json".
117 | Netlist creator: Yosys 0.11+52 (git sha1 UNKNOWN, clang 10.0.0-4ubuntu1 -fPIC -O
118 | s)
119 |
120 | Loading modules...
121 | ERROR: module child should be of type object but isn't
122 | make: *** [../../Makefile.common:13: counter.txt] Segmentation fault
123 | (core dumped)
124 | ```
125 |
126 | Versions:
127 | * Icarus Verilog: commit 71c36d1289873e9e9fb2699c1de1f22dee2021e6
128 | * Yosys: commit 2be110cb0ba645f95f62ee01b6a6fa46a85d5b26
129 | * openfpga: commit f9ae535d0372c246075d1bb05a409adaed0135e7
130 |
--------------------------------------------------------------------------------
/coq/Basics.v:
--------------------------------------------------------------------------------
1 | (* Enumerated Type *)
2 | (*Inductive bool : Type :=
3 | (* Constructors *)
4 | | false : bool
5 | | true : bool.
6 |
7 | Definition negb (b : bool) : bool :=
8 | match b with
9 | | false => true
10 | | true => false
11 | end.
12 |
13 | (* Definition andb (b1 : bool) (b2 : bool) : bool := *)
14 | Definition andb (b1 b2 : bool) : bool :=
15 | match b1 with
16 | | true => b2
17 | | false => false
18 | end.
19 |
20 | Infix "&&" := andb.*)
21 |
22 | (*********)
23 | (* nandb *)
24 | (*********)
25 |
26 | Definition nandb (b1 b2 : bool) : bool :=
27 | negb (b1 && b2).
28 |
29 | Example ex_nandb1 : (nandb false false) = true.
30 | Proof. simpl. reflexivity. Qed.
31 | Example ex_nandb2 : (nandb false true ) = true.
32 | Proof. simpl. reflexivity. Qed.
33 | Example ex_nandb3 : (nandb true false) = true.
34 | Proof. simpl. reflexivity. Qed.
35 | Example ex_nandb4 : (nandb true true ) = false.
36 | Proof. simpl. reflexivity. Qed.
37 |
38 | (*********)
39 | (* andb3 *)
40 | (*********)
41 |
42 | Definition andb3 (b1 b2 b3 : bool) : bool :=
43 | b1 && b2 && b3.
44 |
45 | Example ex_andb3_1 : (andb3 false false false) = false.
46 | Proof. simpl. reflexivity. Qed.
47 | Example ex_andb3_2 : (andb3 false false true ) = false.
48 | Proof. simpl. reflexivity. Qed.
49 | Example ex_andb3_3 : (andb3 false true false) = false.
50 | Proof. simpl. reflexivity. Qed.
51 | Example ex_andb3_4 : (andb3 false true true ) = false.
52 | Proof. simpl. reflexivity. Qed.
53 | Example ex_andb3_5 : (andb3 true false false) = false.
54 | Proof. simpl. reflexivity. Qed.
55 | Example ex_andb3_6 : (andb3 true false true ) = false.
56 | Proof. simpl. reflexivity. Qed.
57 | Example ex_andb3_7 : (andb3 true true false) = false.
58 | Proof. simpl. reflexivity. Qed.
59 | Example ex_andb3_8 : (andb3 true true true ) = true.
60 | Proof. simpl. reflexivity. Qed.
61 |
62 | (*************)
63 | (* factorial *)
64 | (*************)
65 |
66 | (* Fixpoint: recursive definition *)
67 | Fixpoint factorial (n : nat) : nat :=
68 | match n with
69 | | O => 1
70 | (* | S n' => mult n (factorial n') *)
71 | | S n' => n * (factorial n')
72 | end.
73 |
74 | Example ex_factorial1 : (factorial 0) = 1.
75 | Proof. simpl. reflexivity. Qed.
76 | Example ex_factorial2 : (factorial 1) = 1.
77 | Proof. simpl. reflexivity. Qed.
78 | Example ex_factorial3 : (factorial 5) = 120.
79 | Proof. simpl. reflexivity. Qed.
80 |
81 | (***********)
82 | (* blt_nat *)
83 | (***********)
84 |
85 | Fixpoint be_nat (n m : nat) : bool :=
86 | match n with
87 | | O => match m with
88 | | O => true
89 | | S m' => false
90 | end
91 | | S n' => match m with
92 | | O => true
93 | | S m' => be_nat n' m'
94 | end
95 | end.
96 |
97 | Fixpoint ble_nat (n m : nat) : bool :=
98 | match n with
99 | | O => true
100 | | S n' => match m with
101 | | O => false
102 | | S m' => ble_nat n' m'
103 | end
104 | end.
105 |
106 | Definition blt_nat (n m : nat) : bool :=
107 | (negb (be_nat n m)) && (ble_nat n m).
108 |
109 | Example ex_blt_nat_1 : (blt_nat 2 2) = false.
110 | Proof. simpl. reflexivity. Qed.
111 | Example ex_blt_nat_2 : (blt_nat 2 4) = true.
112 | Proof. simpl. reflexivity. Qed.
113 | Example ex_blt_nat_3 : (blt_nat 4 2) = false.
114 | Proof. simpl. reflexivity. Qed.
115 |
116 | (********************)
117 | (* plus_id_exercise *)
118 | (********************)
119 |
120 | (* -> "implies" *)
121 |
122 | Theorem plus_id_exercise : forall n m o : nat,
123 | n = m -> m = o -> n + m = m + o.
124 |
125 | Proof.
126 | (* Move n, m, o from goal to assumptions *)
127 | intros n m o.
128 | (* Move hypotheses into context *)
129 | intros H H'.
130 | (* Rewrite goal using hypotheses from left to right *)
131 | rewrite -> H.
132 | rewrite -> H'.
133 | (* Check both sides for equal values *)
134 | reflexivity.
135 | Qed.
136 |
137 | (************)
138 | (* mult_S_1 *)
139 | (************)
140 |
141 | Theorem mult_S_1 : forall n m : nat,
142 | m = S n ->
143 | m * (1 + n) = m * m.
144 |
145 | Proof.
146 | (* Move n, m into context *)
147 | intros n m.
148 | (* Move hypothesis into context *)
149 | intros H.
150 | rewrite -> H.
151 | reflexivity.
152 | Qed.
153 |
154 | (*******************)
155 | (* andb_true_elim2 *)
156 | (*******************)
157 |
158 | Theorem andb_true_elim2 : forall b c : bool,
159 | andb b c = true -> c = true.
160 |
161 | Proof.
162 | intros b. destruct b.
163 | - destruct c.
164 | + simpl. reflexivity.
165 | + simpl. intros H. rewrite -> H. reflexivity.
166 | - destruct c.
167 | + simpl. reflexivity.
168 | + simpl. intros H. rewrite -> H. reflexivity.
169 | Qed.
170 |
171 | (* Alternative:
172 | Proof.
173 | intros [] [].
174 | - simpl. intros H. rewrite -> H. reflexivity.
175 | - reflexivity.
176 | - simpl. intros H. rewrite -> H. reflexivity.
177 | - reflexivity. Qed.*)
178 |
179 | (********************)
180 | (* zero_nbeq_plus_1 *)
181 | (********************)
182 |
183 | Theorem zero_nbeq_plus_1 : forall n : nat,
184 | be_nat 0 (n + 1) = false.
185 |
186 | Proof.
187 | intros [|n].
188 | - reflexivity.
189 | - simpl. reflexivity.
190 | Qed.
191 |
192 | (*********************)
193 | (* boolean_functions *)
194 | (*********************)
195 |
196 | Theorem identity_fn_applied_twice :
197 | forall (f : bool -> bool),
198 | (forall (x : bool), f x = x) ->
199 | forall (b : bool), f (f b) = b.
200 |
201 | Proof.
202 | intros f H.
203 | intros [].
204 | - rewrite -> H. rewrite -> H. reflexivity.
205 | - rewrite -> H. rewrite -> H. reflexivity.
206 | Qed.
207 |
208 | Theorem negation_fn_applied_twice :
209 | forall (f : bool -> bool),
210 | (forall (x : bool), f x = negb x) ->
211 | forall (b : bool), f (f b) = b.
212 |
213 | Proof.
214 | intros f H.
215 | intros [].
216 | - rewrite -> H. rewrite -> H. reflexivity.
217 | - rewrite -> H. rewrite -> H. reflexivity.
218 | Qed.
219 |
220 | (***************)
221 | (* andb_eq_orb *)
222 | (***************)
223 |
224 | Theorem andb_eq_orb :
225 | forall (b c : bool),
226 | (andb b c = orb b c) ->
227 | b = c.
228 |
229 | Proof.
230 | intros b c.
231 | destruct b.
232 | - simpl. intros H. rewrite -> H. reflexivity.
233 | - simpl. intros H. rewrite -> H. reflexivity.
234 | Qed.
235 |
236 | (**********)
237 | (* binary *)
238 | (**********)
--------------------------------------------------------------------------------
/sds011/sds011.c:
--------------------------------------------------------------------------------
1 | /*
2 | SDS011 dust sensor
3 |
4 | Compile with:
5 | -------------
6 | make
7 |
8 | References:
9 | -----------
10 | * https://web.archive.org/web/20160705112431/http://inovafitness.com/software/SDS011%20laser%20PM2.5%20sensor%20specification-V1.3.pdf
11 | * https://github.com/ryszard/sds011/blob/master/doc/Protocol_V1.3.docx
12 | * http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/
13 | * https://www.cmrr.umn.edu/~strupp/serial.html
14 | */
15 |
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | static const bool debug = false;
31 |
32 | /* size of data packet */
33 | #define MSG_SIZE 10
34 | /* message header */
35 | #define MSG_HDR 0xaa
36 | /* data command */
37 | #define MSG_DATA 0xc0
38 | /* message tail */
39 | #define MSG_TAIL 0xab
40 |
41 | /* offsets in data packets */
42 | enum {
43 | OFF_HDR = 0, /* message header */
44 | OFF_CMD, /* command */
45 | OFF_DATA1, /* PM 2.5 low byte */
46 | OFF_DATA2, /* PM 2.5 high byte */
47 | OFF_DATA3, /* PM 10 low byte */
48 | OFF_DATA4, /* PM 10 high byte */
49 | OFF_DATA5, /* ID byte 1 */
50 | OFF_DATA6, /* ID byte 2 */
51 | OFF_CHK, /* checksum = DATA1 + DATA2 + ... + DATA6 */
52 | OFF_TAIL /* message tail */
53 | };
54 |
55 | /* directory for log files */
56 | #define LOGDIR "/home/pi/sds011/logs"
57 |
58 | int main(int argc, char *argv[])
59 | {
60 | int fd, ret = EXIT_SUCCESS;
61 | struct termios opt;
62 |
63 | if (argc < 2) {
64 | fprintf(stderr, "Usage: %s /dev/ttyUSBx\n", argv[0]);
65 | ret = EXIT_FAILURE;
66 | goto error;
67 | }
68 |
69 | /* process isn't a controlling terminal, ignore DCD state */
70 | if ((fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY)) == -1) {
71 | perror("Error opening serial port");
72 | ret = EXIT_FAILURE;
73 | goto error;
74 | }
75 |
76 | /* we want read calls to block */
77 | if (fcntl(fd, F_SETFL, 0) == -1) {
78 | perror("fcntl");
79 | ret = EXIT_FAILURE;
80 | goto error;
81 | }
82 |
83 | /* get settings for serial port */
84 | if (tcgetattr(fd, &opt) == -1) {
85 | perror("tcgetattr");
86 | ret = EXIT_FAILURE;
87 | goto error;
88 | }
89 |
90 | /* 8 data bits */
91 | opt.c_cflag &= ~CSIZE;
92 | opt.c_cflag |= CS8;
93 | /* 1 stop bit */
94 | opt.c_cflag &= ~CSTOPB;
95 | /* enable receiver */
96 | opt.c_cflag |= CREAD;
97 | /* disable parity */
98 | opt.c_cflag &= ~PARENB;
99 | /* local line */
100 | opt.c_cflag |= CLOCAL;
101 | /* disable hardware control flow */
102 | #ifdef CNEW_RTSCTS
103 | opt.c_cflag &= ~CNEW_RTSCTS;
104 | #endif
105 |
106 | /* set baud rate to 9600 */
107 | if (cfsetispeed(&opt, B9600) == -1 || cfsetospeed(&opt, B9600) == -1) {
108 | perror("cfsetispeed/cfsetospeed");
109 | ret = EXIT_FAILURE;
110 | goto error;
111 | }
112 |
113 | /* raw input */
114 | opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
115 | /* no software flow control */
116 | opt.c_iflag &= ~(IXON | IXOFF | IXANY);
117 |
118 | /* raw output */
119 | opt.c_oflag &= ~OPOST;
120 |
121 | /* receive at least PACKET_SIZE bytes with read, no timer */
122 | opt.c_cc[VMIN] = MSG_SIZE;
123 | opt.c_cc[VTIME] = 0;
124 |
125 | /* apply settings to serial port and flush input/output buffers */
126 | if (tcsetattr(fd, TCSAFLUSH, &opt) == -1) {
127 | perror("tcsetattr");
128 | ret = EXIT_FAILURE;
129 | goto error;
130 | }
131 |
132 | uint8_t buf[MSG_SIZE];
133 | FILE *log = NULL;
134 |
135 | while (read(fd, buf, MSG_SIZE) > 0) {
136 | /* calculate checksum */
137 | uint8_t chksum = 0;
138 | for (int i = OFF_DATA1; i <= OFF_DATA6; ++i)
139 | chksum += buf[i];
140 | /* check if message is valid, otherwise discard it
141 | and flush input buffer */
142 | if (buf[OFF_HDR] == MSG_HDR && buf[OFF_CMD] == MSG_DATA &&
143 | buf[OFF_CHK] == chksum && buf[OFF_TAIL] == MSG_TAIL) {
144 | /* PM 2.5 (ug/m^3) */
145 | float pm25 = (buf[OFF_DATA2]<<8 | buf[OFF_DATA1])/10.f;
146 | /* PM 10 (ug/m^3) */
147 | float pm10 = (buf[OFF_DATA4]<<8 | buf[OFF_DATA3])/10.f;
148 | if (debug)
149 | printf("PM 2.5: %f, PM 10: %f\n", pm25, pm10);
150 |
151 | /* get time and date */
152 | time_t unix_time = time(NULL);
153 | struct tm *t = localtime(&unix_time);
154 | struct stat st;
155 | char logname[strlen(LOGDIR)+1+strlen("yyyy-mm-dd")+1];
156 |
157 | snprintf(logname, sizeof logname, "%s/%04d-%02d-%02d",
158 | LOGDIR,
159 | t->tm_year + 1900, t->tm_mon + 1, t->tm_mday);
160 |
161 | /* append to logfile if it already exists */
162 | if (log == NULL && stat(logname, &st) == 0)
163 | log = fopen(logname, "a");
164 | /* create new logfile at midnight */
165 | if (stat(logname, &st) == -1) {
166 | /* close old logfile */
167 | if (log)
168 | (void)fclose(log);
169 | if ((log = fopen(logname, "w")))
170 | fprintf(log, "# hh:mm:ss"
171 | "\tPM2.5 / ug/m^3"
172 | "\tPM10 / ug/m^3\n");
173 | }
174 |
175 | if (log)
176 | fprintf(log, "%02i:%02i:%02i\t%f\t%f\n",
177 | t->tm_hour, t->tm_min, t->tm_sec,
178 | pm25, pm10);
179 | } else {
180 | tcflush(fd, TCIFLUSH);
181 | if (debug) {
182 | /* PM 2.5 (ug/m^3) */
183 | float pm25 = (buf[OFF_DATA2]<<8 | buf[OFF_DATA1])/10.f;
184 | /* PM 10 (ug/m^3) */
185 | float pm10 = (buf[OFF_DATA4]<<8 | buf[OFF_DATA3])/10.f;
186 |
187 | printf("PM 2.5: %f, PM 10: %f\n", pm25, pm10);
188 | fprintf(stderr, "header : %s\n",
189 | buf[OFF_HDR]==MSG_HDR?"pass":"fail");
190 | fprintf(stderr, "cmd : %s\n",
191 | buf[OFF_CMD]==MSG_DATA?"pass":"fail");
192 | fprintf(stderr, "checksum: %s\n",
193 | buf[OFF_CHK]==chksum?"pass":"fail");
194 | if (buf[OFF_CHK] != chksum)
195 | fprintf(stderr, "checksum: 0x%02x, "
196 | "expected: 0x%02x\n",
197 | buf[OFF_CHK], chksum);
198 | fprintf(stderr, "tail : %s\n",
199 | buf[OFF_TAIL]==MSG_TAIL?"pass":"fail");
200 | }
201 | }
202 | }
203 |
204 | error:
205 | return ret;
206 | }
207 |
--------------------------------------------------------------------------------
/nbody/nbody/kernel.cu:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 |
4 | /* check for CUDA error */
5 | #define CHECK_ERROR check_cuda_error(__LINE__-1, __FILE__)
6 |
7 | /* #bodies */
8 | static int N;
9 |
10 | /* #threads/block (leapfrog) */
11 | static int TPB = 128;
12 |
13 | /* #tiles (acceleration kernel) */
14 | static int P;
15 |
16 | /* #timesteps */
17 | static int TIMESTEPS = 1000;
18 | /* softening factor (square), G, \Delta t */
19 | static const float EPS = 0.1f, G = 2.f, DELTA_T = 0.01f;
20 |
21 | /* acceleration */
22 | __device__ float4 *a;
23 | /* x,y,z: position; w: mass */
24 | static float4 *r_host;
25 | __device__ float4 *r;
26 | /* velocity */
27 | static float4 *v_host;
28 | __device__ float4 *v;
29 |
30 | /* random number in [0,1] */
31 | static inline float rnd()
32 | {
33 | return (float)rand() / RAND_MAX;
34 | }
35 |
36 | /* check for CUDA error */
37 | static void check_cuda_error(const int line, const char *file)
38 | {
39 | cudaError_t e;
40 |
41 | e = cudaGetLastError();
42 | if (e != cudaSuccess) {
43 | printf("CUDA error: %s, line %i, file '%s'\n",
44 | cudaGetErrorString(e), line, file);
45 | exit(1);
46 | }
47 | }
48 |
49 | /* leap frog integration kernel (1 particle/thread) */
50 | __global__ void leap_frog_1p_2(float4 *a, float4 *v, float4 *r, float delta_t)
51 | {
52 | int i = threadIdx.x + __mul24(blockIdx.x, blockDim.x);
53 | float3 v_tmp;
54 |
55 | v_tmp.x = v[i].x;
56 | v_tmp.y = v[i].y;
57 | v_tmp.z = v[i].z;
58 |
59 | v_tmp.x += a[i].x * delta_t;
60 | v_tmp.y += a[i].y * delta_t;
61 | v_tmp.z += a[i].z * delta_t;
62 |
63 | r[i].x += v_tmp.x * delta_t;
64 | r[i].y += v_tmp.y * delta_t;
65 | r[i].z += v_tmp.z * delta_t;
66 |
67 | v[i] = make_float4(v_tmp.x, v_tmp.y, v_tmp.z, 0.f);
68 | }
69 |
70 | /* body-body interaction, returns a_i */
71 | __device__ float3 interaction(float3 ri, float4 rj, float eps)
72 | {
73 | float3 rij, ai;
74 | float dst_sqr, cube, inv_sqrt;
75 |
76 | /* distance vector */
77 | rij.x = rj.x - ri.x;
78 | rij.y = rj.y - ri.y;
79 | rij.z = rj.z - ri.z;
80 |
81 | /* compute acceleration */
82 | dst_sqr = rij.x*rij.x + rij.y*rij.y + rij.z*rij.z + eps;
83 | cube = dst_sqr * dst_sqr * dst_sqr;
84 | inv_sqrt = rsqrtf(cube) * rj.w;
85 |
86 | /* acceleration a_i */
87 | ai.x = rij.x * inv_sqrt;
88 | ai.y = rij.y * inv_sqrt;
89 | ai.z = rij.z * inv_sqrt;
90 |
91 | return ai;
92 | }
93 |
94 | /* calculate accelerations */
95 | __global__ void acc(float4 *r, float4 *a, float eps, float g)
96 | {
97 | /* dynamically allocated shared memory */
98 | extern __shared__ float4 shared[];
99 | /* acceleration a_i */
100 | float3 ai = make_float3(0.f, 0.f, 0.f), tmp;
101 | /* position particle i */
102 | float3 ri;
103 | /* particle i */
104 | int i = threadIdx.x + __mul24(blockIdx.x, blockDim.x);
105 | int k, l;
106 |
107 | /* get position of particle i */
108 | ri.x = r[i].x;
109 | ri.y = r[i].y;
110 | ri.z = r[i].z;
111 |
112 | /* loop over tiles */
113 | for (k = 0; k < gridDim.x; ++k) {
114 | /* load position and mass into shared memory */
115 | shared[threadIdx.x] = r[__mul24(k, blockDim.x) + threadIdx.x];
116 | __syncthreads();
117 |
118 | /* loop over particles in a tile */
119 | #pragma unroll 32
120 | for (l = 0; l < blockDim.x; ++l) {
121 | tmp = interaction(ri, shared[l], eps);
122 | ai.x += tmp.x;
123 | ai.y += tmp.y;
124 | ai.z += tmp.z;
125 | }
126 |
127 | /* wait for other threads to finish calculation */
128 | __syncthreads();
129 | }
130 |
131 | /* save acceleration a_i in global memory */
132 | a[i] = make_float4(ai.x*g, ai.y*g, ai.z*g, 0.f);
133 | }
134 |
135 | void init();
136 |
137 | int main(int argc, char *argv[])
138 | {
139 | cudaEvent_t start, stop;
140 | float time;
141 | int i, timestep;
142 |
143 | if (argc < 2) {
144 | printf("usage: nbody -N#bodies [-T#threads/block] [-S#timesteps] -P#tiles\n");
145 | exit(1);
146 | }
147 |
148 | /* get command line parameters */
149 | for (i = 1; i < argc; ++i) {
150 | if (argv[i][0] == '-') {
151 | switch (argv[i][1]) {
152 | case 'N':
153 | N = atoi(argv[i]+2);
154 | break;
155 | case 'T':
156 | TPB = atoi(argv[i]+2);
157 | break;
158 | case 'S':
159 | TIMESTEPS = atoi(argv[i]+2);
160 | break;
161 | case 'P':
162 | P = atoi(argv[i]+2);
163 | break;
164 | default:
165 | break;
166 | }
167 | }
168 | }
169 |
170 | /*printf("N: %i, TPB: %i, TIMESTEPS: %i, P: %i\n", N, TPB, TIMESTEPS, P);*/
171 |
172 | if (N % TPB) {
173 | printf("#bodies must be a multiple of #threads/block!\n");
174 | exit(1);
175 | }
176 |
177 | if (N % P) {
178 | printf("#bodies must be a multiple of #p!\n");
179 | exit(1);
180 | }
181 |
182 | /* alloc host memory */
183 | r_host = (float4 *)malloc(N*sizeof(float4));
184 | v_host = (float4 *)malloc(N*sizeof(float4));
185 | /* alloc device memory */
186 | cudaMalloc((void **)&a, N*sizeof(float4));
187 | cudaMalloc((void **)&r, N*sizeof(float4));
188 | cudaMalloc((void **)&v, N*sizeof(float4));
189 | CHECK_ERROR;
190 |
191 | /* generate initial configuration */
192 | srand(1);
193 | init();
194 |
195 | /* copy config to device memory */
196 | cudaMemcpy(r, r_host, N*sizeof(float4), cudaMemcpyHostToDevice);
197 | cudaMemcpy(v, v_host, N*sizeof(float4), cudaMemcpyHostToDevice);
198 | CHECK_ERROR;
199 |
200 | /* start counter */
201 | cudaEventCreate(&start);
202 | cudaEventCreate(&stop);
203 | cudaEventRecord(start, 0);
204 |
205 | /* integration steps */
206 | for (timestep = 0; timestep < TIMESTEPS; ++timestep) {
207 | /* update accelerations */
208 | acc<<>>(r, a, EPS, G);
209 |
210 | /* leap frog */
211 | leap_frog_1p_2<<>>(a, v, r, DELTA_T);
212 | /*cudaMemcpy(r_host, r, N * sizeof(float3), cudaMemcpyDeviceToHost);
213 | printf("#1: x: %f, y: %f, z: %f\n", r_host[0].x, r_host[0].y, r_host[0].z);
214 | printf("#2: x: %f, y: %f, z: %f\n", r_host[1].x, r_host[1].y, r_host[1].z);*/
215 | }
216 |
217 | /* stop counter */
218 | cudaEventRecord(stop, 0);
219 | cudaEventSynchronize(stop);
220 | /* unit: milliseconds */
221 | cudaEventElapsedTime(&time, start, stop);
222 | CHECK_ERROR;
223 | /*printf("elapsed time: %f\n", time);
224 | printf("#interactions/s: %f\n", ((float)TIMESTEPS*N*N) / time * 1000);*/
225 | printf("%f\n", ((float)TIMESTEPS*N*N) / time * 1000);
226 |
227 | /* free host memory */
228 | free(r_host);
229 | free(v_host);
230 | /* free device memory */
231 | cudaFree(a);
232 | cudaFree(r);
233 | cudaFree(v);
234 | CHECK_ERROR;
235 |
236 | return 0;
237 | }
238 |
239 | /* generate initial configuration */
240 | void init()
241 | {
242 | int i;
243 |
244 | for (i = 0; i < N; ++i) {
245 | /* mass */
246 | r_host[i].w = rnd()>0.5 ? 1.f : 10.f;
247 |
248 | /* velocity */
249 | v_host[i].x = 3.f;
250 | v_host[i].y = rnd() * 10.f;
251 | v_host[i].z = -5.f;
252 |
253 | /* position */
254 | r_host[i].x = rnd() * 50.f;
255 | r_host[i].y = rnd() * 50.f;
256 | r_host[i].z = rnd() * 50.f;
257 | }
258 | }
259 |
--------------------------------------------------------------------------------
| | |