How to toggle a digital pin

I’m trying to figure out how to do a simple toggle of an led. Here’s what I got so far:

// We name pin D0 as led
int led = D0; 

// This routine runs only once upon reset
void setup() 
{
  // Initialize D0 pin as an output
  pinMode(led, OUTPUT);
}

// This routine loops forever 
void loop() 
{
  digitalWrite(led, !digitalRead(led));   // Toggle led
  delay(5000);              
}

This doesn’t seem to work. The led never turns on. What is the issue here?

Hi @greatwitenorth,

Happy to help, try this:

int state = 0;
void setup() {
    pinMode(D7, OUTPUT);
}
void loop() {
    digitalWrite(D7, (state) ? HIGH : LOW);
    state = !state;
    delay(100);
}

And an alternate version based on Dave’s code without delays, so you can make longer delays without dropping the connection to the cloud:

unsigned long lastPass = 0;
int state = 0;
void setup() {
    pinMode(D7, OUTPUT);
}
void loop() {
    if (millis() > lastPass) {
      digitalWrite(D7, (state) ? HIGH : LOW);
      state = !state;
      lastPass = millis() + 5000UL;
    }
}
1 Like

oh that’s a good point. I actually didn’t need the delay in there. I forgot to take it out. But I do like your solution.

AND, you could include the ellapsedMillis library to do it this way:

elapsedMillis  lastPass;

int state = 0;
void setup() {
    pinMode(D7, OUTPUT);
}
void loop() {
    if (lastpass >= 5000L) {
      digitalWrite(D7, (state) ? HIGH : LOW);
      state = !state;
      lastPass = 0;
    }
}

:smile:

2 Likes

I wonder, can we keep this going? How many ways can we blink the LED?

Edit: this may seem silly, but I’m genuinely kind of excited about this…

Here’s another that just counts up:

int state = 0;
int counter = 0;
int someNumLoops = 1000;

void setup() {
    pinMode(D7, OUTPUT);
}

void loop() {
    counter++;
    if ((counter % someNumLoops) == 0) {
        toggle();
    }
}

void toggle() {
    digitalWrite(D7, (state) ? HIGH : LOW);
    state = !state;
}

