PWMOut.cpp 54.6 KB
Newer Older
1
2
/****************************************************************************
 *
Lorenz Meier's avatar
Lorenz Meier committed
3
 *   Copyright (c) 2012-2021 PX4 Development Team. All rights reserved.
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

34
#include "PWMOut.hpp"
David Sidrane's avatar
David Sidrane committed
35

Daniel Agar's avatar
Daniel Agar committed
36
37
38
pthread_mutex_t pwm_out_module_mutex = PTHREAD_MUTEX_INITIALIZER;
static px4::atomic<PWMOut *> _objects[PWM_OUT_MAX_INSTANCES] {};

39
40
41
42
43
44
45
46
47
48
static bool is_running()
{
	for (auto &obj : _objects) {
		if (obj.load() != nullptr) {
			return true;
		}
	}

	return false;
}
Daniel Agar's avatar
Daniel Agar committed
49
50
51
52
53
54

PWMOut::PWMOut(int instance, uint8_t output_base) :
	CDev((instance == 0) ? PX4FMU_DEVICE_PATH : PX4FMU_DEVICE_PATH"1"),
	OutputModuleInterface((instance == 0) ? MODULE_NAME"0" : MODULE_NAME"1", px4::wq_configurations::hp_default),
	_instance(instance),
	_output_base(output_base),
55
56
	_cycle_perf(perf_alloc(PC_ELAPSED, MODULE_NAME": cycle")),
	_interval_perf(perf_alloc(PC_INTERVAL, MODULE_NAME": interval"))
57
{
58
59
	_mixing_output.setAllMinValues(PWM_DEFAULT_MIN);
	_mixing_output.setAllMaxValues(PWM_DEFAULT_MAX);
60
61
}

62
PWMOut::~PWMOut()
63
{
Beat Küng's avatar
Beat Küng committed
64
	/* make sure servos are off */
Daniel Agar's avatar
Daniel Agar committed
65
	up_pwm_servo_deinit(); // TODO: review for multi
Beat Küng's avatar
Beat Küng committed
66

67
	/* clean up the alternate device node */
68
	unregister_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH, _class_instance);
69

70
	perf_free(_cycle_perf);
71
	perf_free(_interval_perf);
72
73
}

74
int PWMOut::init()
75
76
{
	/* do regular cdev init */
77
	int ret = CDev::init();
px4dev's avatar
px4dev committed
78

Lorenz Meier's avatar
Lorenz Meier committed
79
	if (ret != OK) {
80
		return ret;
Lorenz Meier's avatar
Lorenz Meier committed
81
	}
82

Lorenz Meier's avatar
Lorenz Meier committed
83
84
85
86
87
88
89
90
	// XXX best would be to register / de-register the device depending on modes

	/* try to claim the generic PWM output device node as well - it's OK if we fail at this */
	_class_instance = register_class_devname(PWM_OUTPUT_BASE_DEVICE_PATH);

	if (_class_instance == CLASS_DEVICE_PRIMARY) {
		/* lets not be too verbose */
	} else if (_class_instance < 0) {
David Sidrane's avatar
David Sidrane committed
91
		PX4_ERR("FAILED registering class device");
92
93
	}

94
95
	_mixing_output.setDriverInstance(_class_instance);

Beat Küng's avatar
Beat Küng committed
96
97
98
99
100
101
	/* force a reset of the update rate */
	_current_update_rate = 0;

	// Getting initial parameter values
	update_params();

102
103
	ScheduleNow();

Beat Küng's avatar
Beat Küng committed
104
	return 0;
Mark Whitehorn's avatar
Mark Whitehorn committed
105
106
}

