text:
Explanantion of Addressing
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.

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.

It's kinda weird, that he's using 3B address, as it's 64kB memory and 16bits should be enough. So: 1B read command, 2B adddress, 1B dummy (or more) to shift out data from the device.

@KIIV The 24-bit address is a standard protocol. It's the same as for flash chips, and they come in megabyte sizes. You can't arbitrarily choose your protocol, it is dictated by the chip, and all the chips use the same standard.

For Flash yes, but this is the SRAM and according to the datasheet, it uses only 2Byte Address for direct access and 1B Address for page read/write

You're right, that one does only use a 16-bit address. So the OP should read the datasheet and modify their code accordingly. Also they should never trust anything they read on Instructables since it's completely filled with complete ****.

@Majenko Thank you for your thorough explanation, i have a lot more insight into what is happening on the memory level. I have been looking at SPI and SpiRAM code on github and have seen that they do not include the & 0xFF because it is redundant.

@Majenko I guess the only thing I'm a little unsure of now is why we don't start reading at address 0, 1, 2, etc, and why we would have to shift the addresses to read every 8 or 16 times. Am i right in thinking that the reason we shift address is because we read and write memory in '8' bits and more at a time, not a bit at a time?

You shift addresses because the Arduino's SPI routines can only handle 8 bits at a time, so you have to split the address into 8 bit chunks and send those chunks. Then you can read (or write) as many bytes from that address as you like (size permitting)


text:
formatting of IPAddress via printf(...) family similar to Serial Object
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.

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:
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.
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.

Awesome information about the abstract classes. This is kind of what I was dying to know.

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]);

yes, as I said, "which isn't wrong, but its not the usual format for an IP address". this doesn't answer my question. Thanks, though.

@Octopus: I hoped you'll figure this out by yourself. Anyway code added (untested)

right on. now i'm having one of those "why didn't i think of that" moments. perfect!

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;
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Strange binary number representation
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.

Works for me. How it's even separated? Maybe it's 100 100 11 or so because you did just print not println ...

I also got a 100 when I tried it. @KIIV did raised a good point about println.

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.

I indeed falsely assumed the output to be split 4 bits each. println clarified the issue. The lagging 11 originated from some other print statement not displayed in my question above. Thanks!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Arduino shield bluetooth
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.

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). This will let you connect the shield to your Arduino while still leaving you with all of your female headers.


text:
20x4 LCD will write but then won't update
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.

it needs to be reset every 10 minutes or it loses its mind - I'm not familiar with electronic devices losing their mind, so to speak. Can you elaborate? As for your other problems, it is impossible to answer without seeing your code.

Please post the code that does not work, otherwise your question is unanswerable. Also the exact ref of your LCD would be good to know (they are not all the same). Finally a wiring diagram might be helpful too.

Have you tried to isolate the problem, ie remove all other sensors and only keep code that handles the display updates at specific times?

Ha.  Loses its mind means it becomes non-responsive - comatose.  I suppose I can be criticized for anthropomorphizing computer equipment.  :

If you look above you will see the source code is pretty basic.  And the problem has been solved by simply clearing the display and rewriting it.

I agree with SDsolar. I read the question, read the solution and am happy with SDsolar's response. No need for anything else

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.

Neither the question nor this answer are adding much value to the site. You have an unspecified LCD, with an unspecified library, called by code you haven't posted. Your solution doesn't clarify why this is needed in this case and not other cases.

@Gammon, you must not have read the actual question..  I suggest you scroll back up and take a look.  Meanwhile, the problem is solved by clearing and rewriting the display.  I don't have the expertise to debug libraries, but at least it now works.

I see a drive-by downvoted this answer.  I don't get that.  Bottom line is that this answer solved the problem.  Some peoples' kids.....

@Gammon, re adding value to the site:  For me, this added a lot of value.  I may not be like you so we may come to different conclusions.  Your comment that it does not add much value is at least parsed enough to not be an absolute, but there are a lot of different levels of people using this information.  Why not record our experiences?


text:
Arduino weather vane
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?