I was totally serious, here’s a version that syncs the clock with an NTP server, and then blinks on 5 second intervals (code from this thread! https://community.spark.io/t/getting-utc-time-from-ntp-server/1213/3 - Thanks! )

UDP UDP;

char string[ 17 ] = { "" };

int hour, minute, second;

unsigned int localPort = 123;
unsigned int timeZone = -6;

unsigned int serverNum = 0;
unsigned long timeout;

const char timeServer[] = "pool.ntp.org";
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
int synced = 0;
int state = 0;
unsigned int offset = 0;
unsigned long secsSince1900 = 0;



void setup()
{
	UDP.begin(localPort);
	Serial.begin(9600);
	Serial.println("NTP-clock");
	pinMode(D7, OUTPUT);
}

void loop()
{
    if (!synced) {
        Serial.println("Syncing...");
        syncTime();
        synced = 1;
    }
    receiveTimeTick();
    displayTime();
    
    if ((second % 5) == 0) {
        //toggle every 5 seconds, synced with NTP.
        toggle();
    }
    
    delay(1000);
}

void toggle() {
    digitalWrite(D7, (state) ? HIGH : LOW);
    state = !state;
}




void displayTime() {
    if (!synced) {
        return;
    }
    
    // now convert NTP time into everyday time:
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;    
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    
    //add elapsed seconds.
    epoch += ((millis() - offset) / 1000.0);

    hour = (epoch % 86400L) / 3600;         
    minute = (epoch % 3600) / 60;
    second = (epoch % 60);

    Serial.print (hour);
    Serial.print (":");
    Serial.print (minute);
    Serial.print (":");
    Serial.println (second);
}

void syncTime() {
    sendNTPpacket(timeServer);  // send an NTP packet to a time server
	// wait to see if a reply is available
}

void receiveTimeTick() {
    if (synced) {
        return;
    }
    
    if ( UDP.parsePacket() ) {
    	UDP.read(packetBuffer, NTP_PACKET_SIZE);  // read the packet into the buffer

	    //the timestamp starts at byte 40 of the received packet and is four bytes,
	    // or two words, long. First, esxtract the two words:

	    unsigned long highWord = (packetBuffer[40] << 8) + packetBuffer[41];
	    unsigned long lowWord = (packetBuffer[42] << 8) + packetBuffer[43];
	    // combine the four bytes (two words) into a long integer
	    // this is NTP time (seconds since Jan 1 1900):
        secsSince1900 = highWord << 16 | lowWord;
	    secsSince1900 += timeZone*60*60;
	    
	    offset = millis();
	    synced = 1;
    }

	while ( UDP.parsePacket() ) {               // clean-up buffer
		UDP.read(packetBuffer, NTP_PACKET_SIZE);  // read the packet into the buffer
	}
}


// send an NTP request to the time server at the given address
unsigned long sendNTPpacket(const char *address)
{
	// set all bytes in the buffer to 0
	memset(packetBuffer, 0, NTP_PACKET_SIZE);
	// Initialize values needed to form NTP request
	// (see URL above for details on the packets)
	packetBuffer[0] = 0b11100011;   // LI, Version, Mode
	packetBuffer[1] = 0;     // Stratum, or type of clock
	packetBuffer[2] = 6;     // Polling Interval
	packetBuffer[3] = 0xEC;  // Peer Clock Precision
	// 8 bytes of zero for Root Delay & Root Dispersion
	packetBuffer[12]  = 49;
	packetBuffer[13]  = 0x4E;
	packetBuffer[14]  = 49;
	packetBuffer[15]  = 52;

	// all NTP fields have been given values, now
	// you can send a packet requesting a timestamp:
	UDP.beginPacket(address, 123);
	UDP.write(packetBuffer, NTP_PACKET_SIZE); //NTP requests are to port 123
	UDP.endPacket();
}
1 Like

Oh ya… well is is the ultimate:

char state[] = "I state that I will flip the switch every second";

void setup() {
  Serial.begin(9600);
  Serial.println(state);
  Serial.println("Ready??");
  Serial.println("ok, flip the switch to turn ON the LED and wait about one second");
  Serial.println("Then, flip the switch to turn OFF the LED, wait another second and start over");
}

void loop() {
// Look no loop needed!!
}

Geesh! :smile:

1 Like

You know I can’t resist a good challenge!

/*
 * =================================
 * RUBE GOLDBERG LED TOGGLE
 * ---------------------------------
 * BDub / Technobly - Feb 11th, 2014
 * =================================
 *
 */
 
uint16_t TIM_ARR = (uint16_t)(65535/6); // Calc PWM period.

void setup() {
  pinMode(D1, INPUT); // sets D1 as an input
  pinMode(D0, OUTPUT); // sets D0 as an output
  pinMode(D7, OUTPUT); // sets D7 as an output
  attachInterrupt(D1, updateD7, CHANGE); // call updateD7() everytime D1's input changes
  analogWrite2(D0, 128); // Set D0 output as a 0.1Hz 50% duty cycle PWM (5s on, 5s off)
}

void loop() {
  // Jumper D0 to D1 to control D7 for 5 seconds on, and 5 seconds off
  // in the most convolutedly awexome way I could think of, for now ;)
  
  // look Ma, no hands!
}

void updateD7() {
  digitalWrite(D7,digitalRead(D1)); // translate PWM to LED output
}

// User defined analogWrite() to gain control of PWM initialization
void analogWrite2(uint16_t pin, uint8_t value) {
  TIM_OCInitTypeDef TIM_OCInitStructure;

  if (pin >= TOTAL_PINS || PIN_MAP[pin].timer_peripheral == NULL) {
    return;
  }
  // SPI safety check
  if (SPI.isEnabled() == true && (pin == SCK || pin == MOSI || pin == MISO)) {
    return;
  }
  // I2C safety check
  if (Wire.isEnabled() == true && (pin == SCL || pin == SDA)) {
    return;
  }
  // Serial1 safety check
  if (Serial1.isEnabled() == true && (pin == RX || pin == TX)) {
    return;
  }
  if (PIN_MAP[pin].pin_mode != OUTPUT && PIN_MAP[pin].pin_mode != AF_OUTPUT_PUSHPULL) {
    return;
  }
  // Don't re-init PWM and cause a glitch if already setup, just update duty cycle and return.
  if (PIN_MAP[pin].pin_mode == AF_OUTPUT_PUSHPULL) {
    TIM_OCInitStructure.TIM_Pulse = (uint16_t)(value * (TIM_ARR + 1) / 255);
    if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
      PIN_MAP[pin].timer_peripheral-> CCR1 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
      PIN_MAP[pin].timer_peripheral-> CCR2 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
      PIN_MAP[pin].timer_peripheral-> CCR3 = TIM_OCInitStructure.TIM_Pulse;
    } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
      PIN_MAP[pin].timer_peripheral-> CCR4 = TIM_OCInitStructure.TIM_Pulse;
    }
    return;
  }

  TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

  //PWM Frequency : PWM_FREQ (Hz)
  uint16_t TIM_Prescaler = (uint16_t)65535; // largest prescaler!

  // TIM Channel Duty Cycle(%) = (TIM_CCR / TIM_ARR + 1) * 100
  uint16_t TIM_CCR = (uint16_t)(value * (TIM_ARR + 1) / 255);

  // AFIO clock enable
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

  pinMode(pin, AF_OUTPUT_PUSHPULL);

  // TIM clock enable
  if (PIN_MAP[pin].timer_peripheral == TIM2)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM3)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
  else if (PIN_MAP[pin].timer_peripheral == TIM4)
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);

  // Time base configuration
  TIM_TimeBaseStructure.TIM_Period = TIM_ARR;
  TIM_TimeBaseStructure.TIM_Prescaler = TIM_Prescaler;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;

  TIM_TimeBaseInit(PIN_MAP[pin].timer_peripheral, & TIM_TimeBaseStructure);

  // PWM1 Mode configuration
  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
  TIM_OCInitStructure.TIM_Pulse = TIM_CCR;

  if (PIN_MAP[pin].timer_ch == TIM_Channel_1) {
    // PWM1 Mode configuration: Channel1
    TIM_OC1Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC1PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_2) {
    // PWM1 Mode configuration: Channel2
    TIM_OC2Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC2PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_3) {
    // PWM1 Mode configuration: Channel3
    TIM_OC3Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC3PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  } else if (PIN_MAP[pin].timer_ch == TIM_Channel_4) {
    // PWM1 Mode configuration: Channel4
    TIM_OC4Init(PIN_MAP[pin].timer_peripheral, & TIM_OCInitStructure);
    TIM_OC4PreloadConfig(PIN_MAP[pin].timer_peripheral, TIM_OCPreload_Enable);
  }

  TIM_ARRPreloadConfig(PIN_MAP[pin].timer_peripheral, ENABLE);

  // TIM enable counter
  TIM_Cmd(PIN_MAP[pin].timer_peripheral, ENABLE);
}