107
int PWMOut::set_mode(Mode mode)
108
{
109
110
	unsigned old_mask = _pwm_mask;

111
	/*
112
113
114
115
116
117
118
	 * Configure for PWM output.
	 *
	 * Note that regardless of the configured mode, the task is always
	 * listening and mixing; the mode just selects which of the channels
	 * are presented on the output pins.
	 */
	switch (mode) {
Julian Oes's avatar
Julian Oes committed
119
120
121
122
123
	case MODE_1PWM:
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
124
		_pwm_mask = 0b0000'0000'0000'0001 << _output_base;
Julian Oes's avatar
Julian Oes committed
125
		_pwm_initialized = false;
126
		_num_outputs = 1;
Daniel Agar's avatar
Daniel Agar committed
127
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
128
		update_params();
Julian Oes's avatar
Julian Oes committed
129
130
		break;

131
132
#if defined(BOARD_HAS_CAPTURE)

David Sidrane's avatar
David Sidrane committed
133
134
135
	case MODE_2PWM2CAP:	// v1 multi-port with flow control lines as PWM
		up_input_capture_set(2, Rising, 0, NULL, NULL);
		up_input_capture_set(3, Rising, 0, NULL, NULL);
136
		PX4_DEBUG("MODE_2PWM2CAP");
137
#endif
David Sidrane's avatar
David Sidrane committed
138

139
140
	/* FALLTHROUGH */

141
	case MODE_2PWM:	// v1 multi-port with flow control lines as PWM
142
		PX4_DEBUG("MODE_2PWM");
143

144
145
146
147
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
148
		_pwm_mask = 0b0000'0000'0000'0011 << _output_base;
149
		_pwm_initialized = false;
150
		_num_outputs = 2;
Daniel Agar's avatar
Daniel Agar committed
151
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
152
		update_params();
153
154
155

		break;

156
157
#if defined(BOARD_HAS_CAPTURE)

David Sidrane's avatar
David Sidrane committed
158
	case MODE_3PWM1CAP:	// v1 multi-port with flow control lines as PWM
159
		PX4_DEBUG("MODE_3PWM1CAP");
David Sidrane's avatar
David Sidrane committed
160
		up_input_capture_set(3, Rising, 0, NULL, NULL);
161
#endif
David Sidrane's avatar
David Sidrane committed
162

163
164
	/* FALLTHROUGH */

David Sidrane's avatar
David Sidrane committed
165
	case MODE_3PWM:	// v1 multi-port with flow control lines as PWM
166
		PX4_DEBUG("MODE_3PWM");
David Sidrane's avatar
David Sidrane committed
167
168
169
170
171

		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
172
		_pwm_mask = 0b0000'0000'0000'0111 << _output_base;
173
		_pwm_initialized = false;
174
		_num_outputs = 3;
Daniel Agar's avatar
Daniel Agar committed
175
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
176
		update_params();
177

David Sidrane's avatar
David Sidrane committed
178
179
		break;

180
181
182
183
184
185
186
187
188
#if defined(BOARD_HAS_CAPTURE)

	case MODE_4PWM1CAP:
		PX4_DEBUG("MODE_4PWM1CAP");
		up_input_capture_set(4, Rising, 0, NULL, NULL);
#endif

	/* FALLTHROUGH */

Lorenz Meier's avatar
Lorenz Meier committed
189
	case MODE_4PWM: // v1 or v2 multi-port as 4 PWM outs
190
		PX4_DEBUG("MODE_4PWM");
191

192
193
194
195
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
196
		_pwm_mask = 0b0000'0000'0000'1111 << _output_base;
197
		_pwm_initialized = false;
198
		_num_outputs = 4;
Daniel Agar's avatar
Daniel Agar committed
199
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
200
		update_params();
201
202
203

		break;

DanielePettenuzzo's avatar
DanielePettenuzzo committed
204
205
206
207
208
209
210
211
212
213
#if defined(BOARD_HAS_CAPTURE)

	case MODE_4PWM2CAP:
		PX4_DEBUG("MODE_4PWM2CAP");
		up_input_capture_set(5, Rising, 0, NULL, NULL);

		/* default output rates */
		_pwm_default_rate = 400;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
214
		_pwm_mask = 0b0000'0000'0000'1111 << _output_base;
DanielePettenuzzo's avatar
DanielePettenuzzo committed
215
216
		_pwm_initialized = false;
		_num_outputs = 4;
Daniel Agar's avatar
Daniel Agar committed
217
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
218
		update_params();
DanielePettenuzzo's avatar
DanielePettenuzzo committed
219
220
221
222

		break;
#endif

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#if defined(BOARD_HAS_CAPTURE)

	case MODE_5PWM1CAP:
		PX4_DEBUG("MODE_5PWM1CAP");
		up_input_capture_set(5, Rising, 0, NULL, NULL);
#endif

	/* FALLTHROUGH */

	case MODE_5PWM: // v1 or v2 multi-port as 5 PWM outs
		PX4_DEBUG("MODE_5PWM");

		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
239
		_pwm_mask = 0b0000'0000'0001'1111 << _output_base;
240
		_pwm_initialized = false;
241
		_num_outputs = 5;
Daniel Agar's avatar
Daniel Agar committed
242
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
243
		update_params();
244
245
246

		break;

247
248
249
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 6

	case MODE_6PWM:
250
		PX4_DEBUG("MODE_6PWM");
251

252
253
254
255
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
256
		_pwm_mask = 0b0000'0000'0011'1111 << _output_base;
257
		_pwm_initialized = false;
258
		_num_outputs = 6;
Daniel Agar's avatar
Daniel Agar committed
259
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
260
		update_params();
261

262
		break;
263
#endif
px4dev's avatar
px4dev committed
264

265
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 8
Lorenz Meier's avatar
Lorenz Meier committed
266

Daniel Agar's avatar
Daniel Agar committed
267
	case MODE_8PWM:
268
		PX4_DEBUG("MODE_8PWM");
Ash Charles's avatar
Ash Charles committed
269
270
271
272
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
273
		_pwm_mask = 0b0000'0000'1111'1111 << _output_base;
274
		_pwm_initialized = false;
275
		_num_outputs = 8;
Daniel Agar's avatar
Daniel Agar committed
276
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
277
		update_params();
278

Ash Charles's avatar
Ash Charles committed
279
280
281
		break;
#endif

Daniel Agar's avatar
Daniel Agar committed
282
283
284
285
286
287
288
289
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 12

	case MODE_12PWM:
		PX4_DEBUG("MODE_12PWM");
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
290
		_pwm_mask = 0b0000'1111'1111'1111 << _output_base;
Daniel Agar's avatar
Daniel Agar committed
291
292
		_pwm_initialized = false;
		_num_outputs = 12;
Daniel Agar's avatar
Daniel Agar committed
293
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
294
295
296
297
298
		update_params();

		break;
#endif

299
300
301
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 14

	case MODE_14PWM:
302
		PX4_DEBUG("MODE_14PWM");
303
304
305
306
		/* default output rates */
		_pwm_default_rate = 50;
		_pwm_alt_rate = 50;
		_pwm_alt_rate_channels = 0;
Daniel Agar's avatar
Daniel Agar committed
307
		_pwm_mask = 0b0011'1111'1111'1111 << _output_base;
308
309
		_pwm_initialized = false;
		_num_outputs = 14;
Daniel Agar's avatar
Daniel Agar committed
310
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
311
		update_params();
312
313
314
315

		break;
#endif

316
	case MODE_NONE:
317
		PX4_DEBUG("MODE_NONE");
318
319
320
321

		_pwm_default_rate = 10;	/* artificially reduced output rate */
		_pwm_alt_rate = 10;
		_pwm_alt_rate_channels = 0;
322
323
		_pwm_mask = 0x0;
		_pwm_initialized = false;
324
		_num_outputs = 0;
Daniel Agar's avatar
Daniel Agar committed
325
		_mixing_output.setMaxNumOutputs(_num_outputs);
Daniel Agar's avatar
Daniel Agar committed
326
		update_params();
327

328
329
		if (old_mask != _pwm_mask) {
			/* disable servo outputs - no need to set rates */
Daniel Agar's avatar
Daniel Agar committed
330
			up_pwm_servo_deinit(); // TODO: review for multi
331
		}
332

333
		break;
334
335
336

	default:
		return -EINVAL;
337
	}
338

339
340
341
342
	_mode = mode;
	return OK;
}

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/* When set_pwm_rate is called from either of the 2 IOCTLs:
 *
 * PWM_SERVO_SET_UPDATE_RATE        - Sets the "alternate" channel's rate to the callers's rate specified
 *                                    and the non "alternate" channels to the _pwm_default_rate.
 *
 *                                    rate_map     = _pwm_alt_rate_channels
 *                                    default_rate = _pwm_default_rate
 *                                    alt_rate     = arg of IOCTL (see rates)
 *
 * PWM_SERVO_SET_SELECT_UPDATE_RATE - The caller's specified rate map selects the "alternate" channels
 *                                    to be set to the alt rate. (_pwm_alt_rate)
 *                                    All other channels are set to the default rate. (_pwm_default_rate)
 *
 *                                    rate_map     = arg of IOCTL
 *                                    default_rate = _pwm_default_rate
 *                                    alt_rate     = _pwm_alt_rate

 *  rate_map                        - A mask of 1's for the channels to be set to the
 *                                    alternate rate.
 *                                    N.B. All channels is a given group must be set
 *                                    to the same rate/mode. (default or alt)
 * rates:
 *   alt_rate, default_rate           For PWM is 25 or 400Hz
 *                                    For Oneshot there is no rate, 0 is therefore used
 *                                    to  select Oneshot mode
368
 */