There are two-axis analog hall sensors that detect the orientation of a magnet, but they cost a bit more.  You could probably make yourself a low resolution absolute optical encoder with hand tools or a 3d printer.

Use two pots with the dead-spots at opposite ends.

Not sure but I think you should be able to use a magnetometer (compass). 5US on Amazon.com could afford you something good enough. https://www.amazon.com/HiLetgo-HMC5883L-Electronic-Compass-Magnetic/dp/B00UAIY698/ref=sr_1_2?ie=UTF8&qid=1477482294&sr=8-2&keywords=gy+271

Thank you for your pointer.  Here is the one I just ordered:  https://www.amazon.com/gp/product/B00SDTFI1Q/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1

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.

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)

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) 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.

The Arduino has plenty of pins (unless you're using lots and lots of them already). Think KEYPAD.


text:
How come my transistor doesn't work?
I have a TIP 120 to 229 NON 60V 5A transistor
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:

simulate this circuit – Schematic created using CircuitLab
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.

A magnet?!?! Do you mean an Electro-Magnet??

How about showing a circuit diagram?

@canadiancyborg Yes

@Majenko sure, gimme a sec!

Also try using a different pin then pin 13, use 12 for example. The led on pin 13 could mess up the transistor.

@Majenko not actually sure I could make a correct one...

Then how about a photo?

@Majenko great idea, updating

@canadiancyborg tried chaning to 12, no difference.

Uhhh transistor wrong way around in the schematic?

@Bradman175 The power is upside down, fixed it.

Is there the only wire from Arduino to the Base of Transistor?
Basically you need something like this:

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.

With reverse transistor do you mean reverse collector and emitter? What is "the base"?  I'll put in R1 but would that make this setup not work? I don't have D1 either, what does that do?

If the wire marked by white is +12V, it will be the last case, so no. Also you need common ground, but be carefull, I can see the smoke generator more likely...

The transistor is connected to on the wire with a white mark, is that the right or wrong wire?

White is usually the positive supply. You have to measure it.

You need a resistor between the arduino and the base of the darlington transistor.

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.

I don't understand the two-transistor part of your circuit - It's a Darlington transistor

@Kingsley, needs to be connected to the ground ok thanks! Is this likely what's causing my problem or is this for some other reason (trying to learn as much as possible).

Can confirm the darlington transistor, concerning the relay, I needed something really fast for my application, so I went with a transistor.

Also How would I do ground arduino in practice? Should i run a wire from ground on the Arduino to the negative pole on the 12V DC-converter?

@Himmators - Yes, the ground of the arduino should be connected to the power supply ground.  Generally all grounds are connected together.

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.

Why don't you add a schematic? Also, I think you overlooked the most important error in the original question, which is that the NPN darlington is used a a high side switch (which is never a good idea for an NPN device). In general, Darlingtons are more robust devices than MOSFETs, especially with inducive loads, so I think it's perfectly acceptable here.

A NPN as a high side and a PNP as a low side are emitter follower circuits, not switches as the transistor cannot be saturated. The emitter follower or common collector circuit provides an ideal buffer amplifier and it is easy to design the circuit however a switch it is not. Check this link: https://www.electronics-notes.com/articles/analogue_circuits/transistor/transistor-common-collector-emitter-follower.php


text:
How to speed up writing a file to a WifiClient?
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 with the web server example. 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?

You may try if doing it line by line is faster. Or in chunks of 500bytes (or whatever amount of RAM you have available)

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


text:
Keep References Between Objects
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)

The variable reference must be known and initialized in constructor (in its initializer list). If you need later initialization use pointers.

And that Easing library is pretty nasty one. So many sequence-point warnings...

may i ask why you downvoted this ? thank you for your feedback regarding the easing library tho. also, is it only that i need to initialize the reference holder or did you mean the reference variable ?

What is pixel.l? there is no "l" member (or function) in your PIxel class.

You don't need to use this->blah to access class member variables, just blah is enough.  e.g.: this->hue = 47.96; can just be hue = 47.96;  I guess you did this because you have the same parameter name as class member.

