SerialReceivewithServo.ino 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Control a servo according to incoming OSC control
  3. *
  4. */
  5. #include <OSCBundle.h>
  6. #include <OSCBoards.h>
  7. #include <Servo.h>
  8. #ifdef BOARD_HAS_USB_SERIAL
  9. #include <SLIPEncodedUSBSerial.h>
  10. SLIPEncodedUSBSerial SLIPSerial( thisBoardsSerialUSB );
  11. #else
  12. #include <SLIPEncodedSerial.h>
  13. SLIPEncodedSerial SLIPSerial(Serial1);
  14. #endif
  15. Servo myservo;
  16. void servoControl(OSCMessage &msg)
  17. {
  18. if (msg.isInt(0))
  19. {
  20. myservo.write(msg.getInt(0));
  21. }
  22. #ifdef TEMPoraray
  23. else if (msg.isFloat(0))
  24. {
  25. //test if that pin is a PWM
  26. if (digitalPinHasPWM(LED_BUILTIN))
  27. {
  28. pinMode(LED_BUILTIN, OUTPUT);
  29. analogWrite(LED_BUILTIN, (int)(msg.getFloat(0)*127.0f));
  30. }
  31. else
  32. SoftPWMSet(LED_BUILTIN, (int)(msg.getFloat(0)*127.0f));
  33. }
  34. #endif
  35. }
  36. void setup() {
  37. SLIPSerial.begin(9600);
  38. myservo.attach(13);
  39. myservo.write(90);
  40. }
  41. //reads and dispatches the incoming message
  42. void loop(){
  43. OSCBundle bundleIN;
  44. int size;
  45. while(!SLIPSerial.endofPacket())
  46. if( (size =SLIPSerial.available()) > 0)
  47. {
  48. while(size--)
  49. bundleIN.fill(SLIPSerial.read());
  50. }
  51. if(!bundleIN.hasError())
  52. bundleIN.dispatch("/servo", servoControl);
  53. }