369
int PWMOut::set_pwm_rate(uint32_t rate_map, unsigned default_rate, unsigned alt_rate)
370
{
Daniel Agar's avatar
Daniel Agar committed
371
	PX4_DEBUG("pwm_out%u set_pwm_rate %x %u %u", _instance, rate_map, default_rate, alt_rate);
372

373
	for (unsigned pass = 0; pass < 2; pass++) {
374

375
		/* We should note that group is iterated over from 0 to FMU_MAX_ACTUATORS.
376
377
378
379
380
381
382
383
384
385
386
387
388
		 * This allows for the ideal worlds situation: 1 channel per group
		 * configuration.
		 *
		 * This is typically not what HW supports. A group represents a timer
		 * and channels belongs to a timer.
		 * Therefore all channels in a group are dependent on the timer's
		 * common settings and can not be independent in terms of count frequency
		 * (granularity of pulse width) and rate (period of repetition).
		 *
		 * To say it another way, all channels in a group moust have the same
		 * rate and mode. (See rates above.)
		 */

389
		for (unsigned group = 0; group < FMU_MAX_ACTUATORS; group++) {
390
391
392

			// get the channel mask for this rate group
			uint32_t mask = up_pwm_servo_get_rate_group(group);
393

Lorenz Meier's avatar
Lorenz Meier committed
394
			if (mask == 0) {
395
				continue;
Lorenz Meier's avatar
Lorenz Meier committed
396
			}
397
398
399
400
401
402
403

			// all channels in the group must be either default or alt-rate
			uint32_t alt = rate_map & mask;

			if (pass == 0) {
				// preflight
				if ((alt != 0) && (alt != mask)) {
404
					PX4_WARN("rate group %u mask %x bad overlap %x", group, mask, alt);
405
406
407
					// not a legal map, bail
					return -EINVAL;
				}
408

409
410
411
			} else {
				// set it - errors here are unexpected
				if (alt != 0) {
412
413
					if (up_pwm_servo_set_rate_group_update(group, alt_rate) != OK) {
						PX4_WARN("rate group set alt failed");
414
						return -EINVAL;
415
					}
416

417
				} else {
418
419
					if (up_pwm_servo_set_rate_group_update(group, default_rate) != OK) {
						PX4_WARN("rate group set default failed");
420
						return -EINVAL;
421
					}
422
423
424
425
				}
			}
		}
	}
426

427
428
429
	_pwm_alt_rate_channels = rate_map;
	_pwm_default_rate = default_rate;
	_pwm_alt_rate = alt_rate;
430

431
432
433
434
435
436
437
438
439
440
441
442
443
	// minimum rate for backup schedule
	unsigned backup_schedule_rate_hz = math::min(_pwm_default_rate, _pwm_alt_rate);

	if (backup_schedule_rate_hz == 0) {
		// OneShot rate is 0
		backup_schedule_rate_hz = 50;
	}

	// constrain reasonably (1 to 50 Hz)
	backup_schedule_rate_hz = math::constrain(backup_schedule_rate_hz, 1u, 50u);

	_backup_schedule_interval_us = roundf(1e6f / backup_schedule_rate_hz);

444
445
	_current_update_rate = 0; // force update

446
447
	return OK;
}
448

