PWMOut.cpp 53.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);

Daniel Agar's avatar
Daniel Agar committed
477
478
	PX4_INFO("instance: %d, MAX RATE: %d, default: %d, alt: %d", _instance, max_rate, _pwm_default_rate, _pwm_alt_rate);

479
480
	_current_update_rate = max_rate;
	_mixing_output.setMaxTopicUpdateRate(update_interval_in_us);
481
482
}

483
int PWMOut::task_spawn(int argc, char *argv[])
484
{
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
	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
503
			}
504

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

Daniel Agar's avatar
Daniel Agar committed
513
	return PX4_OK;
514
515
}

516
517
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
518
{
519
	PWMOut *dev = static_cast<PWMOut *>(context);
David Sidrane's avatar
David Sidrane committed
520
521
522
	dev->capture_callback(chan_index, edge_time, edge_state, overflow);
}

523
524
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
525
{
526
	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
527
}
528

529
void PWMOut::update_pwm_out_state(bool on)
530
531
{
	if (on && !_pwm_initialized && _pwm_mask != 0) {
532
		up_pwm_servo_init(_pwm_mask);
533
534
535
536
		set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, _pwm_alt_rate);
		_pwm_initialized = true;
	}

Daniel Agar's avatar
Daniel Agar committed
537
	up_pwm_servo_arm(on); // TODO REVIEW for multi
538
539
}

