プログラムを貼ってみる実験(小分け編1/2

#include <Time.h>
#include <TimeLib.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// bit set / clear
#ifndef cbi
#define cbi(PORT, BIT) (_SFR_BYTE(PORT) &= ~_BV(BIT))
#endif
#ifndef sbi
#define sbi(PORT, BIT) (_SFR_BYTE(PORT) |= _BV(BIT))
#endif


// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

unsigned int localPort = 8888; // local port to listen for UDP packets

char timeServer = "time.nist.gov"; // time.nist.gov NTP server

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;

byte timecode[60];
unsigned long lastNTPTime = 0;

void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}

// start Ethernet and UDP
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
for (;;)
;
}
Udp.begin(localPort);
NTPSetTime();
setupTimeCode();
}


void loop()
{
int wait_start = second();
while (wait_start == second()); // wait until time is corrected
unsigned long startTime = millis();

// generate 40khz from 3 pin using PWM
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
TCCR2A = _BV(WGM20);
TCCR2B = _BV(WGM22) | _BV(CS20);
OCR2A = F_CPU / 2 / 40000/*hz*/;
OCR2B = OCR2A / 2; /* 50% duty */
sbi(TCCR2A,COM2B1);

// calc signal duration (ms)
int ms = calcTimeCodeDuration();

// wait ms and stop PWM
while (millis() - startTime < ms);
cbi(TCCR2A,COM2B1);

if (millis() - lastNTPTime > 60*60*1000L) {
NTPSetTime();
setupTimeCode();
lastNTPTime = millis();
}
}