449
450
451
452
453
int PWMOut::set_i2c_bus_clock(unsigned bus, unsigned clock_hz)
{
	return device::I2C::set_bus_clock(bus, clock_hz);
}

454
void PWMOut::update_current_rate()
455
{
456
457
458
459
460
461
462
463
464
465
466
	/*
	* Adjust actuator topic update rate to keep up with
	* the highest servo update rate configured.
	*
	* We always mix at max rate; some channels may update slower.
	*/
	int max_rate = (_pwm_default_rate > _pwm_alt_rate) ? _pwm_default_rate : _pwm_alt_rate;

	// oneshot
	if ((_pwm_default_rate == 0) || (_pwm_alt_rate == 0)) {
		max_rate = 2000;
467
468
469
470
471

	} else {
		// run up to twice PWM rate to reduce end-to-end latency
		//  actual pulse width only updated for next period regardless of output module
		max_rate *= 2;
472
473
474
475
476
	}

	// max interval 0.5 - 100 ms (10 - 2000Hz)
	const int update_interval_in_us = math::constrain(1000000 / max_rate, 500, 100000);

477
478
479
	if (_current_update_rate != max_rate) {
		PX4_INFO("instance: %d, max rate: %d, default: %d, alt: %d", _instance, max_rate, _pwm_default_rate, _pwm_alt_rate);
	}
Daniel Agar's avatar
Daniel Agar committed
480

481
482
	_current_update_rate = max_rate;
	_mixing_output.setMaxTopicUpdateRate(update_interval_in_us);
483
484
}

485
int PWMOut::task_spawn(int argc, char *argv[])
486
{
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
	for (unsigned instance = 0; instance < (sizeof(_objects) / sizeof(_objects[0])); instance++) {

		if (instance < PWM_OUT_MAX_INSTANCES) {
			uint8_t base = instance * 8;  // TODO: configurable
			PWMOut *dev = new PWMOut(instance, base);

			if (dev) {
				_objects[instance].store(dev);

				if (dev->init() != PX4_OK) {
					PX4_ERR("%d - init failed", instance);
					delete dev;
					_objects[instance].store(nullptr);
					return PX4_ERROR;
				}

			} else {
				PX4_ERR("alloc failed");
Daniel Agar's avatar
Daniel Agar committed
505
			}
506

Daniel Agar's avatar
Daniel Agar committed
507
		} else {
508
509
510
511
			// This hardware platform does not support
			// this many devices, set the storage to
			// a sane default
			_objects[instance].store(nullptr);
512
		}
513
514
	}

Daniel Agar's avatar
Daniel Agar committed
515
	return PX4_OK;
516
517
}