Please reduce your code to simply show what you need, rather than obliging everyone to read a lot of code that is unnecessary to provide a real answer to your question.

thank you @kingsley for this. i haf few parameters the same and coming from javascript putting "this" everywhere became a habit. i'll cut it down.

@jfpoilpret thank you for your feedback. i reduced the code already to make it what i thought the bare minimum not to be asked to put more code to understand fully the question. sorry for that.

From your question alone I am unsure what you are asking. Please edit your question so that it is clear what you are asking.

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.

i'm sorry if the sample code didn't really show my goal. i guess my lack of knowledge in C confused people more than anything else ; but you guessed right with your 2 answers. Thank you very much for your patience.


text:
Why the GSM Shield is discontinued? What options are available?
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?

I don't know about South America, but GSM is obsolete. There are only a few users in most countries, the networks have been cannibalised and will shortly be shut down.

@Milliways, not really. GSM is a reliable and easy way to communicate. It is not yet obsolete.

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 to the GSM shield 2), or even an other model by Adafruit. Here is a link 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.


text:
ATMega328 not able to fully switch coreless motor on
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 :

FETs are soldered on correctly and made sure they aren't defective.
Motor works fine prior to connecting it to the circuit.
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.

Can you interchange any pins / FETs / motors?  Eg, exchange the pin 3 and 5 connections to see if another pin drives 3's FET ok, or if 3 can drive another FET ok, and similarly for motors.

Indeed, mix and match would be a good idea.  If you mean "pager" type moters they can fail in interesting ways resulting in very high current drain.  Also use a scope, or failing that a speaker with DC blocking cap to make sure the pin in question is constantly on - perhaps try a simpler program that does nothing but drive that pin and enter an infinite loop.

What's your clock speed?

jwpat7 I have tried driving that motor with Pin 7 but without any luck. Though that is only a digital pin and without PWM capability.

canadiancyborg I'm using a 16MHz crystal

Can you post a higher resolution schematic? That is almost unreadable.

"I have tried driving that motor with Pin 7": Using 7 introduces another variable. What would be more useful is to interchange the motor on pin3 with one from 5, 6, or 9 - the working combinations. Then see if the problem follows the motor or the pin.

Nick Gammon Sorry for that, I've updated the post with a clear picture of the motor control circuit.

@JRobert and Chris - I removed the chip form the PCB, then put it into the Arduino board and ported the o/ps to the chip socket in the PCB. The circuit functioned fine in this setup but failed again after putting the chip into the PCB. So is it some sort of under-powering issue with the ATMega328 ? I'm using a 3.7V 500mAh  25C lipo. This supply worked well when I tested this setup on a breadboard. My understanding is that the ATMega328 brown out is set at 2.7V so the chip also should've been able to function.

A couple of thoughts: 1) The issue only happens with the chip on the PCB so the PCB environment is suspect. The PCB itself was used in both trials, right? If so, its hdw is prob OK. 2) On the Arduino, did you power with 5V? From USB? Then the PCB/LiPo combo might be starved for power. 2) Pin 3 is the only one of the 4 using Timer-2 for PWM. That might mean that in that chip, T-2 is closest to its margins, so is the first one to fail. Try testing the LiPo voltage for droop under load. 4) Try pin-10 instead of pin-3; it uses Timer-1. Definitely not a fix :)  but it might be instructive.

@JRobert No luck on pin 10 either! Yes the PCB was used in both cases. I'm not sure if it is a power issue anymore since even when I'm switching that single motor on it does not seem to work. I tried swapping chips but the problem still persists. When I cut the trace to the non-working pin, the other 3 motors work fine and even the unconnected pin3 works fine when I checked it with a DMM.

@SidharthM - let's take this to chat: http://chat.stackexchange.com/rooms/info/47641/atmega328-not-able-to-fully-switch-coreless-motor-on?tab=general

authors: พัชรีญา จันทร


text:
Arduino IDE - Start Serial Monitor once upload is complete
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.

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 is the one I'm most familiar with but AutoHotkey 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.

thats more complicated then clicking CTRL+SHIFT+M