540
bool PWMOut::updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS],
541
542
543
			   unsigned num_outputs, unsigned num_control_groups_updated)
{
	if (_test_mode) {
544
		return false;
545
546
547
548
	}

	/* output to the servos */
	if (_pwm_initialized) {
549
		for (size_t i = 0; i < math::min(_num_outputs, num_outputs); i++) {
Daniel Agar's avatar
Daniel Agar committed
550
			up_pwm_servo_set(_output_base + i, outputs[i]);
551
552
553
554
555
556
557
		}
	}

	/* 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
558
		up_pwm_update(); // TODO: review for multi
559
	}
560
561

	return true;
562
563
}

564
void PWMOut::Run()
565
{
566
567
	if (should_exit()) {
		ScheduleClear();
568
		_mixing_output.unregister();
569

Daniel Agar's avatar
Daniel Agar committed
570
		//exit_and_cleanup();
571
572
573
		return;
	}

574
	perf_begin(_cycle_perf);
575
	perf_count(_interval_perf);
576

577
578
579
	// push backup schedule
	ScheduleDelayed(_backup_schedule_interval_us);

580
	if (_new_mode_request.load() != MODE_NO_REQUEST) {
581
		set_mode(_new_mode_request.load());
582
		_new_mode_request.store(MODE_NO_REQUEST);
583
584
	}

585
	_mixing_output.update();
Lorenz Meier's avatar
Lorenz Meier committed
586

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

590
591
592
593
	if (_pwm_on != pwm_on) {
		_pwm_on = pwm_on;
		update_pwm_out_state(pwm_on);
	}
Beat Küng's avatar
Beat Küng committed
594

595
596
597
598
599
600
601
	// check for parameter updates
	if (_parameter_update_sub.updated()) {
		// clear update
		parameter_update_s pupdate;
		_parameter_update_sub.copy(&pupdate);

		// update parameters from storage
602
603
		update_params();
	}
604

605
606
	if (_current_update_rate == 0) {
		update_current_rate();
607
	}
608

609
	// check at end of cycle (updateSubscriptions() can potentially change to a different WorkQueue thread)
610
	_mixing_output.updateSubscriptions(true, true);
611

612
	perf_end(_cycle_perf);
613
614
}

615
void PWMOut::update_params()
616
{
617
	updateParams();
Daniel Agar's avatar
Daniel Agar committed
618
619
620
621
622
623
624
625
626
627
628

	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";

629
630
631
632
		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
633
634
635
636
637
638

	} 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);
639
		param_get(param_find("PWM_AUX_DISARM"), &pwm_disarmed_default);
Daniel Agar's avatar
Daniel Agar committed
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
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
		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
752
					reverse_pwm_mask = reverse_pwm_mask | (1 << i);
Daniel Agar's avatar
Daniel Agar committed
753
754

				} else {
Daniel Agar's avatar
Daniel Agar committed
755
					reverse_pwm_mask = reverse_pwm_mask & ~(1 << i);
Daniel Agar's avatar
Daniel Agar committed
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
				}
			}
		}
	}

	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;
777
778
}

779
int PWMOut::ioctl(file *filp, int cmd, unsigned long arg)
780
{
781
	int ret;
782

David Sidrane's avatar
David Sidrane committed
783
784
785
786
787
788
789
	/* try it as a Capture ioctl next */
	ret = capture_ioctl(filp, cmd, arg);

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

790
	/* if we are in valid PWM mode, try it as a PWM ioctl as well */
791
	switch (_mode) {
Julian Oes's avatar
Julian Oes committed
792
	case MODE_1PWM:
793
	case MODE_2PWM:
David Sidrane's avatar
David Sidrane committed
794
	case MODE_3PWM:
795
	case MODE_4PWM:
796
	case MODE_5PWM:
David Sidrane's avatar
David Sidrane committed
797
798
	case MODE_2PWM2CAP:
	case MODE_3PWM1CAP:
799
	case MODE_4PWM1CAP:
DanielePettenuzzo's avatar
DanielePettenuzzo committed
800
	case MODE_4PWM2CAP:
801
	case MODE_5PWM1CAP:
802
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 6
803
	case MODE_6PWM:
804
805
#endif
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 8
Ash Charles's avatar
Ash Charles committed
806
	case MODE_8PWM:
807
#endif
Daniel Agar's avatar
Daniel Agar committed
808
809
810
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 12
	case MODE_12PWM:
#endif
811
812
#if defined(BOARD_HAS_PWM) && BOARD_HAS_PWM >= 14
	case MODE_14PWM:
Ash Charles's avatar
Ash Charles committed
813
#endif
814
815
		ret = pwm_ioctl(filp, cmd, arg);
		break;
816

817
	default:
Daniel Agar's avatar
Daniel Agar committed
818
		PX4_DEBUG("pwm_out%u, not in a PWM mode", _instance);
819
820
821
822
		break;
	}

	/* if nobody wants it, let CDev have it */
823
	if (ret == -ENOTTY) {
824
		ret = CDev::ioctl(filp, cmd, arg);
825
	}
826
827
828
829

	return ret;
}