518
519
void PWMOut::capture_trampoline(void *context, uint32_t chan_index,
				hrt_abstime edge_time, uint32_t edge_state, uint32_t overflow)
David Sidrane's avatar
David Sidrane committed
520
{
521
	PWMOut *dev = static_cast<PWMOut *>(context);
David Sidrane's avatar
David Sidrane committed
522
523
524
	dev->capture_callback(chan_index, edge_time, edge_state, overflow);
}

525
526
void PWMOut::capture_callback(uint32_t chan_index,
			      hrt_abstime edge_time, uint32_t edge_state, uint32_t overflow)
David Sidrane's avatar
David Sidrane committed
527
{
528
	fprintf(stdout, "FMU: Capture chan:%d time:%lld state:%d overflow:%d\n", chan_index, edge_time, edge_state, overflow);
David Sidrane's avatar
David Sidrane committed
529
}
530

531
void PWMOut::update_pwm_out_state(bool on)
532
533
{
	if (on && !_pwm_initialized && _pwm_mask != 0) {
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566

		// Collect all PWM masks from all instances
		uint32_t pwm_mask_new = 0;
		// Collect the PWM alt rate channels across all instances
		uint32_t pwm_alt_rate_channels_new = 0;

		// Collect the minimum default rate
		unsigned default_rate_min = 0;
		// Collect the maximum alternative rate (400 Hz or DSHOT outputs)
		unsigned alt_rate_max = 0;

		for (int i = 0; i < PWM_OUT_MAX_INSTANCES; i++) {
			if (_objects[i].load()) {
				pwm_mask_new |= _objects[i].load()->get_pwm_mask();
				pwm_alt_rate_channels_new |= _objects[i].load()->get_alt_rate_channels();

				if (_objects[i].load()->get_alt_rate() > alt_rate_max) {
					alt_rate_max = _objects[i].load()->get_alt_rate();
				}

				if (_objects[i].load()->get_default_rate() < default_rate_min) {
					default_rate_min = _objects[i].load()->get_default_rate();
				}
			}
		}

		// Initialize the PWM output state for all instances
		// this is re-done once per instance, but harmless
		up_pwm_servo_init(pwm_mask_new);

		// Set rate is not affecting non-masked channels, so can be called
		// individually
		set_pwm_rate(pwm_alt_rate_channels_new, default_rate_min, alt_rate_max);
567
568
569
		_pwm_initialized = true;
	}

570
	up_pwm_servo_arm(on);
571
572
}

573
bool PWMOut::updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS],
574
575
576
			   unsigned num_outputs, unsigned num_control_groups_updated)
{
	if (_test_mode) {
577
		return false;
578
579
580
581
	}

	/* output to the servos */
	if (_pwm_initialized) {
582
		for (size_t i = 0; i < math::min(_num_outputs, num_outputs); i++) {
Daniel Agar's avatar
Daniel Agar committed
583
			up_pwm_servo_set(_output_base + i, outputs[i]);
584
585
586
587
588
589
590
		}
	}

	/* Trigger all timer's channels in Oneshot mode to fire
	 * the oneshots with updated values.
	 */
	if (num_control_groups_updated > 0) {
Daniel Agar's avatar
Daniel Agar committed
591
		up_pwm_update(); // TODO: review for multi
592
	}
593
594

	return true;
595
596
}

597
void PWMOut::Run()
598
{
599
600
	if (should_exit()) {
		ScheduleClear();
601
		_mixing_output.unregister();
602

Daniel Agar's avatar
Daniel Agar committed
603
		//exit_and_cleanup();
604
605
606
		return;
	}

607
	perf_begin(_cycle_perf);
608
	perf_count(_interval_perf);
609

610
611
612
	// push backup schedule
	ScheduleDelayed(_backup_schedule_interval_us);

613
	if (_new_mode_request.load() != MODE_NO_REQUEST) {
614
		set_mode(_new_mode_request.load());
615
		_new_mode_request.store(MODE_NO_REQUEST);
616
617
	}

618
	_mixing_output.update();
Lorenz Meier's avatar
Lorenz Meier committed
619

620
	/* update PWM status if armed or if disarmed PWM values are set */
621
	bool pwm_on = _mixing_output.armed().armed || (_num_disarmed_set > 0) || _mixing_output.armed().in_esc_calibration_mode;
622

623
624
625
626
	if (_pwm_on != pwm_on) {
		_pwm_on = pwm_on;
		update_pwm_out_state(pwm_on);
	}
Beat Küng's avatar
Beat Küng committed
627

628
629
630
631
632
633
634
	// check for parameter updates
	if (_parameter_update_sub.updated()) {
		// clear update
		parameter_update_s pupdate;
		_parameter_update_sub.copy(&pupdate);

		// update parameters from storage
635
636
		update_params();
	}
637

638
639
	if (_current_update_rate == 0) {
		update_current_rate();
640
	}
641

642
	// check at end of cycle (updateSubscriptions() can potentially change to a different WorkQueue thread)
643
	_mixing_output.updateSubscriptions(true, true);
644

645
	perf_end(_cycle_perf);
646
647
}