@canadiancyborg of course it's more complicated. Any solution will be more complicated to initially set up than pressing three keys. Maybe there's a better answer but this is the one I know and have used to automate similar processes related to Arduino development.

OK Three keys doesn't seem so bad now.  I'll keep this because I'm sure I'll find a use for it on another binge of laziness.


text:
FTDI Breakout with additional ISP connector
TL;DR - Can the six yellow ISP pins be used as a normal ISP?

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

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.

Here is a view of the rear:

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

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.

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:

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 to that version of avrdude, with the compiled FTDI driver, is dead.
It is also said, in post #7, that these pins are actually equivalent to an X3 connector, as found on the older Arduino Dicimila/NG/Duemilanove boards.

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

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.
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.

There's a thread about that on the Arduino Forum - 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.

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)

You can in fact configure that header to be an SPI programmer, as described for example, in FT232R Bitbang Programmer.

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

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:

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

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 about bit bang mode mentioned above we have this table, with annotations in blue by me:

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

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.

Thanks Nick. Yes, that thread on the Arduino forums is the one that I referenced in my question, but it wasn't really clear as to how to use it - but it usefully pointed to the X3 header blog. The second link you provide seems to expand upon that topic even further, excellent, thanks. However, there still isn't any blog specifically written for this particular board, which is odd.

I believe that if you do this, you would be talking to the FTDI as a USB device and no longer using the operating system's serial port API, so there may be additional setup/driver/permission issues depending on what system one is using to host it.  FTDI's more capable FT4232H/FT2232H/FT232H parts are often used this way as JTAG interfaces to more advanced processors.

See amended answer. I got my board to work as an ICSP programmer.

Fantastic, great work. That is the documentation that I was after.

would it be possible to repeat the experiment in windows? I find it a very interesting topic

Yes, basically the same development files are part of the IDE downloaded for Windows.

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


text:
Using Arduino to detect when a sensor is on and off and display time elapsed
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;
}

QueryPerformanceCounter is a function from windows API. Arduino's millis() function will act in a similar way, but only in millisecond accuracy.

@chamod Arduino also has a micros() function which has accuracy down to 4 microseconds

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 and add an if statement after the analog read and combine that with the millis() function from the Arduino BlinkWithoutDelay example:
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;
  }

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.


text:
Trouble connecting Arduino Pro Mini (Atmega328, 3.3V) to nRF24L01 over SPI, receiving all 0 values when I use radio.printDetails();
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

Sorry guys quick update: 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

The printdetails output indicate bad connection or faulty module. Check your wiring and try again.

Aside from the fact your program does not look like this one, I would venture to guess that you are trying to use the address of the pointer to the first letter in your character string.  Try it again w/o the  '&'.  I think that way you will just use the pointer to the first letter in your character string.

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!


text:
Why do i get additional characters when reading a file through a buffer if buffer size > 15?
This is a follow up question to How to speed up writing a file to a WifiClient?
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.

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);

That worked, btw. what's the matter with the downvotes? How can I improve my questions?

@cross Who knows? This place can be a bit fickle sometimes...

Since you are doing this for speed drop the memset() it's a waste of CPU cycles in this situation

You are quite right there. I have removed it from my example for clarification too.

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.

I am aware of the pitfalls of sizeof and had tried it with a macro definition to double check, but the result was the same. I will try your suggestions regarding the null termination. The question still stands: Why does this only happen if bufferSize > 15?

If the issue does turn out to be a lack of termination (the second option is the best way to prove that) then the reason is that the behavior without the termination is completely undefined. It could well be that with a smaller buffer the compiler placed things in memory in a different way such that there always happened to be a 0 in the byte after the buffer.


text:
How to change the variable value on arduino program using java?
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

Devise and implement your own custom protocol through the (USB-tunneled) serial connection: the Java side would tell the Arduino “set this variable to this value” and the Arduino would do it.

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


text:
"stray '/302' in program error" when compiling
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() {
}

What IDE version?

Could you please edit your question to include the exact error message.

@canadiancyborg: Your edit obscured the problem.

@IgnacioVazquez-Abrams I just translated the french comments to english, how did it change anything?

