UDPEcho.ino 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. Leverage the UDP source IP and port calls to
  3. return OSC information back
  4. This example can be extended to build routers and forwarders of OSC packets
  5. */
  6. #include <Ethernet.h>
  7. #include <EthernetUdp.h>
  8. #include <SPI.h>
  9. #include <OSCBundle.h>
  10. EthernetUDP Udp;
  11. //the Arduino's IP
  12. IPAddress ip(128, 32, 122, 252);
  13. //port numbers
  14. const unsigned int inPort = 8888;
  15. const unsigned int outPort = 9999;
  16. //everything on the network needs a unique MAC
  17. #if defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MKL26Z64__)
  18. // Teensy 3.x has MAC burned in
  19. static byte mac[6];
  20. void read(uint8_t word, uint8_t *mac, uint8_t offset) {
  21.   FTFL_FCCOB0 = 0x41;             // Selects the READONCE command
  22.   FTFL_FCCOB1 = word;             // read the given word of read once area
  23.   // launch command and wait until complete
  24.   FTFL_FSTAT = FTFL_FSTAT_CCIF;
  25.   while(!(FTFL_FSTAT & FTFL_FSTAT_CCIF));
  26.   *(mac+offset) =   FTFL_FCCOB5;       // collect only the top three bytes,
  27.   *(mac+offset+1) = FTFL_FCCOB6;       // in the right orientation (big endian).
  28.   *(mac+offset+2) = FTFL_FCCOB7;       // Skip FTFL_FCCOB4 as it's always 0.
  29. }
  30. void read_mac() {
  31.   read(0xe,mac,0);
  32.   read(0xf,mac,3);
  33. }
  34. #else
  35. void read_mac() {}
  36. byte mac[] = {
  37. 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // you can find this written on the board of some Arduino Ethernets or shields
  38. #endif
  39. void setup() {
  40. Ethernet.begin(mac,ip);
  41. Udp.begin(inPort);
  42. }
  43. void loop(){
  44. OSCBundle bndl;
  45. int size;
  46. //receive a bundle
  47. if( (size = Udp.parsePacket())>0)
  48. {
  49. // unsigned int outPort = Udp.remotePort();
  50. while(size--)
  51. bndl.fill(Udp.read());
  52. if(!bndl.hasError())
  53. {
  54. //and echo it back
  55. if(bndl.size() > 0)
  56. {
  57. static int32_t sequencenumber=0;
  58. // we can sneak an addition onto the end of the bundle
  59. bndl.add("/micros").add((int32_t)micros()); // (int32_t) is the type of OSC Integers
  60. bndl.add("/sequencenumber").add(sequencenumber++);
  61. Udp.beginPacket(Udp.remoteIP(), outPort);
  62. bndl.send(Udp);
  63. Udp.endPacket();
  64. }
  65. }
  66. }
  67. }