Show Posts
Pages: [1] 2
1  Using Arduino / General Electronics / Re: Designing optocoupler circuit for arduino input on: February 14, 2013, 11:38:48 am
There is another weak point in the circuit of mmoscz:

ALWAYS connect the transistors at the inputs with their emitter to GND and the collector to the input! This is more safe against disturbances.
The resistor is not necessary, just use the command

digitalWrite(Pin#,INPUT);
digitalWrite(Pin#,HIGH);

with this you enable the internal pull up resistor.

If it is absolutely required to go your way due to any other reason, you need to use much lesser resistor value.
2  Using Arduino / General Electronics / Re: Designing optocoupler circuit for arduino input on: February 14, 2013, 11:22:56 am
Hi this circuit is no good idea as it is, mmoscz!

This circuit MUST be completed with diodes antiparallel to the opto-LED, or they will be destroyed by the negative voltage. LED's are sensitive against negative voltage.
Additionally (surge-) suppressor diodes would help to protect against bursts on the line which are caused by most electrical machines an by dimmers as well as just switching anything on or off.
3  Using Arduino / Programming Questions / Re: Problem with setSyncProvider() [from Time Library] on: February 09, 2013, 10:20:59 am
@johncc
the 500ms should be no problem. As I wrote: I always get the time, if I call getNtpTime(); with the method "setTime((time_t)getNtpTime());" the clock will always be set.
I'm using the same time lib, the files already came with IDE 1.0.1 and are from Jul and Sept 2011.

@PaulS
If just calling setSyncProvider(getNtpTime); is fundamentally wrong, I'm asking why is this method presented in every example?
I began with copy and paste.
And again: getNtpTime(); works well!! Just setSyncProvider(getNtpTime); does not return. And this must work independently from the chosen interval.

What I'm wondering now is that the function getNtpTime() is returning an "unsigned long" while setTime() -and maybe setSyncProvider internally also- is requesting "time_t". I know, there is only a pointer argument in the call setSyncProvider(getNtpTime); , but somehow the time has to be transferred.
 
4  Using Arduino / Programming Questions / Re: Problem with setSyncProvider() [from Time Library] on: February 09, 2013, 05:23:05 am
Meanwhile I replaced the setting of the clock by

setTime((time_t)getNtpTime());

It works for the moment, but it is not what wanted initially, as the getSyncProvider cares also for re-syncing.
Ans I don't know if the cast trick has negative side effects.
5  Using Arduino / Programming Questions / Re: Problem with setSyncProvider() [from Time Library] on: February 09, 2013, 03:36:44 am
Nick,

did you think of this?
Code:

volatile boolean s_flag = false;


it did not work. (I'm not a specialist in C...)
6  Using Arduino / General Electronics / Re: Designing optocoupler circuit for arduino input on: February 09, 2013, 03:21:34 am
I suggest, to use an additional capacitor in series with the resistor, that limits the current as well, but it does not produce as much heat. It does not just convert current to heat loss. The impedance [ohms] you can calculate with 1/(2*Pi*50*C). Some 100 nF should do. To protect the opto you just insert a Zener in parallel to the opto-LED. There are special surge supressor diodes for this usage. Your dealer should be able to help to find the right one. For a quick'n'dirty solution you could also use 3 or 4 normal diodes in series, and this (in forward direction) in parallel to the opto input.

Be careful!
7  Using Arduino / General Electronics / Re: Reducing voltage on a breadboard. on: February 09, 2013, 03:06:57 am
I would suggest to use a phone chaging plug for usage in cars. They normally have an input range starting from 6 point something volts up to 30V. They have an output of 5V and in the bay you catch them for very few $.
The advantage is good regulation of the output and very low power dissipation.
8  Using Arduino / Programming Questions / Problem with setSyncProvider() [from Time Library] on: February 09, 2013, 02:52:52 am
I'm getting mad on this...
My application grew and grew and even though it is my first try, everything worked fine until I tried to implement a clock. I stuck already a week on this.
Meanwhile I located the error, but I have no idea, what the root cause could be.

In my program I want to set the clock by NTP, but when calling the function setSyncProvider(getNtpTime); normally nothing will happen except that there will be a timeout after a certain time (not the while... loop, the printout "Time Status after setSyncProvider" does not appear). The time status will not change and the clock is not set. A very few times it works fine, but I did not find out in which cases. I sometimes thought I have some evidence, but a few trials later it was gone.

Below the code I printed the serial output. In this example two times the setting of the clock did not work, the third try runs and the clock output begins.
It is obvious, that the function getNtpTime(); always returns the correct time (as you also can see in the printout). But the setSyncProvider() function only gets the pointer to the function getNtpTime(); I think, and I don't know how the clock is being set when using this construction, so I don't know how to locate the real problem.
Has anybody an idea?

Code:
// NTP time issue
// IDE 1.0.3
// DHCP Server required
// Arduino Mega2560 + Ethernetshield for Mega with SD-slot

#include <MsTimer2.h>
#include <Time.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>


#define SD_CS 4

// Ethernet library configuration
byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
IPAddress timeServer;

/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 8888;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;     
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE]; 
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                   

boolean s_flag = false;



void setup() {               

  // disable SD SPI Chip Select
  pinMode(SD_CS,OUTPUT);
  digitalWrite(SD_CS,HIGH);

  Serial.begin(19200);
 

// Setup Ethernet by DHCP

  Serial.println("Wait for DHCP Server");
  if (Ethernet.begin(mac) == 0) {  // start Ethernet by DHCP conf.
    Serial.println("DHCP config failed! ");
  }

  DNSClient dns;
  dns.begin(Ethernet.dnsServerIP());
  dns.getHostByName("pool.ntp.org",timeServer); // at this point the function works
  Serial.print("NTP Server: ");
  Serial.println(timeServer);

  setSyncInterval(5); // Set seconds between re-sync (5s for test only)
 
  Udp.begin(localPort);
  Serial.print("Time: ");
  Serial.println(getNtpTime());
  Serial.print("Time Status before setSyncProvider:");
  Serial.println(timeStatus());
  setSyncProvider(getNtpTime);
  Serial.print("Time Status after setSyncProvider:");
  Serial.println(timeStatus());

  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider


  MsTimer2::set(1000, update1s); // 1s period
  MsTimer2::start();


}
 
 
void loop() {

  if (s_flag){
    s_flag=false; 
    digitalClockDisplay();
  }




void update1s(){
// 1s is over flag
  s_flag=true;
}


void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(day());
  Serial.print(".");
  Serial.print(month());
  Serial.print(".");
  Serial.print(year());
  Serial.print(" ");
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(" ");
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding
  // colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(500);
   
    if ( Udp.parsePacket() ) {
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer


     //the timestamp starts at byte 40, convert four bytes into a long integer
     unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
     unsigned long low = word(packetBuffer[42], packetBuffer[43]);
     // this is NTP time (seconds since Jan 1 1900
     unsigned long secsSince1900 = hi << 16 | low; 
     // Unix time starts on Jan 1 1970
     const unsigned long seventyYears = 2208988800UL;     
     unsigned long epoch = secsSince1900 - seventyYears + adjustDstEurope();  // subtract 70 years, add Daylight Saving and Timezone adjust
     return epoch;
  }
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(IPAddress& address)
//sendNTPpacket(IPAddress address)
{


  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0

  // Initialize values needed to form NTP request
  packetBuffer[0] = B11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum
  packetBuffer[2] = 6;     // Max Interval between messages in seconds
  packetBuffer[3] = 0xEC;  // Clock Precision
  // bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
  packetBuffer[12]  = 49;  // four-byte reference ID identifying
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // send the packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123

  Udp.write(packetBuffer,NTP_PACKET_SIZE);

  Udp.endPacket();

}


int adjustDstEurope()
{
  // last sunday of march
  int beginDSTDate=  (31 - (5* year() /4 + 4) % 7);
  //Serial.println(beginDSTDate);
  int beginDSTMonth=3;
  //last sunday of october
  int endDSTDate= (31 - (5 * year() /4 + 1) % 7);
  //Serial.println(endDSTDate);
  int endDSTMonth=10;
  // DST is valid as:
  if (((month() > beginDSTMonth) && (month() < endDSTMonth))
      || ((month() == beginDSTMonth) && (day() >= beginDSTDate))
      || ((month() == endDSTMonth) && (day() <= endDSTDate)))
  return 7200;  // DST europe = utc +2 hour
  else return 3600; // nonDST europe = utc +1 hour
}


Wait for DHCP Server
NTP Server: 91.143.83.62
Time: 1360396530
Time Status before setSyncProvider:0

---restarted due to USB interrupt

Wait for DHCP Server
NTP Server: 46.4.54.78
Time: 1360396556
Time Status before setSyncProvider:0

---restarted due to USB interrupt

Wait for DHCP Server
NTP Server: 178.63.9.212
Time: 1360396573
Time Status before setSyncProvider:0
Time Status after setSyncProvider:2
9.2.2013 7:56:14
9.2.2013 7:56:15
9.2.2013 7:56:16
9.2.2013 7:56:17
...
9  Using Arduino / Programming Questions / Re: Problem with dns.getHostByName("pool.ntp.org",timeServer); on: February 06, 2013, 11:52:46 am
Thanks SurferTim!
Your example works also in my environment. I will use it as the base for my implementation.

kind regards from cold Berlin
purehunter
10  Using Arduino / Programming Questions / Re: Problem with dns.getHostByName("pool.ntp.org",timeServer); on: February 04, 2013, 03:45:18 pm
@SurferTim
curious, I definitely did not remove the "&" from the example I copied, as I don't understand its meaning. Can you tell me, what it means at this place? I know it in regard to pointers, but oly in front of the name.
First I thought, it works with that Ampersand added in, but further tries showed the same as before: sometime it works, mostly not.

From my view "void" should be ok for that function, as it doesn't return anything.

@PaulS
In the instruction for the time.h, I found this:
Functions for managing the timer services are:
...
 setSyncProvider(getTimeFunction);// Set the external time
                                  //  provider
 setSyncInterval(interval);    // Set the number of
                               //  seconds between re-sync
 


So after reading your question, may it be correct to use the "setSyncProvider()" only once in combination with "setSyncInterval()" and thats it?
11  Using Arduino / Programming Questions / Re: Problem with dns.getHostByName("pool.ntp.org",timeServer); on: February 04, 2013, 01:00:14 pm
@SurferTim
Quote
Move the declaration for DNSClient dns;
...
edit: Or use another declaration in your other function.

I declared it already in the function according Pauls hint. That worked.

The mentioned thread I already knew. It uses the same -functional- code than I. The only modifications I did is the function declaration (unsigned long -> void)
as I got compiler warnings at that point.
Code:
// send an NTP request to the time server at the given address
//unsigned long sendNTPpacket(IPAddress address)
void sendNTPpacket(IPAddress address)
{

and I tried out several delays
Code:

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(500);
   
    if ( Udp.parsePacket() ) {

What I mostly wondering about is the fact that with some servers it works fine, also the re-syncing


@PaulS
Quote
How is calling that function again here useful?

Why not re-syncing?
Do you have a better idea?
I don't have a RTC so I thought it would be good to re-sync time after time

12  Using Arduino / Programming Questions / Re: Problem with dns.getHostByName("pool.ntp.org",timeServer); on: February 04, 2013, 12:10:26 pm
@PaulS
thanks for your hint! Now I got it.

But there is another problem where I don't have a clue, what goes wrong, as I just use the code that is used in 99% of examples with minimal modification.
It seems to me, that there is no response from the time server, but I can't believe that.

Before I implemented the dns code for the usage of NTP pools, I used fixed IP's for the time server. Then the effect was, that I found one NTP server where I got the time always immediately. Nearly all other server IP's I used, led to the same situation as I have it now with 99% of the IP's from the pool: the program will stuck in the endless loop in the setup() :

Code:
  lcd.print("NTP sync ...        ");
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider



The complete code is

Code:
// NTP time
// IDE 1.0.3 Win7/64
// DHCP Server required
// LCD connected for debugging


#include <MsTimer2.h>
#include <Time.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>

// LCD
#define LCD_RS 15
#define LCD_E 16
#define LCD_D4 21
#define LCD_D5 20
#define LCD_D6 19
#define LCD_D7 18

LiquidCrystal lcd(LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

// Ethernet library configuration
byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
IPAddress timeServer(0, 0, 0, 0);

/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 75;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;     
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE]; 
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                   

boolean s_flag = false;



void setup() {               

    lcd.begin(20, 4);

// Setup Ethernet by DHCP
    lcd.setCursor(0,0);
    lcd.print("Wait for DHCP Server");
    if (Ethernet.begin(mac) == 0) {  // start Ethernet by DHCP conf.
      lcd.setCursor(0,0);
      lcd.print("DHCP config failed! ");
     }

  DNSClient dns;
  dns.begin(Ethernet.dnsServerIP());
  dns.getHostByName("pool.ntp.org",timeServer); // at this point the function works
  lcd.setCursor(0,1); //col,row
  lcd.print("NTP: ");
  lcd.print(timeServer);
 
  Udp.begin(localPort);
  lcd.setCursor(0,0);
  lcd.print("NTP sync ...        ");
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider
  setSyncInterval(86400);    // Set seconds between re-sync 86400 = 24hr
  //setSyncInterval(120);                           

  MsTimer2::set(1000, update1s); // 1s period
  MsTimer2::start();

}
 
 
void loop() {

  if (s_flag){
    s_flag=false; 
    digitalClockDisplay();
    ntpSync();
  }




void update1s(){
// das Flag zeigt an, ob 1s um ist
s_flag=true;
}

void ntpSync(){

  if (((minute() % 3)==0) && (second()==0)){
//  dns.getHostByName("pool.ntp.org",timeServer); //at this point the function causes a Compiler error
    setSyncProvider(getNtpTime);
  }   
}



void digitalClockDisplay(){
  // digital clock display of the time
  lcd.setCursor(0,0); //col,row
  lcd.print(day());
  lcd.print(".");
  lcd.print(month());
  lcd.print(".");
  lcd.print(year()-2000);
  lcd.print(" ");
  lcd.print(hour());
  printDigits(minute());
  if(timeStatus()!= timeNeedsSync) // if ntp sync lost, don't show the seconds to indicate this
    printDigits(second());
  else
    lcd.print("   ");
  lcd.print("  ");
 
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding
  // colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(500);
   
    if ( Udp.parsePacket() ) {
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer


     //the timestamp starts at byte 40, convert four bytes into a long integer
     unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
     unsigned long low = word(packetBuffer[42], packetBuffer[43]);
     // this is NTP time (seconds since Jan 1 1900
     unsigned long secsSince1900 = hi << 16 | low; 
     // Unix time starts on Jan 1 1970
     const unsigned long seventyYears = 2208988800UL;     
     unsigned long epoch = secsSince1900 - seventyYears + adjustDstEurope();  // subtract 70 years, add Daylight Saving and Timezone adjust
     return epoch;
  }
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
//unsigned long sendNTPpacket(IPAddress address)
void sendNTPpacket(IPAddress address)
{


  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0

  // Initialize values needed to form NTP request
  packetBuffer[0] = B11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum
  packetBuffer[2] = 6;     // Max Interval between messages in seconds
  packetBuffer[3] = 0xEC;  // Clock Precision
  // bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
  packetBuffer[12]  = 49;  // four-byte reference ID identifying
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // send the packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123

  Udp.write(packetBuffer,NTP_PACKET_SIZE);

  Udp.endPacket();

}


int adjustDstEurope()
{
  // last sunday of march
  int beginDSTDate=  (31 - (5* year() /4 + 4) % 7);
  //Serial.println(beginDSTDate);
  int beginDSTMonth=3;
  //last sunday of october
  int endDSTDate= (31 - (5 * year() /4 + 1) % 7);
  //Serial.println(endDSTDate);
  int endDSTMonth=10;
  // DST is valid as:
  if (((month() > beginDSTMonth) && (month() < endDSTMonth))
      || ((month() == beginDSTMonth) && (day() >= beginDSTDate))
      || ((month() == endDSTMonth) && (day() <= endDSTDate)))
  return 7200;  // DST europe = utc +2 hour
  else return 3600; // nonDST europe = utc +1 hour
}


13  Using Arduino / Programming Questions / Re: how to add debounce code to pushingbox code on: February 02, 2013, 02:44:49 am
Try this code. It should lit the onboard LED when pressing the key at pin 3...
Code:
#include <Bounce.h>
// search for this lib and read the instructions...
// to have a comfortable debouncing and key reading

#define KEY 3
#define LED 13


Bounce key = Bounce( KEY, 50 ); //Debounce for 50ms


void setup() {               

  pinMode(KEY, INPUT); 
  digitalWrite(KEY, HIGH);

  pinMode(LED,OUTPUT); 

}

void loop() {

  processKey();
 


void processKey(){
  key.update(); // Bounce check for key status
  if ( key.fallingEdge())  // key pressed
    {
    digitalWrite(LED,HIGH); //LED on
    }
  else
    digitalWrite(LED,LOW); //LED off
     
  }
14  Using Arduino / Programming Questions / Re: Problem with dns.getHostByName("pool.ntp.org",timeServer); on: February 02, 2013, 02:10:15 am
Nice tone!

Try again: I stripped down the sketch to the intresting parts. There are 2 points with the dns.getHostByName() call. One is working [in the setup()] and one leads to the compiler error [in ntpSync()]:

error: request for member 'getHostByName' in 'dns', which is of non-class type '<anonymous enum>'

What can I do to use dns.getHostByName() frequently to fresh up the used server IP? Or for other purposes?

Code:
// NTP time
// IDE 1.0.3 Win7/64
// DHCP Server required
// LCD connected for debugging


#include <MsTimer2.h>
#include <Time.h>
#include <LiquidCrystal.h>
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>

// LCD
#define LCD_RS 15
#define LCD_E 16
#define LCD_D4 21
#define LCD_D5 20
#define LCD_D6 19
#define LCD_D7 18

LiquidCrystal lcd(LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

// Ethernet library configuration
byte mac[] = { 0x24, 0x7B, 0xA2, 0x4A, 0x52, 0x10 };
IPAddress timeServer(0, 0, 0, 0);

/* ALTER THESE VARIABLES AT YOUR OWN RISK */
// local port to listen for UDP packets
unsigned int localPort = 75;
// NTP time stamp is in the first 48 bytes of the message
const int NTP_PACKET_SIZE= 48;     
// Buffer to hold incoming and outgoing packets
byte packetBuffer[NTP_PACKET_SIZE]; 
// A UDP instance to let us send and receive packets over UDP
EthernetUDP Udp;                   

boolean s_flag = false;



void setup() {               

    lcd.begin(20, 4);

// Setup Ethernet by DHCP
    lcd.setCursor(0,0);
    lcd.print("Wait for DHCP Server");
    if (Ethernet.begin(mac) == 0) {  // start Ethernet by DHCP conf.
      lcd.setCursor(0,0);
      lcd.print("DHCP config failed! ");
     }

  DNSClient dns;
  dns.begin(Ethernet.dnsServerIP());
  dns.getHostByName("pool.ntp.org",timeServer); // at this point the function works
  lcd.setCursor(0,1); //col,row
  lcd.print("NTP: ");
  lcd.print(timeServer);
 
  Udp.begin(localPort);
  lcd.setCursor(0,0);
  lcd.print("NTP sync ...        ");
  setSyncProvider(getNtpTime);
  while(timeStatus()== timeNotSet)
     ; // wait until the time is set by the sync provider
  setSyncInterval(86400);    // Set seconds between re-sync 86400 = 24hr
  //setSyncInterval(120);                           

  MsTimer2::set(1000, update1s); // 1s period
  MsTimer2::start();

}
 
 
void loop() {

  if (s_flag){
    s_flag=false; 
    digitalClockDisplay();
    ntpSync();
  }




void update1s(){
// das Flag zeigt an, ob 1s um ist
s_flag=true;
}

void ntpSync(){

  if (((minute() % 3)==0) && (second()==0)){
//  dns.getHostByName("pool.ntp.org",timeServer); //at this point the function causes a Compiler error
    setSyncProvider(getNtpTime);
  }   
}



void digitalClockDisplay(){
  // digital clock display of the time
  lcd.setCursor(0,0); //col,row
  lcd.print(day());
  lcd.print(".");
  lcd.print(month());
  lcd.print(".");
  lcd.print(year()-2000);
  lcd.print(" ");
  lcd.print(hour());
  printDigits(minute());
  if(timeStatus()!= timeNeedsSync) // if ntp sync lost, don't show the seconds to indicate this
    printDigits(second());
  else
    lcd.print("   ");
  lcd.print("  ");
 
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding
  // colon and leading 0
  lcd.print(":");
  if(digits < 10)
    lcd.print('0');
  lcd.print(digits);
}

/*-------- NTP code ----------*/

unsigned long getNtpTime()
{
  sendNTPpacket(timeServer); // send an NTP packet to a time server
    delay(500);
   
    if ( Udp.parsePacket() ) {
     Udp.read(packetBuffer,NTP_PACKET_SIZE);  // read packet into buffer


     //the timestamp starts at byte 40, convert four bytes into a long integer
     unsigned long hi = word(packetBuffer[40], packetBuffer[41]);
     unsigned long low = word(packetBuffer[42], packetBuffer[43]);
     // this is NTP time (seconds since Jan 1 1900
     unsigned long secsSince1900 = hi << 16 | low; 
     // Unix time starts on Jan 1 1970
     const unsigned long seventyYears = 2208988800UL;     
     unsigned long epoch = secsSince1900 - seventyYears + adjustDstEurope();  // subtract 70 years, add Daylight Saving and Timezone adjust
     return epoch;
  }
  return 0; // return 0 if unable to get the time
}

// send an NTP request to the time server at the given address
//unsigned long sendNTPpacket(IPAddress address)
void sendNTPpacket(IPAddress address)
{


  memset(packetBuffer, 0, NTP_PACKET_SIZE);  // set all bytes in the buffer to 0

  // Initialize values needed to form NTP request
  packetBuffer[0] = B11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum
  packetBuffer[2] = 6;     // Max Interval between messages in seconds
  packetBuffer[3] = 0xEC;  // Clock Precision
  // bytes 4 - 11 are for Root Delay and Dispersion and were set to 0 by memset
  packetBuffer[12]  = 49;  // four-byte reference ID identifying
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // send the packet requesting a timestamp:
  Udp.beginPacket(address, 123); //NTP requests are to port 123

  Udp.write(packetBuffer,NTP_PACKET_SIZE);

  Udp.endPacket();

}


int adjustDstEurope()
{
  // last sunday of march
  int beginDSTDate=  (31 - (5* year() /4 + 4) % 7);
  //Serial.println(beginDSTDate);
  int beginDSTMonth=3;
  //last sunday of october
  int endDSTDate= (31 - (5 * year() /4 + 1) % 7);
  //Serial.println(endDSTDate);
  int endDSTMonth=10;
  // DST is valid as:
  if (((month() > beginDSTMonth) && (month() < endDSTMonth))
      || ((month() == beginDSTMonth) && (day() >= beginDSTDate))
      || ((month() == endDSTMonth) && (day() <= endDSTDate)))
  return 7200;  // DST europe = utc +2 hour
  else return 3600; // nonDST europe = utc +1 hour
}

15  Using Arduino / Programming Questions / Re: how to add debounce code to pushingbox code on: February 01, 2013, 03:26:03 pm
May be I do not fully understand your circuit, but why do you use external resistor?
Best method is using internal pull-up resistors. You can do this by writing HIGH to the input.

  pinMode(KEY, INPUT); 
  digitalWrite(KEY, HIGH);

In this case you have to connect the key to GND and to the input pin. The logic is inverted in this case, meaning the key is activated when the input gets low.

It is no good idea to make it opposite and pull the input down to gnd with a resistor and connect the switch to VCC and input!
The reason is the very low threshold for the low signal you are generating with the resistor at the input with an open input. It is ony 0.8V and it will generally lead to false events.



Pages: [1] 2