Start/stop/configure PWM on a pin
()
| 361 | |
| 362 | @app.route('/api/pwm', methods=['POST']) |
| 363 | def control_pwm(): |
| 364 | """Start/stop/configure PWM on a pin""" |
| 365 | try: |
| 366 | data = request.get_json() |
| 367 | pin = int(data['pin']) |
| 368 | action = data['action'].lower() |
| 369 | |
| 370 | if pin not in VALID_PINS: |
| 371 | return jsonify({'error': f'Invalid pin {pin}'}), 400 |
| 372 | |
| 373 | if action == 'start': |
| 374 | frequency = float(data.get('frequency', 1000)) |
| 375 | duty_cycle = float(data.get('duty_cycle', 50)) |
| 376 | |
| 377 | if duty_cycle < 0 or duty_cycle > 100: |
| 378 | return jsonify({'error': 'Duty cycle must be 0-100%'}), 400 |
| 379 | |
| 380 | # Stop existing PWM if running |
| 381 | if pin in pwm_devices: |
| 382 | old_device = pwm_devices[pin]['device'] |
| 383 | if hasattr(old_device, 'close'): |
| 384 | old_device.close() |
| 385 | |
| 386 | # Cleanup regular pin configuration |
| 387 | cleanup_pin(pin) |
| 388 | |
| 389 | if GPIO_BACKEND == 'gpiozero': |
| 390 | pwm_device = PWMOutputDevice(pin, frequency=frequency) |
| 391 | pwm_device.value = duty_cycle / 100.0 |
| 392 | |
| 393 | elif GPIO_BACKEND == 'RPi.GPIO': |
| 394 | GPIO.setup(pin, GPIO.OUT) |
| 395 | pwm_device = GPIO.PWM(pin, frequency) |
| 396 | pwm_device.start(duty_cycle) |
| 397 | |
| 398 | else: # mock |
| 399 | pwm_device = GPIO.PWM(pin, frequency) |
| 400 | pwm_device.start(duty_cycle) |
| 401 | |
| 402 | pwm_devices[pin] = { |
| 403 | 'device': pwm_device, |
| 404 | 'frequency': frequency, |
| 405 | 'duty_cycle': duty_cycle |
| 406 | } |
| 407 | |
| 408 | log_event(f"PWM started on pin {pin}: {frequency}Hz, {duty_cycle}% duty cycle") |
| 409 | |
| 410 | elif action == 'stop': |
| 411 | if pin in pwm_devices: |
| 412 | pwm_device = pwm_devices[pin]['device'] |
| 413 | |
| 414 | if GPIO_BACKEND == 'gpiozero': |
| 415 | pwm_device.close() |
| 416 | elif GPIO_BACKEND == 'RPi.GPIO': |
| 417 | pwm_device.stop() |
| 418 | else: # mock |
| 419 | pwm_device.stop() |
| 420 |
nothing calls this directly
no test coverage detected