648
void PWMOut::update_params()
649
{
650
	updateParams();
Daniel Agar's avatar
Daniel Agar committed
651
652
653
654
655
656
657
658
659
660
661

	int32_t pwm_min_default = PWM_DEFAULT_MIN;
	int32_t pwm_max_default = PWM_DEFAULT_MAX;
	int32_t pwm_disarmed_default = 0;
	int32_t pwm_rate_default = 50;

	const char *prefix;

	if (_class_instance == CLASS_DEVICE_PRIMARY) {
		prefix = "PWM_MAIN";

662
663
664
665
		param_get(param_find("PWM_MAIN_MIN"), &pwm_min_default);
		param_get(param_find("PWM_MAIN_MAX"), &pwm_max_default);
		param_get(param_find("PWM_MAIN_DISARM"), &pwm_disarmed_default);
		param_get(param_find("PWM_MAIN_RATE"), &pwm_rate_default);
Daniel Agar's avatar
Daniel Agar committed
666
667
668
669
670
671

	} else if (_class_instance == CLASS_DEVICE_SECONDARY) {
		prefix = "PWM_AUX";

		param_get(param_find("PWM_AUX_MIN"), &pwm_min_default);
		param_get(param_find("PWM_AUX_MAX"), &pwm_max_default);
672
		param_get(param_find("PWM_AUX_DISARM"), &pwm_disarmed_default);
Daniel Agar's avatar
Daniel Agar committed
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
		param_get(param_find("PWM_AUX_RATE"), &pwm_rate_default);

	} else if (_class_instance == CLASS_DEVICE_TERTIARY) {
		prefix = "PWM_EXTRA";

		param_get(param_find("PWM_EXTRA_MIN"), &pwm_min_default);
		param_get(param_find("PWM_EXTRA_MAX"), &pwm_max_default);
		param_get(param_find("PWM_EXTRA_DISARM"), &pwm_disarmed_default);
		param_get(param_find("PWM_EXTRA_RATE"), &pwm_rate_default);

	} else {
		PX4_ERR("invalid class instance %d", _class_instance);
		return;
	}

	// update the counter
	// this is needed to decide if disarmed PWM output should be turned on or not
	int num_disarmed_set = 0;

	char str[17];

	for (unsigned i = 0; i < _num_outputs; i++) {
		// PWM_MAIN_MINx
		{
			sprintf(str, "%s_MIN%u", prefix, i + 1);
			int32_t pwm_min = -1;

			if (param_get(param_find(str), &pwm_min) == PX4_OK) {
				if (pwm_min >= 0) {
					_mixing_output.minValue(i) = math::constrain(pwm_min, PWM_LOWEST_MIN, PWM_HIGHEST_MIN);

					if (pwm_min != _mixing_output.minValue(i)) {
						int32_t pwm_min_new = _mixing_output.minValue(i);
						param_set(param_find(str), &pwm_min_new);
					}

				} else {
					_mixing_output.minValue(i) = pwm_min_default;
				}
			}
		}

		// PWM_MAIN_MAXx
		{
			sprintf(str, "%s_MAX%u", prefix, i + 1);
			int32_t pwm_max = -1;

			if (param_get(param_find(str), &pwm_max) == PX4_OK) {
				if (pwm_max >= 0) {
					_mixing_output.maxValue(i) = math::constrain(pwm_max, PWM_LOWEST_MAX, PWM_HIGHEST_MAX);

					if (pwm_max != _mixing_output.maxValue(i)) {
						int32_t pwm_max_new = _mixing_output.maxValue(i);
						param_set(param_find(str), &pwm_max_new);
					}

				} else {
					_mixing_output.maxValue(i) = pwm_max_default;
				}
			}
		}

		// PWM_MAIN_FAILx
		{
			sprintf(str, "%s_FAIL%u", prefix, i + 1);
			int32_t pwm_failsafe = -1;

			if (param_get(param_find(str), &pwm_failsafe) == PX4_OK) {
				if (pwm_failsafe >= 0) {
					_mixing_output.failsafeValue(i) = math::constrain(pwm_failsafe, 0, PWM_HIGHEST_MAX);

					if (pwm_failsafe != _mixing_output.failsafeValue(i)) {
						int32_t pwm_fail_new = _mixing_output.failsafeValue(i);
						param_set(param_find(str), &pwm_fail_new);
					}
				}
			}
		}

		// PWM_MAIN_DISx
		{
			sprintf(str, "%s_DIS%u", prefix, i + 1);
			int32_t pwm_dis = -1;

			if (param_get(param_find(str), &pwm_dis) == PX4_OK) {
				if (pwm_dis >= 0) {
					_mixing_output.disarmedValue(i) = math::constrain(pwm_dis, 0, PWM_HIGHEST_MAX);

					if (pwm_dis != _mixing_output.disarmedValue(i)) {
						int32_t pwm_dis_new = _mixing_output.disarmedValue(i);
						param_set(param_find(str), &pwm_dis_new);
					}

				} else {
					_mixing_output.disarmedValue(i) = pwm_disarmed_default;
				}
			}

			if (_mixing_output.disarmedValue(i) > 0) {
				num_disarmed_set++;
			}
		}

		// PWM_MAIN_REVx
		{
			sprintf(str, "%s_REV%u", prefix, i + 1);
			int32_t pwm_rev = 0;

			if (param_get(param_find(str), &pwm_rev) == PX4_OK) {
				uint16_t &reverse_pwm_mask = _mixing_output.reverseOutputMask();

				if (pwm_rev >= 1) {
Daniel Agar's avatar
Daniel Agar committed
785
					reverse_pwm_mask = reverse_pwm_mask | (1 << i);
Daniel Agar's avatar
Daniel Agar committed
786
787

				} else {
Daniel Agar's avatar
Daniel Agar committed
788
					reverse_pwm_mask = reverse_pwm_mask & ~(1 << i);
Daniel Agar's avatar
Daniel Agar committed
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
				}
			}
		}
	}

	if (_mixing_output.mixers()) {
		int16_t values[FMU_MAX_ACTUATORS] {};

		for (unsigned i = 0; i < _num_outputs; i++) {
			sprintf(str, "%s_TRIM%u", prefix, i + 1);

			float pval = 0.0f;
			param_get(param_find(str), &pval);
			values[i] = roundf(10000 * pval);
		}

		// copy the trim values to the mixer offsets
		_mixing_output.mixers()->set_trims(values, _num_outputs);
	}

	_num_disarmed_set = num_disarmed_set;
810
811
}