830
int PWMOut::pwm_ioctl(file *filp, int cmd, unsigned long arg)
831
832
833
{
	int ret = OK;

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

836
837
	lock();

838
839
	switch (cmd) {
	case PWM_SERVO_ARM:
840
		update_pwm_out_state(true);
841
842
		break;

843
844
	case PWM_SERVO_SET_ARM_OK:
	case PWM_SERVO_CLEAR_ARM_OK:
845
	case PWM_SERVO_SET_FORCE_SAFETY_OFF:
846
	case PWM_SERVO_SET_FORCE_SAFETY_ON:
847
848
		break;

849
	case PWM_SERVO_DISARM:
850
851
852
853
854
855

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

856
857
		break;

858
859
860
861
	case PWM_SERVO_GET_DEFAULT_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_default_rate;
		break;

862
	case PWM_SERVO_SET_UPDATE_RATE:
863
864
865
		ret = set_pwm_rate(_pwm_alt_rate_channels, _pwm_default_rate, arg);
		break;

866
867
868
869
870
	case PWM_SERVO_GET_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_alt_rate;
		break;

	case PWM_SERVO_SET_SELECT_UPDATE_RATE:
871
		ret = set_pwm_rate(arg, _pwm_default_rate, _pwm_alt_rate);
872
873
		break;

874
875
876
877
	case PWM_SERVO_GET_SELECT_UPDATE_RATE:
		*(uint32_t *)arg = _pwm_alt_rate_channels;
		break;

878
	case PWM_SERVO_SET_FAILSAFE_PWM: {
879
880
881
			struct pwm_output_values *pwm = (struct pwm_output_values *)arg;

			/* discard if too many values are sent */
882
			if (pwm->channel_count > FMU_MAX_ACTUATORS) {
883
884
				ret = -EINVAL;
				break;
885
886
			}

887
888
889
890
			for (unsigned i = 0; i < pwm->channel_count; i++) {
				if (pwm->values[i] == 0) {
					/* ignore 0 */
				} else if (pwm->values[i] > PWM_HIGHEST_MAX) {
891
					_mixing_output.failsafeValue(i) = PWM_HIGHEST_MAX;
892

893
894
895
896
897
				}

#if PWM_LOWEST_MIN > 0

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

900
901
902
903
904
				}

#endif

				else {
905
					_mixing_output.failsafeValue(i) = pwm->values[i];
906
907
908
909
				}
			}

			break;
910
		}
911

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

915
			for (unsigned i = 0; i < FMU_MAX_ACTUATORS; i++) {
916
				pwm->values[i] = _mixing_output.failsafeValue(i);
917
918
			}

919
			pwm->channel_count = FMU_MAX_ACTUATORS;
920
921
			break;
		}
922
923
924
925
926

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

			/* discard if too many values are sent */
927
			if (pwm->channel_count > FMU_MAX_ACTUATORS) {
928
929
				ret = -EINVAL;
				break;
930
			}
931

932
933
934
935
			for (unsigned i = 0; i < pwm->channel_count; i++) {
				if (pwm->values[i] == 0) {
					/* ignore 0 */
				} else if (pwm->values[i] > PWM_HIGHEST_MAX) {
936
					_mixing_output.disarmedValue(i) = PWM_HIGHEST_MAX;
937
				}
938

939
940
941
#if PWM_LOWEST_MIN > 0

				else if (pwm->values[i] < PWM_LOWEST_MIN) {
942
					_mixing_output.disarmedValue(i) = PWM_LOWEST_MIN;
943
				}
944

945
946
947
#endif

				else {
948
					_mixing_output.disarmedValue(i) = pwm->values[i];
949
950
951
952
953
954
955
956
957
				}
			}

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

958
			for (unsigned i = 0; i < FMU_MAX_ACTUATORS; i++) {
959
				if (_mixing_output.disarmedValue(i) > 0) {
960
					_num_disarmed_set++;
Lorenz Meier's avatar
Lorenz Meier committed
961
				}
962
963
964
			}

			break;
965
		}
966

967
	case PWM_SERVO_GET_DISARMED_PWM: {
968
			struct pwm_output_values *pwm = (struct pwm_output_values *)arg;
969

970
			for (unsigned i = 0; i < FMU_MAX_ACTUATORS; i++) {
971
				pwm->values[i] = _mixing_output.disarmedValue(i);
972
973
			}

974
			pwm->channel_count = FMU_MAX_ACTUATORS;
975
976
			break;
		}
977
978
979
980
981

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

			/* discard if too many values are sent */
982
			if (pwm->channel_count > FMU_MAX_ACTUATORS) {
983
984
				ret = -EINVAL;
				break;
985
			}
986
987
988
989
990

			for (unsigned i = 0; i < pwm->channel_count; i++) {
				if (pwm->values[i] == 0) {
					/* ignore 0 */
				} else if (pwm->values[i] > PWM_HIGHEST_MIN) {
991
					_mixing_output.minValue(i) = PWM_HIGHEST_MIN;
992

993
994
995
996
997
				}

#if PWM_LOWEST_MIN > 0

				else if (pwm->values[i] < PWM_LOWEST_MIN) {
998
					_mixing_output.minValue(i) = PWM_LOWEST_MIN;
999
				}
1000