@canadiancyborg: You removed the non-ASCII characters in the source, which were the cause of the error.

@IgnacioVazquez-Abrams wait, so non-ASCII characters in comments also affect the program?

Compile fine to me. UECIDE 0.9.1.

0302 is 0xc2. 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. 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.

You can probably just copy the code from your post and past it over the original code in the IDE. As I can't detect any weird characters in the text above (I think browser replace NBSPs with regular spaces). Invisible characters can be quite a pain for some compilers.

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.


text:
Problem controlling a Stepper motor with AccelStepper in arduino uno
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?
#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();
}

authors: อานนท์ เอื้อเฟื้อสุข


text:
How do I code my arduino to return a throttle servo to idle?
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):
#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);
}

}

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).


text:
SparkFun Monster Moto Shield current sensing issue
I am using a SparkFun Monster Moto Shield (PDF) 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.

What is supposed to measure the current?

You're goign to need to post your code.

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


text:
Arduino - read multiline serial input
I'm trying to get data from a heat counter via the serial, the format of the response is:
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.

Since the format is just = , 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.

Could you support me with the code?

First give it a try yourself. Come back if you have any questions.


text:
Serial print message results in gibberish
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?

By printing at the same baud rate that you are reading at?

Please show the code that initializes the Serial communication (Serial.begin(...)). Then show the settings of your serial monitor. I think just doing that should give you the solution.

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.

Thanks! I had no idea what baud rate is, but I figured it out with your answer


text:
LiPo batteries with L298N controller
I built an avoidance detector robot from this kit.
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.

Lipro? Do you mean LiPo?

I think so? :P Let me google. Yap. LiPo. Just uncovered my knowledge level. Thanks :-)

Cause Lipro are some diet pills. I see you want to make your Arduino diet a bit on the power but not sure that Lipros will work!!

Haha. They're even from Norway, where I live ;-)

Personally I would ditch the L298N and use a modern MOSFET based motor driver.