812
int PWMOut::ioctl(file *filp, int cmd, unsigned long arg)
813
{
814
	int ret;
815

David Sidrane's avatar
David Sidrane committed
816
817
818
819
820
821
822
	/* try it as a Capture ioctl next */
	ret = capture_ioctl(filp, cmd, arg);

	if (ret != -ENOTTY) {
		return ret;
	}

823
	/* if we are in valid PWM mode, try it as a PWM ioctl as well */
824
	switch (_mode) {
Julian Oes's avatar
Julian Oes committed
825
	case MODE_1PWM:
826
	case MODE_2PWM:
David Sidrane's avatar
David Sidrane committed
827
	case MODE_3PWM:
828
	case MODE_4PWM:
829
	case MODE_5PWM:
David Sidrane's avatar
David Sidrane committed
830
831
	case MODE_2PWM2CAP:
	case MODE_3PWM1CAP:
832
	case MODE_4PWM1CAP:
DanielePettenuzzo's avatar
DanielePettenuzzo committed
833
	case MODE_4PWM2CAP:
834
	case MODE_5PWM1CAP:
835
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 6
836
	case MODE_6PWM:
837
838
#endif
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 8
Ash Charles's avatar
Ash Charles committed
839
	case MODE_8PWM:
840
#endif
Daniel Agar's avatar
Daniel Agar committed
841
842
843
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 12
	case MODE_12PWM:
#endif
844
845
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 14
	case MODE_14PWM:
Ash Charles's avatar
Ash Charles committed
846
#endif
847
848
		ret = pwm_ioctl(filp, cmd, arg);
		break;
849

850
	default:
Daniel Agar's avatar
Daniel Agar committed
851
		PX4_DEBUG("pwm_out%u, not in a PWM mode", _instance);
852
853
854
855
		break;
	}

	/* if nobody wants it, let CDev have it */
856
	if (ret == -ENOTTY) {
857
		ret = CDev::ioctl(filp, cmd, arg);
858
	}
859
860
861
862

	return ret;
}

