LoginSignup
7
8

More than 5 years have passed since last update.

UDP通信でPCからLED(on Arduino)の点滅を制御する

Posted at

はじめに

前回、ArduinoをTCP通信を用いて制御することに成功しました。今回はこれをUDP通信に変える方法を紹介します。UDP通信にすることで

  • 遅延が少なくなる。
  • Max/Mspでのコーディングが楽になる。

という利点があります。

コード

コードは以下の通りです。付属している UDPSendReceiveを改変して使いました

udp.ino
#include <SPI.h>        
#include <Ethernet2.h>
#include <EthernetUdp2.h>  

//macコードを入力
byte mac[] = {
  *,*,*,*,*,*
};
//IPコードを入力
IPAddress ip(*,*,*,*);

unsigned int localPort = 80;      //ポート番号

// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
EthernetUDP Udp;

void setup() {
  // start the Ethernet and UDP:
  Ethernet.begin(mac, ip);
  Udp.begin(localPort);
  pinMode(9,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  // if there's data available, read a packet
  int packetSize = Udp.parsePacket();
  if (packetSize){
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
    for(int i=0;i<packetSize;i++){
      if(packetBuffer[0]=='a'){
        digitalWrite(9,HIGH);
        break;
      }else if(packetBuffer[0]=='b'){
        digitalWrite(9,LOW);
        break;
      }
    }
  }
}

注意

ライブラリEthernet2はArduino 1.7.1以降のideでないと実行できません。これはこちらでダウンロードできます。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8