Good question by Nitech and great answer, mwwalk! (A little low on reputition so I cannot comment directly below you, so I'm posting this here) I'm also new to using batteries and powering electronics. I'm going with the exact description you gave, with an Arduino Uno and L298n motor controller, however with 4 yellow motors. Would a 7.2 V Li-Po (Li-Ion) still be the way to go? I'm also wondering, if I were to connect the arduino Uno to a RPi, e.g. a RPi model 3b, will the problem then be reduced to power the RPi, so that the arduino will draw power from the battery through the RPi? And is ther

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 or maybe the DRV8871, 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.

Thank you for your gentle approach to my lack of knowledge, @mwwalk. I believe you are correct regarding the motors. I tried running the motor controller off a 9V battery- which worked fine, and then the motors ran equally. I am also moving into RC planes and quads, and therefore I can benefit from using Li-ion batteries, since I can probably use the same charger.

I've started reading this guide to LiPo batteries: http://rogershobbycenter.com/lipoguide/


text:
Adding a kill switch for servos with states - blink without delay code
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!

#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

while (analogRead(resswitch) > 700);

Thank you! I've inserted that line in the servoLeft_Sweep()  and servoRight_Sweep() sections, and the LEDs pause where they are and the servos halt, which is good. But, is there a way to insert the "while" argument and have the LED sequence continue to run with the servos stopping?

Turn it into an if, invert the logic, and wrap it around the servo functions.

Please excuse my novice ability... but like this?
if (analogRead(resswitch) > 700);    {
if (currentMillis - previousServoLeftMillis >= servoInterval) {...

It's rather if (analogRead(resswitch) < 700) { servoLeft_Sweep(); servoRight_Sweep(); }

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Native function name w/o parens -- expected behavior?
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.

When you say you "used" millis - can you post the code? A line like this generates a compiler error: int foo = millis; The error is invalid conversion from 'long unsigned int (*)()' to 'long unsigned int'

Not sure how to format code in a comment, but.. basically the use is future = millis() + delay followed later by if millis >= future

Edit the question and put the code there, please using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you. That if statement doesn't look valid anyway.

Don't just post the line, post enough code to reproduce it (ie. that compiles without errors). For example, what type is future?

Many compilers will actually produce a warning for this.

I can't reproduce what you say is happening. For example on your posted line (removing the brackets) gateStopTime = millis + GATE_CLOSE_TIMER; I get the error: error: invalid conversion from 'long unsigned int (*)()' to 'long unsigned int'

And on if (millis >= gateStopTime) I get the error: error: ISO C++ forbids comparison between pointer and integer

@NickGammon  What can I say? Are we using different versions of the IDE (1.6.12 here)? Are there compile options I'm not seeing? I guarantee that it acts exactly as I describe it and not at all as you describe it, in my setup, which is stock out of the box. The program is short enough that I can post the entire thing if you think that will help.

Yes it will. And I can try that exact IDE. I compiled under 1.6.9 but I expect 1.6.12 will be the same. Wait, that's odd! Under 1.6.12 I only get one warning and no errors!  Hmmm - turn warnings up a bit in the preferences. Mine are at "default"

I've made up a test case:
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:
/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.

This is shocking! Why on Earth would they add -fpermissive? Maybe the core wouldn't compile without that?

Maybe. But you would think they have had time to fix that sort of stuff. I can't see an easy way of turning it off either. For newbies they are going to get code that compiles, but fails at runtime in obscure ways. Better to fail at compile time.

Seems that this kind of errors where reported as warnings by old versions of gcc, and the -fpermissive flag was added in order to avoid build errors on old libraries, effective since Arduino 1.6.10. This has already been reported as an issue.

@NickGammon  Thanks for the detective work. I knew I wasn't crazy . I had warnings turned up all the way and I still saw nothing at all. If you'd like my sketch I can post it somewhere, but at 3K bytes stripped it's probably too big to include here...? (And fwiw I'm not trying to "get away" with something, I made a typo that I still feel should have been flagged.) One puzzle to me is still why this isn't seen as an undeclared variable, or as a failure to call with (). Is it the case that in C++ a function name without () is a useful thing, seen as a pointer?

@JimMack: Exactly. A function identifier without () decays into a pointer to the function.

I'm surprised you got no warnings. I did, as I posted above. I didn't mean "get away with" in the sense that you were trying to get away with things - you made a simple error, and the compiler let you. :) As for functions as pointers, see Function pointers / function callbacks / function variables

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.

Is there really a variable named millis in the arduino core, or is it referring to the function pointer?

It's reffered to the function pointer but a function called without () will be seen as a previously declared variable even though it was declared as a function.

@canadiancyborg  So the situation is what I surmised -- it's not seen as undeclared because its name is already in the symbol table for another reason? Still, the question remains: what's the benefit of this compiler behavior-- when would it be useful? Shouldn't it be flagged?

It is flagged as an error when I try to reproduce it. The compiler isn't stupid.

millis is a variable that is declared in a kind of pre-loaded library - you are making this stuff up. It isn't a variable, it is a function. You might more accurately call it a symbol. Whether or not it is in a library is not relevant.

@NickGammon I tried to compile a program with something like int x = millis, worked fine.

'millis', without parens, is the address of the function of that name. It is properly declared; it was merely improperly used. Without parens, millis on the right hand side of an '=' evaluates to the memory address of the millis() function. Either use of the symbol (with or without parens) is valid. What was invalid was the context of use - note that the error messages were about illegal conversions or comparisons of different data-types (function pointer to long int), not about undefined symbols (which it isn't).

I tried to compile a program with something like int x = millis, worked fine. - what is the warnings level in your IDE preferences?

@NickGammon, default.

Which version of the IDE?

@NickGammon, 1.6.12 (downloaded from Arduino.cc)

I tried to compile a program with something like ... - I would be interested to see the actual code, not a vague description of it.


text:
Read string from DigiUSB
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?

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()

At DigiBlink example DigiUSB.refresh(); calls first at "loop()".
Maybe it could solve issue. https://github.com/digistump/DigisparkArduinoIntegration/blob/master/libraries/DigisparkUSB/examples/DigiBlink/DigiBlink.ino