body:
I'm very new to the Arduino/Microcontroller-world, so please be patient :)

I have 4 potentiometers and I want my LED to blink up, when one of these is beeing used.[![enter image description here][1]][1]

So far., so good.. the potentiometers are sending singnals to my inputs A0-A3. In the code I read and buffer the values of send to the inputs, so when a new value is recieved (potentiometer is beeing used), the funcion `blinkLED()` is beeing triggered:

    int ledPin = 13;

    int pin[] =    {A0, A1, A2, A3};
    int cc[] =     {20, 21, 22, 23};
    int potiValues[] =   {0,  0, 0, 0};
    int potiValuesTmp[] = {0, 0, 0, 0};

    void setup() {
      Serial.begin(9600);
     pinMode(ledPin, OUTPUT);
    }

    void loop() {
       // READ EVERY PIN
       for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
           if(potiValues[i] != potiValuesTmp[i]) {
            // NEW VALUE RECIEVED - MAKE OUTPUT
                Serial.println("Pin ");
               Serial.print(pin[i]);
               Serial.print(" - ");
               Serial.print("Value: ");
               Serial.print(potiValues[i]);
               blinkLED();
            }
           potiValuesTmp[i] = potiValues[i];
       }
    }

    void blinkLED() {
       digitalWrite(ledPin, HIGH);
        delay(1000);
        digitalWrite(ledPin, LOW);
    }

It somehow works on the emulator `circuits.io`, but I'm not sure if I did it right(?) Maybe someone could have a look and tell me, what to improve?

**But my main question is:**
When the function `blinkLED()` is triggered, there is this delay,.. does the whole `loop()`-function wait, too?

  [1]: https://i.stack.imgur.com/rYE1J.jpg

title: Arduino - Turn on LED when Potentionmeter is used

Answers: 2

body:
Yes, the main loop (aka void loop) will have to wait during the delay. One method of escaping that problem is to use the `millis()` function. There is an example code called "blinkWithOutDelay" (or something like that). It pretty much uses the ATmega's internal timer. This method is more for advanced users. The `millis()` functions is will return you the number of milliseconds since the start of your program.

Also, potentiometers are always in use. They will report back data everytime. Its not like if it had too fixed states like ON or OFF. So the problem is that they are all in used at the same time. You might consider changing the values of `potiValuesTmp`. My varying that variable, you can make it so that at least one potentiometer has to be higher then a certain point.

body:
> When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Yes, when you call a function it doesn't return until it is done, and `delay` is blocking.

You can rewrite a bit like this:

    int ledPin = 13;

    int pin[] =             {A0, A1, A2, A3};
    int cc[] =              {20, 21, 22, 23};
    int potiValues[] =      {0,  0, 0, 0};
    int potiValuesTmp[] =   {0, 0, 0, 0};

    void setup() {
        Serial.begin(9600);
        pinMode(ledPin, OUTPUT);
    }

    unsigned long lastFlash;
    int flashesToGo;
    const unsigned long flashTime = 50; // ms

    void loop() {
        // READ EVERY PIN
        for(int i=0; i<=3; i++){
            potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
            if(abs (potiValues[i] - potiValuesTmp[i]) > 3) {
                // NEW VALUE RECEIVED - MAKE OUTPUT
                Serial.print("Pin ");
                Serial.print(pin[i]);
                Serial.print(" - ");
                Serial.print("Value: ");
                Serial.println(potiValues[i]);
                flashesToGo = 10;
                potiValuesTmp[i] = potiValues[i];
            }
        }

       // flash LED if required

       if (flashesToGo > 0)   // need more flashing?
          {
          // is it time to toggle the LED?
          if (millis () - lastFlash >= flashTime)
            {
            // toggle LED
            if (digitalRead (ledPin) == HIGH)
              digitalWrite (ledPin, LOW);
            else
              digitalWrite (ledPin, HIGH);
            // remember when we did it
            lastFlash = millis ();
            // count down
            flashesToGo--;  // one less flash
            } // end of time for another flash
          }
       else
         digitalWrite (ledPin, LOW);  // ensure LED off

    }

What this does is add to the main loop a few lines of code that toggle the LED after a certain time is up (50 ms currently). It counts down the number of toggles from a desired starting point (eg. 10) until they are all done. This means that the LED will flash without blocking.

Each time you detect a new analog reading the number of flashes is reset back to the maximum.

---

I modified your test for if the analog reading changed to be:

    if(abs (potiValues[i] - potiValuesTmp[i]) > 3)

I found that without that, the LED flashed continually because the readings were slightly different each time (eg. 51, 52, 51, 50) which would probably just be error in the ADC reading.

With that change, it doesn't count as "changed" unless the reading changes by 3 (you could make it more, or less than that).

---

> I want the LED to blink up just once - when I turn one of the potentiometers

In that case change:

    flashesToGo = 10;

to:

    flashesToGo = 2;

That is one HIGH and one LOW (one flash in total).


body:
This is a follow up to [my previous question](https://arduino.stackexchange.com/questions/30326/can-a-timer-be-used-in-both-ctc-and-fast-pwm-mode-simultaneously).

I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).

The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.

I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.

In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.

I have the following minimal(-ish) example:

    #define OCIEA 1
    #define CA21 1

    void setup() {
      // PD3 as output
      DDRD |= (1 << PD3);

      // Pause the timers so they sync up
      GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

      // Reset timer
      TCNT2 = 0; // set timer2 to 0 (8-bit timer)

      // Enable CTC mode
      TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

      // Clear output pins on compare match
      TCCR2A |= (1 << COM2B1); // Clear OC2B on match

      // Set prescaler
      TCCR2B = (1 << CA21); // set timer 2 divisor to 8

      // Set output compare
      OCR2A = 150; // Determines TOP for Timer2

      // Determines the pulse width
      OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

      // Enable interrupts for timer 2
      TIMSK2 = (1 << OCIEA);

      // Set the timers going again
      GTCCR = 0; // release all timers
    }

    ISR(TIMER2_COMPA_vect)
    {
      TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
      DDRD |= (1 << PD3); // Enable output
      PORTD |= (1 << PD3); // Output high
      TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
    }

    void loop() {

    }

Ideally the ISR would just consist of `PORTD |= (1 << PD3);` but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.

Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).

Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?

I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

title: Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode

Answers: 1

body:
The PWM modes manage pin at both ends of the cycle.

The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.

To manage both ends explicitly, you use normal mode.

To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:

    ISR(TIMER2_COMPA_vect)
    {
      TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
      TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
      TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
    }


body:
I am using a two Arduino setup with two XBee radios. One radio is sending data and the other is receiving data. I am sending three sensor readings following a protocol which uses three bytes for each sensor reading. Byte one is sensor information, byte two is data, and byte three is for error checking. When I run the set up for about 5 minutes I get approximately 47% errors in transmission. Once one error occurs, there seems to be an avalanche of errors. However, when I add delay in between sending bytes (100ms between bytes and 1s between sensor) it works perfectly. I've tried expanding the hardware buffer, but this didn't work.

            delay(2000);

            // Calcuate weather parameters for serial and web
            calcWeather(); // Go calc all the various sensors

            // send weather out to serial port
            if (prevtemplm34_1 == templm34_1) // 2 in a row must be the same to send
            {
                Serial.write(0);
                Serial.write(templm34_1);
                Serial.write(templm34_1 ^ 0);
            }

            // send weather out to serial port
            if(prevtemplm34_2 == templm34_2) // 2 in a row must be the same to send
            {
                Serial.write(1);
                Serial.write(templm34_2);
                Serial.write(templm34_2 ^ 1);
            }

            // send weather out to serial port
            if(prevtemplm34_3 == templm34_3) // 2 in a row must be the same to send
            {
                Serial.write(2);
                Serial.write(templm34_3);
                Serial.write(templm34_3 ^ 2);
            }
            delay(2000);

The code for parsing received data is:

    int readData ()
    {
    // There must be at least three available bytes to satisfy the protocol
    // Otherwise, wait until three bytes have arrived to read anything
    if (Serial.available() >= 3) {

          // Read the next three byte in the serial buffer
          incomingByteOne = Serial.read();
          Serial.write("Byte One: ");
          Serial.write(incomingByteOne);
          Serial.println();
          incomingByteTwo = Serial.read();
          Serial.write("Byte Two: ");
          Serial.write(incomingByteTwo);
          Serial.println();
          incomingByteThree = Serial.read();
          Serial.write("Byte Three: ");
          Serial.write(incomingByteThree);
          Serial.println();

          // XOR the first and second incoming bytes so that the result can be checked against the third error checking byte
          byte xorValue = incomingByteOne ^ incomingByteTwo;
          Serial.write("XOR VALUE: ");
          Serial.write(xorValue);
          Serial.println("Number of Errors: ");
          Serial.println(numberOfErrors);
          Serial.println();
          Serial.println();
          if(xorValue != incomingByteThree) {
            numberOfErrors++; // Add one to the total count of number of errors in transmission
          }
          else {
            // Mask for retrieving the five rightmost bits from incomingByteOne (00011111)
            byte maskForSensorNumber = 0x1f;

            // Shift incomingByteOne right 5 times in order to obtain the three bits representing the unit number
            int unitNumber = incomingByteOne >> 5;

            // AND incomingByteOne with the mask in order to retrieve only the five righmost bits representing the sensor number
            int sensorNumber = incomingByteOne & maskForSensorNumber;

            // Store the data for the correct sensor on the correct unit
            data[unitNumber][sensorNumber] = incomingByteTwo*1;
         }
    }
    }

What could be causing the transmissions to work fine with delay, but not otherwise?

title: High errors in transmission (completely eliminated by adding delay): What's the issue?

Answers: 1

body:
You are probably just transmitting too fast.

Your receiver is writing at least 80 bytes of debugging information (if
I counted it right) for every 3 bytes of incoming data. Since both input
and debug output happen at the same baud rate, this means the receiver
can only cope with an input data rate equal to 3/80 = 3.75% of
the nominal baud rate.

I would expect no errors at the very beginning of the program run,
because the debugging info is written to a RAM buffer. Only when that
buffer fills up the receiver is slowed down by every `Serial.write()`
and `Serial.println()` it performs.


body:
This is the idea. I have 2 Arduinos. One with an IR LED and the other with an IR receiver. I want to read the values of multiple sensors and transmit it to the other Arduino via IR. I know how to send data like a fixed HEX code but I dont know how to send values from a potentiometer.

Just think of how a quadcopter sends and receives data from the joysticks, thats somewhat what I want to do.

**[EDIT]**