863
int PWMOut::pwm_ioctl(file *filp, int cmd, unsigned long arg)
864
865
866
{
	int ret = OK;

Daniel Agar's avatar
Daniel Agar committed
867
	PX4_DEBUG("pwm_out%u: ioctl cmd: %d, arg: %ld", _instance, cmd, arg);
868

869
870
	lock();

871
872
	switch (cmd) {
	case PWM_SERVO_ARM:
873
		update_pwm_out_state(true);
874
875
		break;

876
877
	case PWM_SERVO_SET_ARM_OK:
	case PWM_SERVO_CLEAR_ARM_OK:
878
	case PWM_SERVO_SET_FORCE_SAFETY_OFF:
879
	case PWM_SERVO_SET_FORCE_SAFETY_ON:
880
881
		break;

882
	case PWM_SERVO_DISARM:
883
884
885
886
887
888

		/* Ignore disarm if disarmed PWM is set already. */
		if (_num_disarmed_set == 0) {
			update_pwm_out_state(false);
		}

889
890
		break;

891
892
893
894
	case PWM_SERVO_GET_DEFAULT_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_default_rate;
		break;

895
	case PWM_SERVO_SET_UPDATE_RATE:
896
897
898
		ret = set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, arg);
		break;

899
900
901
902
903
	case PWM_SERVO_GET_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_alt_rate;
		break;

	case PWM_SERVO_SET_SELECT_UPDATE_RATE:
904
		ret = set_pwm_rate(arg, _pwm_default_rate, _pwm_alt_rate);
905
906
		break;

907
908
909
910
	case PWM_SERVO_GET_SELECT_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_alt_rate_channels;
		break;

911
	case PWM_SERVO_SET_FAILSAFE_PWM: {
912
913
914
			struct pwm_output_values *pwm = (struct pwm_output_values *)arg;

			/* discard if too many values are sent */
915
			if (pwm->channel_count > FMU_MAX_ACTUATORS) {
916
917
				ret = -EINVAL;
				break;
918
919
			}

920
921
922
923
			for (unsigned i = 0; i < pwm->channel_count; i++) {
				if (pwm->values[i] == 0) {
					/* ignore 0 */
				} else if (pwm->values[i] > PWM_HIGHEST_MAX) {
924
					_mixing_output.failsafeValue(i) = PWM_HIGHEST_MAX;
925

926
927
928
929
930
				}

#if PWM_LOWEST_MIN > 0

				else if (pwm->values[i] < PWM_LOWEST_MIN) {
931
					_mixing_output.failsafeValue(i) = PWM_LOWEST_MIN;
932

933
934
935
936
937
				}

#endif

				else {
938
					_mixing_output.failsafeValue(i) = pwm->values[i];
939
940
941
942
				}
			}

			break;
943
		}
944

945
	case PWM_SERVO_GET_FAILSAFE_PWM: {
946
			struct pwm_output_values *pwm = (struct pwm_output_values *)arg;
947

948
			for (unsigned i = 0; i < FMU_MAX_ACTUATORS; i++) {
949
				pwm->values[i] = _mixing_output.failsafeValue(i);
950
951
			}

952
			pwm->channel_count = FMU_MAX_ACTUATORS;
953
954
			break;
		}
955
956
957
958
959

	case PWM_SERVO_SET_DISARMED_PWM: {
			struct pwm_output_values *pwm = (struct pwm_output_values *)arg;

			/* discard if too many values are sent */
960
			if (pwm->channel_count > FMU_MAX_ACTUATORS) {
961
962
				ret = -EINVAL;
				break;
963
			}
964

965
966
967
968
			for (unsigned i = 0; i < pwm->channel_count; i++) {
				if (pwm->values[i] == 0) {
					/* ignore 0 */
				} else if (pwm->values[i] > PWM_HIGHEST_MAX) {
969
					_mixing_output.disarmedValue(i) = PWM_HIGHEST_MAX;
970
				}
971

972
973
974
#if PWM_LOWEST_MIN > 0

				else if (pwm->values[i] < PWM_LOWEST_MIN) {
975
					_mixing_output.disarmedValue(i) = PWM_LOWEST_MIN;
976
				}
977

978
979
980
#endif

				else {
981
					_mixing_output.disarmedValue(i) = pwm->values[i];
982
983
984
985
986
987
988
989
990
				}
			}

			/*
			 * update the counter
			 * this is needed to decide if disarmed PWM output should be turned on or not
			 */
			_num_disarmed_set = 0;

991
			for (unsigned i = 0; i < FMU_MAX_ACTUATORS; i++) {
992
				if (_mixing_output.disarmedValue(i) > 0) {
993
					_num_disarmed_set++;
Lorenz Meier's avatar
Lorenz Meier committed
994
				}
995
996
997
			}

			break;
998
		}
999

1000
	case PWM_SERVO_GET_DISARMED_PWM: {