https://gist.github.com/technobly/8950366 (btw I would have just pasted the Gist link, but it won’t display code anymore from there)

2 Likes

I’m loving these answers! I’m wondering if someone can tell me why my first example didn’t seem to work? Can you not do a digitalRead on a pin that’s been set as an OUTPUT? I heard this was an issue with the Arduino Due but previous versions allowed you to read an OUTPUT pin. Is that the case here?

Yes! Thank you @BDub :smiley:

1 Like

Hi @greatwitenorth,

Sure thing! Essentially reading / writing to a pin changes its mode (please correct me someone if I’m wrong here), so you can’t simultaneously read the value and write a value to the same pin at the same time. You could however write one pin high, and read from another pin, and connect the two together directly. I seem to recall someone posting a low-level explanation for this, but I’m having trouble tracking that post down (if someone else has it handy that’s cool) :).

Thanks!
David

There has been some change in the Core’s behaviour.

Now you can digitalRead() an OUTPUT pin and this will return the content of the output latch

if(PIN_MAP[pin].pin_mode == OUTPUT)
{
	return GPIO_ReadOutputDataBit(PIN_MAP[pin].gpio_peripheral, PIN_MAP[pin].gpio_pin);
} 
2 Likes

@ScruffR, Correct! digitalRead() should now return valid data bit for Output pins as well.

I think this is what I’m looking for, so now How Can I read the currently status of a led from the terminal?

In order to see the new Core’s behaviour, do I need to update something? sorry for this dumb question, I’m really noob on this.

Thanks

Oscar

There are at least three answers to this, depending on your use case.

If you just want to know what the state of a LED directly driven by the Core should be, you just write sonething like

#define LEDPIN D5
int ledState;

void setup()
{
  pinMode(LEDPIN, OUTPUT);
}

void loop()
{
  ledState = digitalRead(LEDPIN);
}

void changeState()
{
  // do something to LEDPIN
}

On the other hand, if you actually want to measure what the electrical state of a LED is, that is not directly or solely driven be a dedicated LEDPIN, then you need to setup a dedicated pin in INPUT mode and perform a digitalRead() on that pin measuring the state via a suitable circuitry.

And thirdly if you have a PWM driven LED and you want to know its “illumination level” things get even more complicated :wink:

1 Like

Thanks a lot for your answers, the only thing that I need is to know if the status of the Led is HIGH or LOW, so your first answer works for me!

Thanks again

2 Likes

@satishgn in order to get the new version of the digitalRead() function, Do I need update something?
sorry about this dumb question.

You just need to write some code and flash it from Spark Build or Spark Dev which currently will build with firmware that allows you to perform a digitalRead() on an OUTPUT. Like this LED toggler code:

void setup() {
    pinMode(D7, OUTPUT);
    digitalWrite(D7, LOW);
}

void loop() {
    digitalWrite(D7, !digitalRead(D7));
    delay(100);
}

:sunflower:

2 Likes