This is a precision of what I want to do. I'll read the values of let's say 2 potentiometers, map the values from 0-99, and then I want to send it to the other Arduino **with IR and not anything else.**

title: Sending Analog Data with and IR LED

Answers: 1

body:
Seems to me you first need to establish a protocol.  Could just be a simple one you make up,  with it you will eventually find that repetition and retransmission will need to be explored, and you may want to include things such as a CRC if the application suits it; or not...

As part of the thought process you need to look at your sensors, see how they put out their data, you seem to indicate analog, so that would be read on an a to d converter and that d value might be directly sent as the data part of your chosen protocol.

Or some joysticks packages might have have a I2C or SPI driver built in to which the A to D wouldn't be required.

But using IR you will find timing and validation very important so that the receiver knows where the beginning and end of data is at.

Thinking about it there must some libraries out there already.
Or entirely completed projects to study.

Now you didn't ask but if reliable communication is desired you might want to go wired serial or use a managed protocol like an Ethernet peripheral.


body:
I'm new Arduino user and I'm trying out a SPI protocol to interface a SRAM, specifically, the 23LCV512.

I have found the instructables steps to interface a SRAM using the SPI bus on an Arduino UNO very helpful (http://www.instructables.com/id/Interface-an-SRAM-bus-to-your-arduino/), but there is one  point that i would like some explanation for:

In the mem_demo.ino and other various SPI.h code, I have seen variations of the following, however I do not understand why you would have to do this? I think here that we are communicating the right shifting of an input address 16 places along with 8 bits of '1'.

    SPI.transfer((uint8_t)(address >> 16) & 0xff);
    SPI.transfer((uint8_t)(address >> 8) & 0xff);
    SPI.transfer((uint8_t)address);

Commenting these lines out for the write did not effect the writing to the SRAM, but reading caused it to return mostly 0's.

I really appreciate any help iIget, I do not have a lot of experience with memory addresses and electronics, thank you.

title: Explanantion of Addressing

Answers: 1

body:
It is actually slightly confusing owing to the (actually redundant) `& 0xff` in there.

What is happening is first the address is right-shifted so as to place the byte of interest at that moment in the lowest 8-bits (`address >> 16` for instance to get bits 16-23 moved to bits 0-7) and then the lowest 8 bits are masked off by ANDing them with 0b11111111 (0xFF). This removes any bits that are above the 8 bits we are interested in - however the fact that it's cast to `uint8_t` and also passed to a function that expects `uint8_t` makes that masking redundant. Any bits above the first 8 are discarded anyway.

So to take an example address of, say, 100,000 (which is 0x186A0 in hex) and run those three commands on it, we end up with:

    SPI.transfer((uint8_t)(address >> 16) & 0xff);

    0x186A0 >> 16 = 0x00001
    0x00001 & 0xFF = 0x01

    SPI.transfer((uint8_t)(address >> 8) & 0xff);

    0x186A0 >> 8 = 0x00186
    0x00186 & 0xFF = 0x86

    SPI.transfer((uint8_t)address);

    (uint8_t)0x186A0 = 0xA0

The end result as you can see is three SPI transfers each sending a single byte:

    0x01, 0x86, 0xA0

And that corresponds to the protocol for that chip, which is basically:

    <Command>, <Address H>, <Address M>, <Address L>, <Data>...

For instance:

    0x02, 0x01, 0x86, 0xA0, 0x69

You send the "WRITE" command, send the three bytes of the address you want to write to, then follow that with the data to write. Or you send the READ command, send the three bytes of the address you want to read from, then the data is returned to you a byte at a time.


body:
I am trying to use an sprintf with an IPAddress and I am not sure why Serial.print() is able to convert IPAddress to a reasonable human readable representation. I mean, presumably it uses an overloaded function that detects what type the parameter is. I want to somehow leverage that functionality ina printf or sprintf.

What I know:

    IPAddress ip = WiFi.localIP();
    Serial.println(ip);

works great and outputs "192.168.4.1".

    char *buf = malloc(128);
    sprintf(buf,"%s",String(ip).c_str());

generates buf as "17082560" which isn't wrong, but its not the usual format for an IP address.

I could write a function to output it the way I want, but I figured there must be some relatively simple way to utilize the functionality that Serial.print() provides but somehow channel it to an sprintf() call. Or any other simple way to provide a formatted IP output would be appreciated.

title: formatting of IPAddress via printf(...) family similar to Serial Object

Answers: 3

body:
In short: `hex(17082560) = 0x0104A8C0` where: `0x01 = 1`, `0x04 = 4`, `0xA8 = 168` and `0xC0 = 192`. See the pattern? It's printed as a single `uint32_t`.

Of course endianness is reversed as platform is little endian but IP Adresses are in network byte order (big endian)

And because you didn't understand this answer, there is also whole code:

    uint32_t ip = (uint32_t) WiFi.localIP();
    sprintf(buf, "%u.%u.%u.%u", ip & 0xFF, (ip>>8) & 0xFF, (ip>>16) & 0xFF, (ip>>24) & 0xFF);

Maybe even better:

    IPAddress ip = WiFi.localIP();
    sprintf(buf, "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);

body:
Whereas KIIV's answer solves your problem, it does not address some very
interesting parts of your original question:

> I am not sure why Serial.print() is able to convert IPAddress to a
> reasonable human readable representation

This works thanks to a couple of abstract classes in the Arduino library
called `Print` and `Printable`. A Print object is anything that can
output text, like a serial port, a network connection or an LCD. A
Printable object is anything that can be converted to a text
representation and sent through a Print object.

From Print.h:

<!-- language-all: lang-c++ -->

    class Print
    {
        // ...
        virtual size_t write(uint8_t) = 0;
        // ...
        size_t print(const String &);
        size_t print(const char[]);
        size_t print(unsigned int, int = DEC);
        size_t print(const Printable&);
        // ...
        size_t println(const String &s);
        // ...
    };

In other words, in order to create a Print, you only have to implement
`write(uint8_t)`, which should output a single character. Then you get
all the `print()` and `println()` methods.

From Printable.h:

    class Printable
    {
      public:
        virtual size_t printTo(Print& p) const = 0;
    };

This means you can make any object Printable by implementing
`printTo(Print&)`.

From IPAddress.h:

    class IPAddress : public Printable {
        // ...
    };

This means IPAddress objects are Printable: they know how to print
themselves into any Print. You can find the implementation of
`IPAddress::printTo(Print&)` [at the end of
IPAddress.cpp](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/IPAddress.cpp#L105).

Thus, to answer your question, `Serial.print()` does not really know how
to create a textual representation of the IPAddress, but IPAddress knows
how to send itself through `Serial`, or any other Print object.

> I want to somehow leverage that functionality [...] there must be some
> relatively simple way to utilize the functionality that Serial.print()
> provides but somehow channel it to an sprintf() call.

The functionality is not provided by `Serial.print()`: it's the fact
that the IPAddress is Printable. In order to leverage that, you have to
create a Print object. You cannot use `sprintf()` for that, but you can
create a Print object which behaves like `sprintf()` and writes into a C
string:

    // Write into a C string (a char array), a la sprintf().
    // Warning: there is no check for buffer overflow.
    class StringPrinter : public Print
    {
    public:
        StringPrinter(char *buffer) : buf(buffer), pos(0) {}
        virtual size_t write(uint8_t c)
        {
            buf[pos++] = c;  // add the character to the string
            buf[pos] = 0;    // null perminator
            return 1;        // one character written
        }
    private:
        char *buf;
        size_t pos;
    };

which could be used like this:

    char buf[16];
    StringPrinter(buf).print(ip);

For the sake of simplicity, I would generally prefer the straight
`sprintf()` solution. However, if you are short on flash, the code above
is likely to be smaller, as `sprintf()` is large and you are very likely
to be already using `Print` in your program.

body:
There is also a one-line solution just as you wish. Instead of `String(ip)` use `ip.toString()`.

    IPAddress ip = WiFi.localIP();
    char *buf = malloc(128);
    sprintf(buf, "%s", ip.toString().c_str());

Background: The function `Serial.println(ip);` calls `Print::print(const Printable& x)`, which in turn calls `IPAddress::printTo(Print& p)`.

    size_t Print::print(const Printable& x) {
        return x.printTo(*this);
    }

Alternatively, `String IPAddress::toString()` creates the desired string and reserves just the needed amount of memory (code from ESP8266 2.7.4)

    String IPAddress::toString() const
    {
        StreamString sstr;
    #if LWIP_IPV6
        if (isV6())
            sstr.reserve(40); // 8 shorts x 4 chars each + 7 colons + nullterm
        else
    #endif
            sstr.reserve(16); // 4 bytes with 3 chars max + 3 dots + nullterm, or '(IP unset)'
        printTo(sstr);
        return sstr;
    }


body:
I have a very simple sketch, something like this:

    int aFour = 4;
    softwareSerial.print(4,BIN);
    softwareSerial.print(aFour,BIN);

Which gives the following output:

    1001
    0011

Why don't they print both as `0100`?

EDIT: the output was in one line : `10010011`, I falsely asumed the output should be split into twice 4 bits.

title: Strange binary number representation

Answers: 1

body:
* `print` never prints leading zeroes (how many *should* it print anyway?).
* `print` doesn't start a new line - you need `println` for that

So you get your `4` in binary printed twice followed by something else (not sure what - maybe something else in your program that you're not showing us?): `10010011`

That's `100 100 11` when split up.


body:
I have this arduino motor shield, and I want to connect a Bluetooth module, but don't know how (the tx and rx pins are used by the plate). Tried to sold it but now I don't have the tin to do it. So I want to know if I can use this holes (don't know their names) "the ones encircled in red" to connect the Bluetooth module. Thank you folks.

[![I took and edited it with my phone][1]][1]

  [1]: https://i.stack.imgur.com/Rc2TJ.jpg

title: Arduino shield bluetooth

Answers: 1

body:
You are looking at the wrong place. Tx and Rx are at the bottom of you picture (new picture at the bottom to help you). What you need to do is to get a jumper, heat up the Rx pin and put the jumper in the molten solder. That is not the ideal choice but because you don't have enough solder, thats the way to go. To the same to the Tx pin, GND, and VCC.

A more permanent and clean way of doing this will require extra solder (which you dont have at the moment) and some ["shield headers" (aka stackable headers)][1]. This will let you connect the shield to your Arduino while still leaving you with all of your female headers.

[![enter image description here][2]][2]

  [1]: https://www.sparkfun.com/products/10007
  [2]: https://i.stack.imgur.com/1K31z.jpg


body:
I am controlling a solar tracker, and it needs to be reset every 10 minutes or it loses its mind.  My program works fine, controlling power relays, so I have added I2C&Power to be able to see the status remotely.  For now it is set up on the workbench with fairly short cables.  I also have a RTC and the i2cscanner finds them all..

LCD init code is pretty basic:

    // 20 x 4  LCD Display
    #include LiquidCrystal_I2C.h
    // set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
    //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
    LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

then

    lcd.begin(20,4);
    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("PV Control 3.9");

My LCD (20x4) works fine at first, writing the top line with the name of the program, then the bottom line with a temperature reading, then every 10 minutes I need the second line to show when the power is off for 10 seconds.  It shows "power off" just fine, but after the delay(10000) it is supposed to overwrite that line with  "power on" but nothing changes...

    Serial.println("POWER OFF");
    lcd.setCursor(4,1);
    lcd.print("-Power Off- ");
    digitalWrite(power1,HIGH);  // DC HOUSE power off
    digitalWrite(power2,HIGH);  // DC HOUSE power off
    delay(10000);
    Serial.println("POWER ON");
    lcd.setCursor(4,1);
    lcd.print("-Power On-  ");
    digitalWrite(power1,LOW);  // DC HOUSE power on
    digitalWrite(power2,LOW);  // DC HOUSE power on

The problem is that it continues to say "power off" and doesn't overwrite it.

I can see from the Serial Monitor that the program is running fine, but the LCD doesn't change after the first set of lcd.prints at those character positions.

I haven't heard of anybody having this problem, but perhaps someone out there know about this.   Any suggestions would be very welcome.

Question is:  How can I make the LCD update lines that have been originally written?

-------------------
UPDATE:  Problem solved by simply clearing and rewriting the display when things change.  I can't debug libraries but at least it is working now.

title: 20x4 LCD will write but then won't update

Answers: 1

body:
Ah ha.   I solved it by using lcd.clear() and simply repainting the entire display with every change.  I have much simpler LCD programs that don't require doing this, but it worked in this instance.

Same code as above, but with this before each power notification:

    lcd.clear();
    lcd.setCursor(2,0);
    lcd.print("PV Control 3.9");

  etc...

------------------
UPDATE:
  Now that I have two 20x4 LCD screens showing readings from two separate Arduinos (PV Controls and Weather station) I have discovered that it is very important to keep the screen writes to a minimum.  No time delays in between writing parts of the screen, for instance (like when I had Serial.print statements in there for debugging), doing all the readings and calculations before writing the screen, and timing the screen updates to be infrequent, like on the order of 65 seconds for weather and 10 minutes for the PV.  I2C does not have collision detection so it is important to try to prevent the two screens from being updated at the same time.  The I2C&Power arrangement is working great.  One source of power is all it takes to activate the entire network.


body:
My little weather station is run on a Nano and has the anemometer and the temp/humidity sensor.  A smoke detector is on the way because I live where wildfire is a big concern.

I would like to build a simple weather vane without spending a lot to buy the commercial solutions.  Rotary potentiometers have dead spots and using a bunch of hall effect sensors would use up too many digital inputs to be useful, afaik.

Question:  How can I build a simple direction sensor?

title: Arduino weather vane

Answers: 3

body:
Its a long time since I looked at this and the details are a bit misty, so sorry for the inaccuracies, but I'm sure people will correct them for me :)

I originally brought one of these http://www.maplin.co.uk/p/maplin-replacement-wind-direction-sensor-for-n96fyn96gy-n81nf and then decided to take it to bits, like you do.

The vane spins a magnet around and this triggers 1 of 8 reed switches as it passes around.  The read switch is connected to VCC and a resistor and the resistors feed into a common wire back to the microprocessor.  The 8 resistors all have different values, so the result is a differing output voltage depending on which reed switch has been triggered.

So what you need is:

 - A magnet
 - A number of read switches positioned far enough apart so only one is triggered at a time
 - A number of different resistors

Supply 5V from you Nano and read the result on an analogue pin, then come up with a calibration table to work out the direction.

I hope that makes sense.
(Sorry I can't draw you a circuit diagram)

body:
Another option (similar to reed switches) is to do it optically.

The vane is on an axle. The axle has a disc attached to it. The disc has a small notch out of the edge.

Positioned around the edge are a whole series of photo-interrupters. The disc spins between the infra-red beams and the notch allows only one of them to pass light at a time.

Make the notch the right size so that as one interrupter turns off the next one turns on - you need one on all the time. You could over-compensate slightly so that on occasion two adjacent interrupters are on at once, in which case you can say it's between the two.

A similar system is to use a disc with a series of special slots cut in it (see [Gray Code](https://en.wikipedia.org/wiki/Gray_code)) which allow light to pass through onto a line of photodiodes. In different rotations different combinations of photodiodes are on, and that gives you your direction.

body:
I decided to go with 4 reed sensors.  With experimentation I found I can successfully detect 8 distinct directions using 4 reed switches since the rare-earth magnet will switch two on at once when it is in between.

Thank you all for your answers.  Upvotes for everyone for the discussion.


body:
I have a [TIP 120 to 229 NON 60V 5A transistor][1]

I'm trying to use it to switch an electro magnet. Using the blink example to test it out:

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(13, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(500);              // wait for a second
    }

pin 13 is connected to the base and I'm trying to powering the magnet with a 12V DC adapter. I'm not sure if the transistor is before or after the magnet, but I'm not sure how that would make a difference.

I'm not great with diagrams but something like this (the power source might be the other way around:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/v2xO8.png)

<!-- End schematic -->

I've tried switching between the collector and the emitter. In one instance the magnet is always active and in one instance it's always passive. What could be wrong?

The cords running of the table in the bottom is just a bit of extra wiring.
[![enter image description here][3]][3]
[![enter image description here][2]][2]

  [1]: https://cdn-shop.adafruit.com/datasheets/TIP120.pdf
  [2]: https://i.stack.imgur.com/sGeVf.jpg
  [3]: https://i.stack.imgur.com/Lqawe.jpg

title: How come my transistor doesn't work?

Answers: 3

body:
Is there the only wire from Arduino to the Base of Transistor?

Basically you need something like this:<br/>
[![enter image description here][1]][1]

If you reverse the transistor (E and C), builtin protection diode will be in forward direction, so electro magnet is on.

If you have only one wire to the base, it cannot work as you need current to the base.

If you don't have R1 into the base (about 500R-1K), it'll burn your output eventually. (not if you don't have common ground)

If you have electro magnet between ground and Emitter, you'll have negative current feedback and about 4.2V on L1 tops as there must be some current into the base.

  [1]: https://i.stack.imgur.com/YeDQk.png

body:
The program is fine.

Looking at the first photograph - The Ground of the Arduino needs to be connected to the ground of your circuit.

I do not understand the two-transistor part of your circuit, so I can't say if this is OK or not.  You could also switch the electro-magnet using a relay.

body: Assuming the - of the power supply is connected to ground your circuit becomes an emitter follower utilizing a Darlington transistor.  In that case the emitter will have the same voltage as the base - the VBE which is about 5 Volts. If you reverse it, you will need about 5 volts VBE to turn it on. Note since it is a transistor there is no protection diode. Best suggestion is to use a MOSFET, that will give you a lot more speed then a power transistor. Substitute the MOSFET in the circuit shown above. Source connects to the Emitter point, the Drain connects to the Collector point and the Gate connects to the base. Use something in the 50 Ohm range for the resistor. Your 12V - becomes ground connected to the Arduino ground. Use a logic level avalanche protected MOSFET and the diode is not needed.


body:
I'm working with a Realtek Ameba IoT RTL8195 board that's compatible to Arduino.

I have a text file on an SD card that I want to send via HTTP over wifi, with the Ameba acting as a server.

I combined the [SD card example](http://www.amebaiot.com/en/ameba-arduino-sdio-edit/) with the [web server example](http://www.amebaiot.com/en/ameba-arduino-ameba-web-server/). There's no LED involved here.

Upon request from a client, I want to shove the whole content of the text file into a `text/plain` response as quickly as possible. At the moment i have a 18.7KB dummy file that takes 6.3s to download in the broswer total. That's rather slow.

My code looks essentially like this:

    while (file.available() > 0)
    {
     client.print((char)file.read());
    }
    client.flush();

Where `file` is declared as `SdFatFile file = fs.open(absolute_filename);` and `client` is `WiFiClient client = server.available();`. Which are both classes that come with the Ameba Arduino SDK.

Both of them extend `Stream`. I wonder if reading and writing both streams byte by byte causes a bottleneck. is there a way to simply write "the whole thing" to `client`?

title: How to speed up writing a file to a WifiClient?

Answers: 1

body: Paul's suggestion from the comment worked. Increasing the buffer reduced the overall time to a couple hundred ms.


body:
I'm trying to recreate a small tween engine so I can interpolate values, leds hue, saturation and brightness in a easy way.

I'm having trouble to reference the value to interpolate into my tween object. If you look at the very last block, you'll see what i'm trying to achieve.

I've poor knowledge in pointers and references and it's driving me mad. Thanks for your help !

---

**Pixel.h**

    class Pixel {
      public:
        Pixel(float a = 180, float b = 100, float c = 100);

        float hue;
        float saturation;
        float brightness;

        uint16_t toRGB();
    }

---

**Tween.h**

    class Tween {
      public:
        Tween(int fps = 60);

        float& target;
        float fps;

        void to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d));

        void tick();
        float apply();
        bool active = false;

      private:
        float a = 0;
        float b = 1;
        float (* ease)(float t, float b, float c, float d);

        float increment = 1;
        float progress  = 0;
    };

---

**Tween.cpp**

    #include <Arduino.h>
    #include "Tween.h"

    int const ITERATIONS = 1000;

    Tween::Tween(int f)
    {
      this->fps = f;
      this->active = false;
    }

    void Tween::to(float& target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d)) {
      if (this->active == true) {
        return;
      }

      this->target = target;
      this->active = true;

      this->a = from;
      this->b = to;

      this->ease = ease;

      int frame = 1000 / this->fps;
      int ms = duration * 1000;

      this->progress = 0;
      this->increment = ITERATIONS / (float)(ms / frame);
    }

    void Tween::tick() {
      if (this->progress >= ITERATIONS) {
        this->progress = 0;
        this->active = false;
      }

      if (this->active == false) {
        return;
      }

      this->progress += this->increment;
    }

    float Tween::apply() {
      if (this->active == false) {
        return 0;
      }

      float value = this->ease(this->progress, 0, this->b, ITERATIONS);
      this->target = value;

      return value;
    }

---

The use of those will be :

    Pixel pixel = Pixel();
    Tween tween = Tween(40);

    void setup() {
      Serial.begin(115200);

      // reset the values of the pixel
      pixel.hue = 200;
      pixel.saturation = 100;
      pixel.brightness = 0;

      // setup the tween object
      tween.to(pixel.l, 0, 100, 3, Easing::linearTween);
    }

    void loop() {
      // progress
      tween.tick();

      // set pixel.l = tween value (this is where it's not working)
      tween.apply();

      Serial.println(pixel.brightness);

      // we defined 40fps in the tween so the delay should be 1000/40 => 25ms
      delay(25);
    }

The easing library is actually Robert Penner's work translated to Arduino (https://github.com/tobiastoft/ArduinoEasing)

title: Keep References Between Objects

Answers: 1

body:
The member variable `target` does not need to be passed by reference at all.

    void Tween::to(float target, float from, float to, float duration, float (* ease)(float t, float b, float c, float d))
    {
      if (this->active == true)
        return;

      this->target = target;
      this->active = true;

      // etc...
    }

And then just call it without any sort of address or reference operator.

    // setup the tween object
    tween.to(pixel.l, 0, 100, 3, Easing::linearTween);

(but you still need to sort out what you mean by "pixel.l")

If you wanted to pass a Pixel object to the Tween::to() function, I would use a pointer to the object (although you could use a reference too).

    void Tween::to(Pixel *pixel, /* ... etc*/))
    {
        target = pixel->hue;
        other  = pixel->saturation;
        foo    = pixel->brightness;

        // etc.
    }

Calling it like:

    // setup the tween object
    tween.to(&pixel, 0, 100, 3, Easing::linearTween);

It's not really clear exactly what you're trying to achieve just reading the code sample.


body:
I need to build a device with a single button to make a call over a mobile network (GSM)

I wanted to buy an arduino one and an arduino gsm shield for this, but just noticed that the GSM Shield is retired - discontinued.

I checked all the arduino products but there is no options for integration with GSM.

What options do I've to build my products if the GSM Shields is discontinued?

title: Why the GSM Shield is discontinued? What options are available?

Answers: 1

body:
A retired product is just a product that isn't supported anymore. It doesn't mean that this product is not usable anymore. Because the GSM shield is discontinued by Arduino.cc itself, you could buy Arduino.org ([link][1] to the GSM shield 2), or even an other model by Adafruit. Here is a [link][2] for many options of GSM shields on Adafruits' website.

A last option would be to buy it from a chinese seller on Amazon or Ebay. Though they are cheap, they are usualy very crappy and there are not many libraries for them.

  [1]: http://www.arduino.org/products/shields/arduino-gsm-shield-2
  [2]: https://www.adafruit.com/?q=gsm shield&


body:
I'm having trouble regarding motor control in a project I'm working on.

It uses an ATMega328 DIP package on a PCB. The motors I'm using are small coreless motors and I'm trying to control them using Si2302ds N-MOS FETs. For the power supply I'm using a 3.7V(4.2V on full charge) Lipo. I've tested this setup with a promini before and the motors turned on and off just fine.

This time I'm having problems with controlling 1 motor out of the 4. I've attached 0.1uF caps across each motor terminal (see schematic). Them control pins used for the motors are pins 3,5,6,9. The problem occurs at pin 3. I tried running the blink program on pin 3 to pulse the motor on and off through the FET but all I get is a bit of clicking from the motor.

Things I've already checked relating to the circuit :

 1. FETs are soldered on correctly and made sure they aren't defective.
 2. Motor works fine prior to connecting it to the circuit.
 3. Disconnected the FET and motor from pin 3 and checked the output.
    It works fine on its own.

The puzzling thing is that only 1 motor (at pin 3) seems to struggle to come on. The rest work just fine. Also if I try and turn all 4 motors ON, it doesn't work. But if I turn only the 3 working ones on and keep the non-working one off they turn on perfectly.

Is the problem occuring due to noise generated by the motor? What could be the problem? I've attached the schematic to this post below.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/jVfoy.png

title: ATMega328 not able to fully switch coreless motor on

Answers: 0


body:
When using the Arduino IDE on Windows (10) is there a way to get it to start the serial monitor automatically when the upload to the board completes?

I know this is a long shot, but pressing those extra 3 keys (CTRL-SHIFT-M) is really bugging me.

title: Arduino IDE - Start Serial Monitor once upload is complete

Answers: 1

body:
You could set up a macro triggered by the completion of the upload that automatically sends ctrl+shift+m. This could be done by watching for the exit of the upload application(AVRDUDE for example) or by calling a wrapper batch file from platform.txt's upload.pattern/program.pattern that runs the upload application and then triggers the Serial Monitor keyboard shortcut. There are a variety of Windows software options for doing this. [EventGhost](http://eventghost.net) is the one I'm most familiar with but [AutoHotkey](https://autohotkey.com) could likely do it also.

To do it with EventGhost you would either:

 - Install the **Process Watcher** plugin and use, for example, the `Process.Destroyed.avrdude` event to trigger the Serial Monitor keyboard shortcut using the **Send Keystrokes** action. This will cause false triggers on **Burn Bootloader** but you can get around that issue by identifying uploads by the compilation application events(such as `Process.Destroyed.arduino-builder`) that will not occur with **Burn Bootloader**.
 - Run EventGhost.exe from the wrapper batch file with the `-e` command line option to generate the trigger event.

I think the first option is the best because it doesn't require modifying platform.txt, which will need to be redone on every update of any hardware core.

Not exactly what you're asking for, but a much more simple solution is to use Arduino IDE 1.6.5 or newer, which leaves the Serial Monitor open(but disabled) during uploads. This means you only need to load Serial Monitor once. You could have both the Arduino IDE window and the Serial Monitor window tiled on your screen so that you don't need to switch screens to go from editing/uploading your sketch and using Serial Monitor.


body:
### TL;DR - Can the six yellow ISP pins be used as a normal ISP?

----

The usual USB-TTL FTDI breakout board looks like this:

[![USB-TTL FTDI Breakout board][1]][1]

Recently, I came across a variant of the board shown below. However, what are the additional yellow header pins on this board for? They are labelled ISP.

[![USB-TTL FTDI Breakout board with ISP][2]][2]

Here is a view of the rear:

[![USB-TTL FTDI Breakout board with ISP rear][3]][3]

So can they really be used as a standard ISP/ICSP?

[![AVR-ICSP][4]][4]

However, according to the diagram below, which labels the 6 pins in question, I am not sure that there is a valid correlation of signal lines.

[![USB-TTL FTDI Breakout board with ISP with legend][5]][5]

That is to say, would CTS to MISO, RI to RST, DSR to SCK and DCD to MOSI work? Or is that why a special version of avrdude is required, as alluded to in [FT232RL: USB to Serial 232 TTL Adapter –?and ISP? - post #6][6]:

> As a new feature there is a 6-pin ISP header available. With it, avrdude and avrftdi you can program Atmels and Arduino bootloaders. A special version of avrdude with compiled FTDI driver is neccessary.

However the [provided link][7] to that version of avrdude, with the compiled FTDI driver, is dead.

It is also said, [in post #7][6], that these pins are actually equivalent to an X3 connector, [as found on the older Arduino Dicimila/NG/Duemilanove][8] boards.

[![X3 header on Diecimila][9]][9]

and those can (evidently) be used like so, as a bit banged SPI,

[![Connecting X3 header to ISP header on Diecimila][10]][10]

It should be noted that the RI, CTS, DCD and DSR (labelled RSD) pins are available, along the sides of the original FTDI breakout board. So, does the breakout board with the ISP header just provide access to these same signals using a different header?

I am a little confused - have I just over thought this, and this breakout board is simply an ISP/ICSP header *and* an FTDI connector rolled into one board (when used with the appropriate version of avrdude)? Or is it not a usual ISP header? I can not find any *specific* documentation relating to this type of breakout board, [as stated in post #4][6].

Can anyone say, definitively, what these six pins are for? If they are not a normal ISP header, could you provide a detailed way of using it? A schematic would be helpful.

  [1]: https://i.stack.imgur.com/21VZq.jpg
  [2]: https://i.stack.imgur.com/fIXQV.jpg
  [3]: https://i.stack.imgur.com/sp4qM.jpg
  [4]: https://i.stack.imgur.com/y6e4z.gif
  [5]: https://i.stack.imgur.com/lmG5D.png
  [6]: http://forum.arduino.cc/index.php?topic=216889.0
  [7]: http://helix.air.net.au/index.php/avrdude-and-ftdi-232h/
  [8]: http://make.kosakalab.com/arduino/bootloader/index_en.html
  [9]: https://i.stack.imgur.com/XaIc0.jpg
  [10]: https://i.stack.imgur.com/0LYBD.jpg

title: FTDI Breakout with additional ISP connector

Answers: 2

body:
There's a thread about that on [the Arduino Forum](http://forum.arduino.cc/index.php?topic=216889.0) - someone had a similar question.

---

I found a schematic (below) which is *not* for that board, however the header pins are labelled the same as you found, so it is plausibly similar.

[![FTDI board schematic][1]][1]

It appears that header is used for "Synchronous Bit Bang mode" as documented here: [Bit Bang Modes For The FT232R and FT245R (Application Note AN_232R-01, Document Reference No.: FT_000339)][2]

---

You can in fact configure that header to be an SPI programmer, as described for example, in [FT232R Bitbang Programmer](http://diyduino.blogspot.com.au/2012/08/ft232r-bitbang-programmer.html).

---

I made up a test as I had a similar board in my parts drawer:

[![FTDI board front][3]][3]

It had provision for a 6-pin header similar to yours. Turning the board over we can see that they were labelled exactly the same as yours:

[![FTDI board back][4]][4]

I soldered on a header (in yellow, to be consistent) giving me this:

[![FTDI board with header][5]][5]

I added a white dot to indicate pin 1 (visible on the edge) so I plug the cable in the right way around.

---

When I attempted to use the board I got this message from avrdude:

> avrdude: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again

So, it had to be compiled from scratch! I am using Ubuntu 14.04 if you are trying to follow along. :)

---

## Download avrdude

Go to the site <http://www.nongnu.org/avrdude/>

I downloaded version 6.3 source: <http://download.savannah.gnu.org/releases/avrdude/avrdude-6.3.tar.gz>

## Install libusb and libftdi

Before compiling I had to grab libusb and libftdi:

    sudo apt-get install libusb-1.0-0-dev
    sudo apt-get install libftdi-dev

## Compile avrdude

Now we make avrdude after extracting the archive and navigating to its folder:

    ./configure --enable-libusb --enable-libftdi
    make

## Find correct configuration

Inside the `avrdude.conf` file which comes with avrdude I found (after some pondering) this seems to be the correct entry:

    # see http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
    # Note: pins are numbered from 1!
    programmer
      id    = "arduino-ft232r";
      desc  = "Arduino: FT232R connected to ISP";
      type  = "ftdi_syncbb";
      connection_type = usb;
      miso  = 3;  # CTS X3(1)
      sck   = 5;  # DSR X3(2)
      mosi  = 6;  # DCD X3(3)
      reset = 7;  # RI  X3(4)
    ;

The mapping of pins to numbers works like this... From the [PDF][2] about bit bang mode mentioned above we have this table, with annotations in blue by me:

[![Bit bang mode pins][6]][6]

The numbers refer to the bit number (i.e. in the range 0 to 7) in the "bit banged" data byte. We can see from the earlier schematic that, for example, MISO on the ICSP header is wired to CTS on the FT232RL. Thus MISO is data bit 3, which we tell avrdude in the above configuration. Similarly SCK is data bit 5, and so on.

I attempted to test like this:

    ./avrdude -C avrdude.conf -carduino-ft232r -pm328p  -v

## Fix permissions

I got a permissions error which was fixed by creating a file in the folder `/etc/udev/rules.d/` called `71-FTDI.rules`. Inside this is:

    SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE:="0666"

The numbers may vary for your board. You need to find the vendor and product ID. In Ubuntu you can do `lsusb` and see (amongst other things):

    Bus 003 Device 061: ID 0403:6001 Future Technology Devices International, Ltd FT232 Serial (UART) IC
                           ^^^^ ^^^^

Note the two hex numbers, which get copied into the rules file.

After doing that, tell the system to reload the rules:

    sudo udevadm control --reload-rules

Then unplug and replug the FTDI board to get it to notice the new permissions.

## Test board detection

Finally, the avrdude line above works and reads the chip:

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.01s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: safemode: hfuse reads as DE
    avrdude: safemode: efuse reads as FD

    avrdude: safemode: hfuse reads as DE
    avrdude: safemode: efuse reads as FD
    avrdude: safemode: Fuses OK (E:FD, H:DE, L:FF)

    avrdude done.  Thank you.

I had mine plugged into an ATmega328P.

---

## Example connected to a Diavolino

[![Programming an Atmega328P][7]][7]

Once we have got this far you just connect the FTDI board to your target board with a straight-through cable.

---

## Summary

The FTDI board you have (and the one I have) can be used as a ICSP programmer for the AVR chips, as described above. Thus a simple board can be both a USB to serial converter, and also an ICSP programmer.

I see similar boards selling on eBay for around $5 so that is probably quite a cheap programming option.

  [1]: https://i.stack.imgur.com/5vsiA.png
  [2]: http://www.ftdichip.com/Support/Documents/AppNotes/AN_232R-01_Bit_Bang_Mode_Available_For_FT232R_and_Ft245R.pdf
  [3]: https://i.stack.imgur.com/C3XQg.jpg
  [4]: https://i.stack.imgur.com/JqcK0.jpg
  [5]: https://i.stack.imgur.com/4HcqW.jpg
  [6]: https://i.stack.imgur.com/KGKOn.png
  [7]: https://i.stack.imgur.com/VOm0G.jpg

body:
Arduino IDE:
------------

Additional programmers.txt entries to use  "FT232R as ISP"

    ftdi232rasisp.name=FT232R as ISP
    ftdi232rasisp.communication=usb
    ftdi232rasisp.protocol=arduino-ft232r
    ftdi232rasisp.program.tool=avrdude
    ftdi232rasisp.program.extra_params=

avrdude.exe with FTDI bitbang support
[https://github.com/mariusgreuel/avrdude][1]

  [1]: https://github.com/mariusgreuel/avrdude


body:
I would like to know if I can use a pressure sensor with an Arduino. The code will detect when the sensor is on, will start a timer, stop when the sensor is off, and display the time elapsed.

Here is the code for the timer:

    int main(void) {
      LARGE_INTEGER frequency; // ticks per second
      LARGE_INTEGER t1,t2; // ticks
      double elapsedTime;
      // get ticks per second
      QueryPerformanceFrequency(&frequency);
      // start timer
      QueryPerformanceCounter(&t1);
      //the code for sensorwill be written here
      QueryPerformanceCounter(&t2);
      elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
      printf("\nElapsed time : %lf ms.\n", elapsedTime );
      return 0;
    }

title: Using Arduino to detect when a sensor is on and off and display time elapsed

Answers: 2

body:
You can easily do this in Arduino.

However I've noticed that you've written the code in C with the Windows functions. Why not write the Arduino code and use what the Arduino already has available, which is the `millis()` and `micros()` functions? The only problem with the `micros()` function is that it will overflow after 70 minutes.

The other thing to mention is how will you know when your sensor is on? One way would be to constantly read the value and set a threshold so that you can see whether the pressure sensor is under pressure or not.

Most of the code for this can be extracted from the various Arduino examples that are on the website.

For the pressure sensor threshold you can use the [Arduino AnalogInput example][1] and add an *if* statement after the analog read and combine that with the `millis()` function from the [Arduino BlinkWithoutDelay example][2]:

    int sensorPin = A0; // Choose whichever analog pin you like
    int sensorValue = 0;
    int flagA = 0;
    // flag is used just to indicate if timer has started or stopped

    unsigned long startTime;
    unsigned long stopTime;
    unsigned long elapsedTime;

    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      sensorValue = analogRead(sensorPin);
      // read the value from the sensor
      if(flagA == 0  && sensorValue > xxx) then {
        // if above threshold run timer
        startTime = millis();
        flagA = 1;
      }
      if(flagA == 1 && sensorValue < xxx) then {
        // if falls below threshold stop timer
        stopTime = millis();
        elapsedTime = stopTime - startTime;
        Serial.print("Elapsed time = ");
        // Put your print function in here
        Serial.print(elapsedTime);
        Serial.println(" ms");
        flagA = 0;
      }

  [1]: http://www.arduino.cc/en/Tutorial/AnalogInput
  [2]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

body:
Fairly easy, as basically you just need to time stamp the events from the sensor.

You can create a time base for the stamping. Triggering for the stamping can be done via polling, external or pin hanger I terrupts, or capture. To list a few.


body:
I am trying to connect my Arduino Pro Mini 3.3V to an nRF24L01 transceiver and cannot see what I am doing wrong. I've checked my wiring a million times because the problem hints there is an invalid or no connection between the Arduino and the transceiver. I have the following pin connections:

> Arduino --------------- nRF24L01
>
> --GND ------------------- GND
>
> --VCC ------------------- VCC
>
> ---D9 --------------------- CE
>
> --D10 -------------------- CSN
>
> --D13 -------------------- SCK
>
> --D11 -------------------- MOSI
>
> --D12 -------------------- MISO

I am using the following sketch

    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9, 10);

    const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0C2LL };     //Addresses to send/receive

    void setup()
    {
      printf_begin();
      Serial.begin(9600);
      radio.begin();
      radio.setRetries(15, 15);
      radio.openReadingPipe(1, pipes[0]);
      radio.printDetails();
      radio.stopListening();
    }

    void loop()
    {
      const char text[] = "Hello World";
      radio.write(&text, sizeof(text));

      delay(1000);
    }

I have no clue where I am going wrong. This setup works well on my Uno, however I cannot replicate it on the Arduino Pro Mini. Can anyone tell me if I am doing something super wrong that would prevent this from working? I'm all out of ideas. Appreciate any help in advanced!

**Update**:

I forgot to copy and paste the output from `printDetails()`:

    STATUS = 0x00
    RX_DR=0
    TX_DS=0
    MAX_RT=0
    RX_P_NO=0
    TX_FULL=0
    RX_ADDR_P0-1 = 0x0000000000 0x0000000000
    RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00
    TX_ADDR = 0x0000000000
    RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA = 0x00
    EN_RXADDR = 0x00
    RF_CH = 0x00
    RF_SETUP = 0x00
    CONFIG = 0x00
    DYNPD/FEATURE = 0x00 0x00
    Data Rate = 1MBPS
    Model = nRF24L01
    CRC Length = Disabled
    PA Power = PA_MIN

title: Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();

Answers: 1

body:
Whenever you get an _all zeros_ output from the `printDetails()` function you can bet you are having a communication issue between the Arduino and the nRF24 module.

Start by checking your connections.

Check your connections again, using a multimeter to ensure continuity.

Check your connections again (no, I'm not joking).

Finally add a capacitor (anything between 1uF and 100uF will do) between the `VCC` and `GND` pins of your nRF24 module: those modules are pretty sensitive to voltage fluctuations and they are subject to current consumption spikes at startup.

Pair that with a possibly not state of the art voltage regulator (especially on cheap Arduino clones) and you end up with a non responding nRF24 module: the capacitor will provide the extra juice whenever it's required by the radio module.

This is such a common problem that I started soldering the capacitors directly onto the modules to save breadboard space!

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/zeVvp.jpg


body:
This is a follow up question to https://arduino.stackexchange.com/q/30558/27703

I modified the old code to read from one `Stream` and write to another which looked like this and worked fine albite being a bit slow

    while (file.available() > 0)
    {
        client.print((char)file.read());
    }
    client.flush();

to use a buffer, like so

 char buffer[300];
 size_t bufferSize = sizeof(buffer);

    // ...

    while (file.available() > 0)
 {
  memset(buffer, 0, bufferSize);
  file.read(buffer, bufferSize);

  client.print(buffer);
 }
 client.flush();

Now, if the buffer size is > 15 (in the above case, it's 300), two additional characters `Øb` are introduced after the buffer size amount of characters. **If the buffer size is <= 15, this does not happen.**

If the file to be read contains `abcdefg` repeated several times, I get the following result for a buffer size of 32:

    |-------- 32 characters -------|Øb|-------- 32 characters -------|Øb|-----
    abcdefgabcdefgabcdefgabcdefgabcdØbefgabcdefgabcdefgabcdefgabcdefgaØbbcdefg

**What's causing those additional characters to appear?**

The above output is produced in the browser If I do **not** specify a charset. if I do, I get `�` instead of `Øb`.

title: Why do i get additional characters when reading a file through a buffer if buffer size > 15?

Answers: 2

body:
Try recording the actual number of bytes read and only write that number of bytes:

    size_t nr = file.read(buffer, bufferSize);
    client.write(buffer, nr);

body:
If the buffer is full of data then there is no null terminator on your data to output, the client.print will keep going past the end of the buffer until it hits a 0. Because of the way the compiler is placing things in memory you happen to always get 0b and nothing else (does your code happen to have some other variable with a value of 11?)

There are two solutions:
Either only output the number of bytes you read (in which case the memset instruction is no longer needed) or limit the file.read to one less than your buffer size so that there is always a 0 left at the end of the buffer.

    const int buffersize = 32;
    char buffer[buffersize];

    while (file.available() > 0)
    {
        int bytes = file.read(buffer, bufferSize);
        client.write(buffer,bytes);
    }

or

    while (file.available() > 0)
    {
        memset(buffer, 0, bufferSize);
        file.read(buffer, bufferSize-1);
        client.print(buffer);
    }

Also it's more a personal preference than a requirement but I don't like to use `sizeof(<array>)`, it only works within the same scope as the array definition and doesn't work if the array is passed to a function. This site is full of examples of people getting caught out by that and wondering why their array is always giving them a size of 4. So while it works fine in this instance I avoid using it if at all possible.


body: I am new to arduino and I want to interface it using java . I want to know is there a way to change the variable or set the variable using the input from java :D Thanks For reading Hope you can answer my question .. Sorry for my english not my first language :D

title: How to change the variable value on arduino program using java?

Answers: 1

body:
Although you can't straight-up change variables on the Arduino, you can create your own protocol over a serial connection using processing (https://processing.org) on your computer, and a sketch on Arduino.

Use the function

    Serial.begin(9600);
on the arduino to initialise a serial connection to your computer, and then in processing use the lines:

    Serial myPort;    // Initialise a serial object (do this at the start of the program)

    // Inside the setup() function:
    String portName = Serial.list()[0];    // Get the first portname on the list (this may need to be changed to get the right one)
    myPort = new Serial(this, portName, 9600);
to connect from the computer.

Once you have done this, you can use the functions

    myPort.write();
in processing, and

    val = Serial.read();
To recieve data on the arduino.

Source (see here for more info): https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/all


body:
For some weird reason, the following code doesn't compile. I get a "stray '\302' in program" error around `volatile unsigned int encoderPos = 0; `, and I have no idea what the issue is. I've been trying to figure this out for over 40min, and nothing works. It doesn't make any sense

    #include <U8g2lib.h>
    #include <SPI.h>

    //Pin definitions:

    const int control_PWM = A3; //PWM output for the delay

    const int btn_1 = 1; //Button for mode 1
    const int btn_2 = 4; //Button for mode 2
    const int btn_3 = 5; //Button for mode 3

    const int r_A = 2; //Rotary encoder A's data
    const int r_B = 3; //Rotary encoder A's data
    const int r_SW = 0; //Rotary encoder's button data

    const int oled_CLK = 9; //SPI cloack
    const int oled_MOSI = 8; //MOSI pin
    const int oled_CS = 7; //Chip Select pin
    const int oled_DC = 6; //OLED's D/C pin
    U8G2_SH1106_128X64_NONAME_F_4W_HW_SPI u8g2(U8G2_R0, /* cs=*/ 10, /* dc=*/ 9, /* reset=*/ 8);

    int mode = 1; //1: RGB, 2: HSL, 3: Distance control
    int value_selection = 1; //Actual value selectrion
    int value1 = 0; //red in mode 1; tint in mode 2
    int value2 = 0; ////green in mode 1; saturation in mode 2
    int value3 = 0; //blue in mode 1; luminosity in mode 2

    volatile unsigned int encoderPos = 0;  // rotary encoder's current position
    unsigned int lastReportedPos = 1;   // rotary encoder's previous position
    static boolean rotating=false;      // is the encoder activity status

    // interrupter variables
    boolean A_set = false;
    boolean B_set = false;
    boolean A_change = false;
    boolean B_change= false;
    void setup() {

    }

    void loop() {
    }

title: "stray '/302' in program error" when compiling

Answers: 2

body: 0302 is 0xc2. <s>Somewhere in your source you have one or more non-breaking spaces (0xa0) encoded in UTF-8 (0xc2 0xa0). Use `od` or a similar tool to find them, and then replace them with normal spaces.</s> Since you have non-ASCII Latin-1 characters in your source, those characters are encoded as two bytes with the first being 0xc2 or 0xc3. Remove all non-ASCII characters before proceeding.

body: One cause of the /(302) error is copy and paste code from a word processor. You have ASCII codes copied that add spaces, etc to your code. Go through each identified line and remove any extra spaces at the beginning and end of any identified line. Then, (Arduino IDE) go to TOOLS, Auto Format. At least, this cleared up the problem for me.


body:
I have an Arduino connected to a stepper motor with an Easy Driver. I want for the stepper motor turn to a coordinate point. I wrote a simple program in Visual Studio that sends a coordinate point to the Arduino. I tried to write this below to plot the coordinate point, but when I send a number to the Arduino, the stepper motor will only turn one step. I don't know how fix this.

Can anyone fix this problem please?

<!-- language: lang-cpp -->

    #include <AccelStepper.h>

    AccelStepper stepper(1, 9, 8);

    void setup()
    {
      Serial.begin(9600);
      stepper.setMaxSpeed(10000);
      stepper.setAcceleration(5000);
    }

    void loop()
    {
      char c;

      if(Serial.available())
      {
        int steps = Serial.read();
        stepper.moveTo(steps);
      }
      stepper.run();
    }

title: Problem controlling a Stepper motor with AccelStepper in arduino uno

Answers: 0


body:
I have an Arduino powering a small 180 degree Parallax servo that is used to control the throttle link for a small engine. I have code right now that will allow me to open/close the throttle (in either 1/4 or 1/5 increments) using the keyboard of my computer. This is well and fine but I really want to get it working so that when I press (hold) the hot key "t" the throttle will open but when I release the hot key I want the servo to cycle back to its original position (where the engine idles). If you have suggestions I would really appreciate them.

I am using Putty (Putty.org) to interface with the serial monitor so the arduino knows when 't' is pressed.

My Arduino code is just below this bit of wording (55 deg and 0 deg are the bounds of my throttle link, 55 is closed throttle (idle) and 0 is open throttle):

<!-- language: lang-cpp -->

    #include <Servo.h>

    Servo servo;

    int pos = 55;  // Stores the position (angle) of the servo. Range is [0, 180].

    void setup()
    {
      Serial.begin(9600);
      servo.attach(9);  // Attaches the servo on pin 9 to the servo object.
      servo.write(55);  // Resets the position.
    }

    void loop()
    {
      if (Serial.available())   // Returns true if there is serial input.
    {
        char ch = Serial.read();

        if (ch == 't')

          {if (pos <= 55)
            {pos -= 11.25 ;}}

         else

          {if (pos >= 0)
            {pos += 11.25 ;}}

        // Now ask the servo to move to that position.
        servo.write(pos);
        // Mechnical limitation to the frequency of commands given.
        delay(15);
    }

    }

title: How do I code my arduino to return a throttle servo to idle?

Answers: 1

body:
If your terminal program uses key-repeat, then let each 't' operate the throttle for just slightly longer than the repeat period (slightly longer than twice the period, if you want to tolerate single dropped characters). After that period without another 't', close the throttle. One implementation would be to (re-)start a countdown timer every time you see a 't', and close the throttle when the timer goes to zero.

No auto-repeat? You'll have to simulate it with your finger (and code for a somewhat longer repeat interval, of course).


body:
I am using [a SparkFun Monster Moto Shield (PDF)][1] for driving two DC motors. The shield is working fine and I am able to drive the motor in both directions. However, the current sensing is continuously showing "zero" in the serial monitor.

I am confused why the shield is not measuring any current. I want to measure normal current of 750 mA and stall current of 6 A but I'm getting zero value continuously. If anyone can help me I shall be very thankful.

  [1]: http://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/MonsterMoto-Shield-v12.pdf

title: SparkFun Monster Moto Shield current sensing issue

Answers: 1

body:
Can you show us how your code is looking like? Please remember that you can not measure current directly, the method that is used to do that is to measure voltage drop on measuring resistor.
Check this image
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/62OuG.png


body:
I'm trying to get data from a heat counter via the serial, the format of the response is:

<!-- language: none -->

    t1=ХХХ.ХХ t2=ХХХ.ХХ t3=ХХХ.ХХ t4=ХХХ.ХХ
    P1=ХХ.ХХ P2=ХХ.ХХ
    VolSpd1=ХХ.ХХХ VolSpd2=ХХ.ХХХ
    MassSpd1=ХХ.ХХХ MassSpd2=ХХ.ХХХ
    HeatSpd1=Х.ХХХ HeatSpd2=Х.ХХХ
    SumVolume1=Х.ХХХХХХХ SumVolume2=Х.ХХХХХХХ
    SumMass1=Х.ХХХХХХХ SumMass2=Х.ХХХХХХХ
    SumHeat1=Х.ХХХХХХХ SumHeat2=Х.ХХХХХХХ
    PowTime=Х.ХХХХХХХ PowOffTime=Х.ХХХХХХХ
    MeasTime1=Х.ХХХХХХХ MeasTime2=Х.ХХХХХХХ
    UnMeasTime1=Х.ХХХХХХХ UnMeasTime2=Х.ХХХХХХХ

I managed to get the data and parce it on arduino but only from the first line. I do not know how to get all other data.

title: Arduino - read multiline serial input

Answers: 1

body:
Since the format is just <variablename>=<digits><decimal-point><digits> <whitespace>, I'd parse it this way, instead of relying on newlines.

Just treat them as whitespace. So buffer all data till an `=` sign is found, store the buffer as the variable name, then read until you get something other than a digit or decimal point. Then store this as the value. Then do something with the value based on the variable name. Then read and ignore all following whitespace (spaces, tabs, newlines, carriage-returns). And start back from the top.

That way the parse will never get out of whack when some data get missing or something else goes wrong in the serial stream.


body:
I'm trying to print messages to the serial monitor, and all I get is some unreadable format.

Looping `Serial.println("Wait...!");` gives me the following results:

    ö’ö’ƒÕ•¬ƒ´¼Õƒö“ƒ²ƒƒƒ¬‘¼¬Õ”’“ƒ¬•

Why is it unreadable, and how do I make it print a readable format?

title: Serial print message results in gibberish

Answers: 1

body: This "weird" result usualy happens when you select then wrong baud rate or a different one then the one you beginned the serial communication with in the program. Thus by using `Serial.begin(9600);`, you have to make sure that the serial monitor is actually set to a baud rate of 9600.


body:
I built an avoidance detector robot from [this kit][1].

When I drove the robot, the two motors performed unequally, so I tested replacing the four x 1.5 AA battery pack with a 9 volts battery. It did the trick. I realized, after having read around Stackexchange a bit, that the L298N controller steals a 1.5 V cell just for "heating up".

So... my question is: Can I run the controller off a LiPo battery? If so, which voltage should I choose, when I want to power my Arduino Uno (copy) and the two motors off it?

I don't really understand what voltage the motors can take.

  [1]: https://www.aliexpress.com/item/New-Avoidance-tracking-Motor-Smart-Robot-Car-Chassis-Kit-Speed-Encoder-Battery-Box-2WD-Ultrasonic-module/32362408263.html

title: LiPo batteries with L298N controller

Answers: 1

body:
First off, congratulations on entering the world of robotics.  I hope you enjoy it as much as I have.  You are correct that the L298N has a voltage drop that is between 1.8V and 3.2V (at 1 Amp) or 4.9V (at 2A).  This is a problem I sometimes see in older generations of H-bridge designs.  After you figure this problem out and move on, I'd recommend switching to something a little newer like the [TB6612FNG][1] or maybe the [DRV8871][2], both of which are pretty common, smaller, and more efficient.  But that's a future step.  First lets get this current project powered.

I'm having to make some assumptions based on the images that you linked to but I'm going to assume that the motor board can take up to 12V and that it ouputs 5V that you are using to power the arduino.  I'm also going to assume that those yellow motors are the familiar cheap hobby motors that run at 3-6V.  If any of those are not true, please comment and we can see how things change.

Now as to what kind of batteries to use; there are literally thosands of ways to power this.  One option is AA batteries as you are doing now.  I would use maybe 6-7 AA batteries to account for the voltage drop of the hbridge but remember that they start at 1.5 but can quickly drop voltage.  And the more current you pull from them, the faster they will drop.  This will be cheaper if you only want to run it a few times since AA batteries are like $0.50 a piece in bulk.  But if you want to run it a lot to experiment, it's going to get expensive (and annoying) fast.  Another option is to use NiCad or NiMH batteries that are rechargable.  The batteries will be a little more expensive initially and you'll have to buy a seperate charger but this will save money in the long run and be able to supply more current to your motors.  NiCad and NiMH batteries are 1.2V (nominal) but come packaged in battery packs so I'd recommend probably an 8.4V pack.  Finally there is the Lipo battery packs, also called Li-Ion (which is a much better and more accurate name but I won't get started on that).  Li-Ion are rechargable like NiCad and NiMH but are much smaller and lighter for the same energy capacity (mAh).  Because of this they have become very popular and have become pretty economical.  For instance you can get a decent li-ion for under $20 on hobbyking and be very happy for several years.  Li-ion do have an inherant risk but as long as you don't do anything stupid, you'll be fine.  They also require a special charger but as long as you aren't worried about super fast charging this isn't too expensive.  Li-ion come in individual cells of 3.6V nominal (sometimes advertised as 3.7V) but also come in packs of 7.2V, 11.1V, or 14.4V.  Remember that these are the nominal values.  A 7.2V pack will start at 8.4V and drain to 6V before it is "dead"  If you go this route, I'd go with the 7.2V pack.

I would highly recommend you go with one of the three rechargable options since that will be more economical in the long term and will also allow for longer run times and will supply more current to the motors.  Hobbyking.com is a great resource for cheap rechargable batteries as is amazon.

I can't explain everything but here are some further quesitons you should google to get started:

-LiPo safety

-Lipo C rating

-Lipo voltage range

-Lipo mAh rating

I just want to fix a couple misconceptions from other answers:

1) Lipos are not expensive as hell if you take into acount how long they last and their other benefits such as size, weight, and ability to supply current.

2) For a given battery capacity, a LiPo will be smaller and ligher than AA batteries and will provide more current and longer battery life than AA batteries.  The ammount of current the Arduino draws will be tiny compared to the current of the motors so don't worry much about it.

3) Not only are Lipos recommended by many people for ground (and air and water) robots, they are becoming the standard for RC cars of almost every size.  The motors you are using here are 6V max so 7.2V lipo is a good way to go.  Later you might use motors that are 12V and will move up to a 11.1V or 14.4V lipo.  Some of the nicer lipos can deliver hundreds of amps to motors and are commonly use in battlebots and similar competions.  But you aren't there yet so you're going to use smaller lipos with these smaller motors and maybe someday you'll use big lipos with big motors.  Every project has different needs.

4) Sometimes a rechargable battery back will get hot if you are pulling a lot of curernt from it.  But as long as you respect the "C" rating (google it) you will be absolutely fine.

  [1]: https://www.sparkfun.com/products/9457
  [2]: https://www.adafruit.com/products/3190?gclid=CIXjg6X_htACFYOGaQodM-8DvA


body:
I have many LEDs and two servos connected to one Arduino Uno, and the servos are programmed to move randomly indefinitely. However, I would like to install a kill switch for the servos by reading a pot connected to the A0 pin, and when the input from the pot is over a certain value, the servos stop moving. Then, when the pot is "turned down" again, they resume the movement sequence.

I'm a novice, so please be gentle with me! I'm just in a time crunch and know you all probably have an elegant way of getting this done. Thanks!
<!-- language-all: lang-cpp -->

    #include <Servo.h>

    // ----CONSTANTS (won't change)

    const int led2 = 2;
    const int led3 = 3;// the pin numbers for the LEDs
    const int led4 = 4;
    const int led5 = 5;
    const int led6 = 6;
    const int led7 = 7;
    const int led11 = 11;
    const int led12 = 12;
    const int led13 = 13;
    const int killpot = A0; // analog pin for kill switch pot

    const int servoPin1 = 9; // the pin number for the servo signal
    const int servoPin2 = 10;

    const int led_3_Interval = 2000;
    const int led_5_Interval = 4000;
    const int led_6_Interval = 3000;
    const int led_7_Interval = 10000;
    const int led_11_Interval = 1000;
    const int led_12_Interval = 1000;
    const int led_13_Interval = 6000;
    const int led_4_Interval = 3000;

    const int blinkDuration = 2000; // number of millisecs that Led's are on - all three leds use this

    const int servoMinDegrees = 15; // the limits to servo movement
    const int servoMaxDegrees = 165;

    //------- VARIABLES (will change)

    byte led_2_state = LOW;
    byte led_3_state = LOW;
    byte led_4_state = LOW;
    byte led_5_state = LOW;
    byte led_6_state = LOW;
    byte led_7_state = LOW;
    byte led_11_state = LOW;
    byte led_12_state = LOW;
    byte led_13_state = LOW;// used to record whether the LEDs are on or off

    Servo left_servo;  // create servo object to control a servo
    Servo right_servo;

    int servoPosition1 = 90;     // the current angle of the servo - starting at 90.
    int servoPosition2 = 90;     // the current angle of the servo - starting at 90.
    int servoSlowInterval = 2000; // millisecs between servo moves
    int servoFastInterval = 1000;
    int servoInterval = servoSlowInterval; // initial millisecs between servo moves
    int servoDegrees = random(5, 50);       // amount servo moves at each step
                               //    will be changed to negative value for movement in the other direction

    unsigned long currentMillis = 0;    // stores the value of millis() in each iteration of loop()
    unsigned long previousLed2Millis = 0;   // will store last time the LED was updated
    unsigned long previousLed3Millis = 0;
    unsigned long previousLed4Millis = 0;
    unsigned long previousLed5Millis = 0;
    unsigned long previousLed6Millis = 0;
    unsigned long previousLed7Millis = 0;
    unsigned long previousLed11Millis = 0;
    unsigned long previousLed12Millis = 0;
    unsigned long previousLed13Millis = 0;

    unsigned long previousServoLeftMillis = 0; // the time when the servo was last moved
    unsigned long previousServoRightMillis = 0;

    //========

    void setup() {

     Serial.begin(9600);
     Serial.println("Starting SeveralThingsAtTheSameTimeRev1.ino");  // so we know what sketch is running

         // set the Led pins as output:
     pinMode(led2, OUTPUT);
     pinMode(led3, OUTPUT);
     pinMode(led4, OUTPUT);
     pinMode(led5, OUTPUT);
     pinMode(led6, OUTPUT);
     pinMode(led7, OUTPUT);
     pinMode(led11, OUTPUT);
     pinMode(led12, OUTPUT);
     pinMode(led13, OUTPUT);

         // set the button pin as input with a pullup resistor to ensure it defaults to HIGH

     left_servo.write(servoPosition1); // sets the initial position
     left_servo.attach(servoPin1);
     right_servo.write(servoPosition2); // sets the initial position
     right_servo.attach(servoPin2);
    }

    //=======

    void loop() {

         // Notice that none of the action happens in loop() apart from reading millis()
         //   it just calls the functions that have the action code

     currentMillis = millis();   // capture the latest value of millis()
                                 //   this is equivalent to noting the time from a clock
                                 //   use the same time for all LED flashes to keep them synchronized
     analogRead(resswitch);
     updateLed_2_State();
     updateLed_3_State();
     updateLed_4_State();
     updateLed_5_State();
     updateLed_6_State();
     updateLed_7_State();
     updateLed_11_State();
     updateLed_12_State();
     updateLed_13_State();
     switchLeds();
     servoLeft_Sweep();
     servoRight_Sweep();

    }

    //========

    void updateLed_2_State() {

     digitalWrite(led2, HIGH); // turn eye LEDs on
    }

    //=======

    void updateLed_3_State() {

     if (led_3_state == LOW) {
       if (currentMillis - previousLed3Millis >= led_3_Interval) {
          led_3_state = HIGH;
          previousLed3Millis += led_3_Interval;
       }
     }
     else {
       if (currentMillis - previousLed3Millis >= blinkDuration) {
          led_3_state = LOW;
          previousLed3Millis += blinkDuration;
       }
     }
    }

    //=======

    void updateLed_4_State() {

     if (led_4_state == LOW) {
       if (currentMillis - previousLed4Millis >= led_4_Interval) {
          led_4_state = HIGH;
          previousLed4Millis += led_4_Interval;
       }
     }
     else {
       if (currentMillis - previousLed4Millis >= blinkDuration) {
          led_4_state = LOW;
          previousLed4Millis += blinkDuration;
       }
     }
    }
    //=======

    void updateLed_5_State() {

     if (led_5_state == LOW) {
       if (currentMillis - previousLed5Millis >= led_5_Interval) {
          led_5_state = HIGH;
          previousLed5Millis += led_5_Interval;
       }
     }
     else {
       if (currentMillis - previousLed5Millis >= blinkDuration) {
          led_5_state = LOW;
          previousLed5Millis += blinkDuration;
       }
     }
    }
    //=======

    void updateLed_6_State() {

     if (led_6_state == LOW) {
       if (currentMillis - previousLed6Millis >= led_6_Interval) {
          led_6_state = HIGH;
          previousLed6Millis += led_6_Interval;
       }
     }
     else {
       if (currentMillis - previousLed6Millis >= blinkDuration) {
          led_6_state = LOW;
          previousLed6Millis += blinkDuration;
       }
     }
    }
    //=======

    void updateLed_7_State() {

     if (led_7_state == LOW) {
       if (currentMillis - previousLed7Millis >= led_7_Interval) {
          led_7_state = HIGH;
          previousLed7Millis += led_7_Interval;
       }
     }
     else {
       if (currentMillis - previousLed7Millis >= blinkDuration) {
          led_7_state = LOW;
          previousLed7Millis += blinkDuration;
       }
     }
    }
    //=======

    void updateLed_11_State() {

     if (led_11_state == LOW) {
       if (currentMillis - previousLed11Millis >= led_11_Interval) {
          led_11_state = HIGH;
          previousLed11Millis += led_11_Interval;
       }
     }
     else {
       if (currentMillis - previousLed11Millis >= blinkDuration) {
          led_11_state = LOW;
          previousLed11Millis += blinkDuration;
       }
     }
    }
    //=======

    void updateLed_12_State() {

     if (led_12_state == LOW) {
       if (currentMillis - previousLed12Millis >= led_12_Interval) {
          led_12_state = HIGH;
          previousLed12Millis += led_12_Interval;
       }
     }
     else {
       if (currentMillis - previousLed12Millis >= blinkDuration) {
          led_12_state = LOW;
          previousLed12Millis += blinkDuration;
       }
     }
    }

    //=======

    void updateLed_13_State() {

     if (led_13_state == LOW) {
       if (currentMillis - previousLed13Millis >= led_13_Interval) {
          led_13_state = HIGH;
          previousLed13Millis += led_13_Interval;
       }
     }
     else {
       if (currentMillis - previousLed13Millis >= blinkDuration) {
          led_13_state = LOW;
          previousLed13Millis += blinkDuration;
       }
     }
    }

    //========

    void switchLeds() {
         // this is the code that actually switches the LEDs on and off

     digitalWrite(led3, led_3_state);
     digitalWrite(led4, led_4_state);
     digitalWrite(led5, led_5_state);
     digitalWrite(led6, led_6_state);
     digitalWrite(led7, led_7_state);
     digitalWrite(led11, led_11_state);
     digitalWrite(led12, led_12_state);
     digitalWrite(led13, led_13_state);

    }

    //========

    void servoLeft_Sweep() {

         // this is similar to the servo sweep example except that it uses millis() rather than delay()

         // nothing happens unless the interval has expired
         // the value of currentMillis was set in loop()

     if (currentMillis - previousServoLeftMillis >= servoInterval) {
           // its time for another move
       previousServoLeftMillis += servoInterval;

       servoPosition1 = servoPosition1 + servoDegrees; // servoDegrees might be negative

       if (servoPosition1 <= servoMinDegrees) {
             // when the servo gets to its minimum position change the interval to change the speed
          if (servoInterval == servoSlowInterval) {
            servoInterval = servoFastInterval;
          }
          else {
           servoInterval = servoSlowInterval;
          }
       }
       if ((servoPosition1 >= servoMaxDegrees) || (servoPosition1 <= servoMinDegrees))  {
             // if the servo is at either extreme change the sign of the degrees to make it move the other way
         servoDegrees = - servoDegrees; // reverse direction
             // and update the position to ensure it is within range
         servoPosition1 = servoPosition1 + servoDegrees;
       }
           // make the servo move to the next position
       left_servo.write(servoPosition1);
           // and record the time when the move happened
     }
    }

    //========

    void servoRight_Sweep() {

         // this is similar to the servo sweep example except that it uses millis() rather than delay()

         // nothing happens unless the interval has expired
         // the value of currentMillis was set in loop()

     if (currentMillis - previousServoRightMillis >= servoInterval) {
           // its time for another move
       previousServoRightMillis += servoInterval;

       servoPosition1 = servoPosition1 + servoDegrees; // servoDegrees might be negative

       if ((servoPosition1 >= servoMaxDegrees) || (servoPosition1 <= servoMinDegrees))  {
             // if the servo is at either extreme change the sign of the degrees to make it move the other way
         servoDegrees = - servoDegrees; // reverse direction
             // and update the position to ensure it is within range
         servoPosition1 = servoPosition1 + servoDegrees;
       }
          else {
           servoInterval = servoSlowInterval;
          }
           if (servoPosition1 <= servoMinDegrees) {
             // when the servo gets to its minimum position change the interval to change the speed
          if (servoInterval == servoSlowInterval) {
            servoInterval = servoFastInterval;
          }

       }
           // make the servo move to the next position
       right_servo.write(servoPosition1);
           // and record the time when the move happened
     }
    }
    //=====END

title: Adding a kill switch for servos with states - blink without delay code

Answers: 0


body:
I wrote a sketch that used the `millis()` function in several places. I got odd behavior because I inadvertently used the plain `millis` in one line, without the parens. It evaluated to zero when running.

Why didn't the compiler flag this as an undeclared variable? I suspect it's because the name was already in the symbol table, but I still would have thought it'd be caught. Is this a quirk, or expected? If expected, what is the benefit?

C/C++ is not my main language so be gentle. (-:

Edit as requested to show some code. This is an incomplete sample, but shows the usage:

    const unsigned long GATE_OPEN_TIMER = 7000;
    const unsigned long GATE_CLOSE_TIMER = 12000;
    ...
    unsigned long gateStopTime = 0;
    ...

      if (isGateCycling) {                 // if open/close cycle is running
        if (isGatePassive) {               // if we're not applying power
          if (millis() >= gateStopTime) {  // if current delay expired
            digitalWrite(GateCloseRelay, ACTIVE);
            gateStopTime = millis() + GATE_CLOSE_TIMER;
            isGatePassive = false;

... followed by similar logic for the reverse direction. If any use of `millis()` is replaced by `millis`, the code falls over but the compiler sees nothing wrong.

title: Native function name w/o parens -- expected behavior?

Answers: 2

body:
In short, a function in an Arduino program that gets called without `()` will be considered as a plain variable. Try writing a small function in your program and call it without `()`. Nothing will happen.

The reason the compiler didn't flag it as an undeclared variable was because `millis` is a variable that is declared in a kind of pre-loaded library. Think of it as a library that is always there even if you didn't include it. That is why the compiler only saw it as a regular variable.

body:
I've made up a test case:

<!-- language: lang-c++ -->

    const unsigned long GATE_OPEN_TIMER = 7000;
    const unsigned long GATE_CLOSE_TIMER = 12000;
    unsigned long gateStopTime = 0;

    void setup()
    {
      if (millis >= gateStopTime) {  // if current delay expired
        gateStopTime = millis + GATE_CLOSE_TIMER;
      }
    }
    void loop()
    {
    }

Under IDE 1.6.9 I get these errors:

<!-- language: lang-none -->

    /tmp/arduino_modified_sketch_345879/sketch_oct27a.ino: In function 'void setup()':
    sketch_oct27a:7: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
       if (millis >= gateStopTime) {  // if current delay expired
                     ^
    /tmp/arduino_modified_sketch_345879/sketch_oct27a.ino:8:29: warning: pointer to a function used in arithmetic [-Wpointer-arith]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                                 ^
    sketch_oct27a:8: error: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
         gateStopTime = millis + GATE_CLOSE_TIMER;
                               ^
    exit status 1
    ISO C++ forbids comparison between pointer and integer [-fpermissive]

---

Under IDE 1.6.12 they are downgraded to warnings:

    /tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino: In function 'void setup()':
    /tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:9:21: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]
           if (millis >= gateStopTime) {  // if current delay expired
                         ^
    /tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:33: warning: pointer to a function used in arithmetic [-Wpointer-arith]
             gateStopTime = millis + GATE_CLOSE_TIMER;
                                     ^
    /tmp/untitled109152362.tmp/sketch_oct25b/sketch_oct25b.ino:10:31: warning: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int' [-fpermissive]
             gateStopTime = millis + GATE_CLOSE_TIMER;
                                       ^

    Sketch uses 512 bytes (1%) of program storage space. Maximum is 32,256 bytes.
    Global variables use 13 bytes (0%) of dynamic memory, leaving 2,035 bytes for local variables. Maximum is 2,048 bytes.

---

So, the compiler isn't totally letting you get away with it. You should check the warnings. But *why* are the warnings only warnings?

Checking the generated compile command (using verbose compiling) I see that 1.6.12 has an extra option: `-fpermissive`.

From the documentation:

> Downgrade some diagnostics about nonconformant code from errors to warnings.  Thus, using -fpermissive allows some nonconforming code to compile.

So you have "nonconformant code" but you are getting away with it.

I don't know why the Arduino devs did that. The whole point of making things like that errors is so you fix them at compile time, rather than scratching your head about why things don't work at run time.

Clearly the symbol `millis` exists. But it is a function (or perhaps a pointer to a function) and thus shouldn't be just compared to a number or have a number added to it. That's what those errors were about in 1.6.9.

---

Just remember, in C, C++ and the ilk, to *call* a function you *always use parentheses*, even if you are passing no arguments.


body:
I wrote simple code for my Digispark (Attiny85 with Micronucleus bootloader) in Arduino IDE:

    #include <DigiUSB.h>

    String inst;

    void setup() {
      DigiUSB.begin();
      pinMode(1, OUTPUT);
    }

    void loop() {
      if (DigiUSB.available()) {

        char inp = DigiUSB.read();

        if (inp == '\n') {
          DigiUSB.println(inst);
          DigiUSB.println(inst.length());
          inst = "";

        }
        else {
          inst += inp;
          }
      }

      DigiUSB.delay(1);
    }

DigiUSB works just like Serial communication in classic boards

If i send string and newline char i expect it to output this string back and print its length, but instead i receiving null string and 0 in any case

Is it problem with code or microcontroller itself?

[![DigiUSB monitor software][1]][1]

  [1]: https://i.stack.imgur.com/nG6tb.png

----------
**EDIT:**
Its seems to be digispark library problem itself:

DigiUSB.println() and DigiUSB.print() accept only char arrays

Also, there is no toCharArray() from classic arduino lib and no c_str() so i cant use atoi()

title: Read string from DigiUSB

Answers: 0