text:
manual square wave period is off
I'm generating a square wave with my Arduino UNO using the following:
#define pin 10 // data pin to control servo

// pulse width (in microseconds)
int pulsewidth = 2500; // 400 Hz

// wave period in microseconds
int period = 20000; // 50 Hz

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

void loop() {

  // turn pulse on for pulsewidth duration
  digitalWrite(pin, HIGH);
  delayMicroseconds(pulsewidth);

  // turn pulse off
  digitalWrite(pin, LOW);
  delayMicroseconds(period - pulsewidth);

}

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).
Why is this exactly?  Is it because digitalWrite() is slow?

If you want precise timing use the PWM pins. E.g. Using the Timer1 library

Your comment on the pulse width line is not correct.  2500 usec would be 400 Hz if it were a period.

Why is this exactly? Is it because digitalWrite() is slow?

There is "hidden" code in the main() function which is calling loop(). Also digitalWrite() is slow compared to what is possible. Last, the millis() ISR is executing in the background.
Try the below:
void loop() {

  while (1) {
    // turn pulse on for pulsewidth duration
    digitalWrite(pin, HIGH);
    delayMicroseconds(pulsewidth);

    // turn pulse off
    digitalWrite(pin, LOW);
    delayMicroseconds(period - pulsewidth);
  }
}

And then try turning off interrupts.
Cheers!

From Arduino reference on delayMicroseonds:

Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

Although the reference does not specify further what happens if delay > 16383, a look at the actual code explains this (in wiring.c):
/* Delay for the given number of microseconds.  Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */
void delayMicroseconds(unsigned int us)
{
...
#elif F_CPU >= 16000000L
    // for the 16 MHz clock on most Arduino boards

    // for a one-microsecond delay, simply return.  the overhead
    // of the function call takes 14 (16) cycles, which is 1us
    if (us <= 1) return; //  = 3 cycles, (4 when true)

    // the following loop takes 1/4 of a microsecond (4 cycles)
    // per iteration, so execute it four times for each microsecond of
    // delay requested.
    us <<= 2; // x4 us, = 4 cycles

    // account for the time taken in the preceeding commands.
    // we just burned 19 (21) cycles above, remove 5, (5*4=20)
    // us is at least 8 so we can substract 5
    us -= 5; // = 2 cycles,
...

    // busy wait
    __asm__ __volatile__ (
        "1: sbiw %0,1" "\n\t" // 2 cycles
        "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
    );
    // return = 4 cycles
}

The line us <<= 2; explains why us should not exceed 16383, otherwise the left-shifted value will overflow (unsigned int is 16 bits on AVR).
In your situation, (20000-2500) << 2 will not be 70000 or 0x11170 in hexa (that does not fit into unsigned int), hence the result will be truncated to 0x1170 i.e. 4464, which will make the last part of the function (the busy wait) wait for the wrong duration.
In order to fix it, you have to split your second delayMicroseconds in one delay in milliseconds plus one delayMicroseconds:
delay(17);
delayMicroseconds(500);


text:
wire.h multiple slave addresses
Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?  For example I'd like it to emulate two different devices, one at I2C address 23 and the other at address 57.
I'm either looking for a way to do this directly, or to run multiple instances (each would need a different onReceive handler).

Why do you want to? That's like saying "I have a house in New York, and another in London. When someone sends a letter to the London house I want it to arrive in the New York house." That's not how addresses work.

Now you described, how my e-mails works :) Anyway I would like to do the same with i2C, as I am planning to have one master and a lot of slave devices (implemented by Ard's) and want to start with one dummy to emulate commanding all of them, then later, as I would implement the bodies and start suffering from space, pins and speed, I would transfer some devices to another HW. Then, if  I improve and shorten my code I would like to move back.So having more I2C addresses on the same Arduino (and access to different would run different code/codepath) make perfect sense for me. Bad luck, I cannot.

Is it possible to use wire.h on an Arduino Uno to act as a slave for more than one address?

The quick answer is: No!
The ATmega328 2-Wire Serial Interface has a special register for the address match in slave mode. This only allows a single address to be matched.

22.5.4   Address Match Unit
The Address Match unit checks if received address bytes match the seven-bit address in the TWI Address
  Register (TWAR). If the TWI General  Call Recognition Enable (TWGCE)
  bit in  the TWAR is written to one, all  incoming address bits will
  also be compared against the General Call address. Upon  an address
  match, the  Control Unit is informed, allowing correct action to be
  taken. The TWI may or may not acknowledge its address,  depending on
  settings in the TWCR. The Address Match  unit is able to compare
  addresses even when the AVR  MCU is in sleep mode, enabling the MCU to
  wake up if addressed by a Master. Reference, pp. 213

On an ATtiny with USI it is actually possible to implement multiple address matching as this is controlled by software.
Last, a pure software approach could be used, i.e. implement the I2C protocol with external interrupt pin and fast pin access. See Amtel Application Note AVR154. The code for this app-note can be found on github. This could be modified to allow multiple slave addresses.
Cheers!

source: Stack Exchange

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

sort: votes


text:
First Serial.print voltage is wrong, way too low. Ruins average calculation
The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.
https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf
For the average calculation I added:
count = count + 1;
volt_mV = ((count-1)/count)*volt_mV + (1/count)*volt_V;

Please post the exact code you are using, rather than letting us see what source you have started from and then try to guess what you have added or changed to it.

The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.
Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.
Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply exponential smoothing or some other form of smoothing to the readings.
Note, the formula you show for averaging – ((count-1)/count)*volt_mV + (1/count)*volt_V – has a number of problems.  First, if count is an integer, both of ((count-1)/count) and (1/count) will compute to zero values.  Secondly, as count becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a running average, it does not compute a moving average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like movingAverage = (15*movingAverage + newReading)/16.

Your movingAverage formula is a lot better than the one I was using. It quickly fades out the error from the first reading. Its nice to learn the difference between a running average vs. a moving average.

If it is truly only the first reading that is bogus, you could take one or a few readings during setup() whose values you ignore, before your program starts collecting data. Or you could investigate why your first reading is bogus....

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


text:
What am I doing wrong with my millis()?
Im new to Arduino and have been trying to use the millis() function for an assignment of mine. I have had a lot of trouble trying to get the millis() function to work but now it seems to be working properly as far as I can tell through the serial viewer but it wont stop my loop once it goes higher than the run time. Im trying to stop my loop after 10 seconds, but it continues going and I feel like it has something to do with my millis().
 // Pin 13 is the LED

 int led = 13;        // pin 13 on the board
 int ledOFF = 8;      //led off time delay
 int ledON = 5;            //led on time delay
 unsigned long Timer = 0;      // store time
 int runtime = 10000;      // run loop for 10s

 void setup() {
   pinMode(led, OUTPUT);

   Serial.begin(9600);
   delay(1000);
 }

 void loop() {
   Timer = millis();
   int state = 0;
   while(millis() - Timer <= runtime){
     Serial.println(Timer);
     if(state==0){
       digitalWrite(led,LOW);
       state = 1;
       delay(ledOFF);
     }
     else{
       digitalWrite(led,HIGH);
       state = 0;
       delay(ledON);
     }
    }
   }

as @Andre said on comment, you give variable 'Timer' a new value each loop. One of the solution is putting Timer = millis(); on the void setup instead on void loop

Thanks for your reply as well, that was exactly my problem. I cant believe I been over looking that all this time.

You are always re-init Timer as millis on every loop. So millis() - Timer is probably always a few milisecond and never reaches your runtime value.


text:
How to setup an I2C bus which stays valid if a slave is powered down or fails?
I have setup an I2C bus between 3 Arduinos (Master, Slave1 and Slave2) by connecting all 3 A4 pins together, all 3 A5 pins together and one GND pin of each Arduino to a common ground line. The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.
The slaves use the Wire library: Slave1 is at address 0x07 and Slave2 at 0x08. The Master uses the I2C library by Wayne Truchsess, because this library has timeout functionality. Master polls Slave1 and 100 ms later, polls Slave2. If either Slave is unavailable, Master should still read the other Slave (this is why Master doesn't work with the Wire library).
However, even though Master doesn't get locked-up, it can't read one Slave if the other gets powered down but left connected. If I cut the power of Slave1, Master becomes unable to read data from Slave2 until I physically disconnect Slave1. If I disconnect Slave1, Master is immediately able to read from Slave2 again. I2C scanning suggests the whole bus becomes invalid when a Slave is powered down (SCL and/or SDA turned low?).
From what I have been reading, this is not a software issue but an electronics circuitry problem: leaking current related to Slave1 and Slave2 having some diodes, something that perhaps could be solved with some transistors or N-FETs which would act like check-valves? Please advise.
P.S.: I have very little background in electronics and English is not my first language.

From what I have been reading, this is not a software issue but an
  electronics circuitry problem: leaking current related to Slave1 and
  Slave2 having some diodes, something that perhaps could be solved with
  some transistors or N-FETs which would act like check-valves? Please
  advise.

A nice solution to this problem is to use I2C Bus Isolation with TI TCA4311A Hot Swappable 2-Wire Bus Buffers alt. Analog Devices ADUM1250.
Please see the EEVblog Electronics Community Forum for further details and discussion.
Cheers!

That was the forum where I saw the "diodes" issue. I tried to draw an schematic of how I understood things should be wired, but I don't know what to connect to the VCC of the hot swap chip. A4 and A5 are the I2C pins of arduinos and D6 would be a pin I could use to drive the hot swap. Could you take a look? http://www.schematics.com/project/test-44785/

Please see fig. 11, pp. 13, for correct wiring of hot-spot; http://www.ti.com/lit/ds/symlink/tca4311a.pdf

Thank you! It makes sense. Two more questions: 1) what is BD_SEL? 2) can the VCC of the backplane simply be a 5V regulated output from the Master Arduino?

Ah, another question: in the drawing, there is a branch called "Card enable/disable". That is a pin in the slave arduino which would be always set HIGH by the slave's firmware so that a failure would automatically disable that slave, right?

The ADUM1250 might be easier to understand and use. Please see the Application Note; http://www.analog.com/media/en/technical-documentation/application-notes/AN_913.pdf. This is very straight forward.

The 3 Arduinos are currently being powered by independent USB power supplies, but I intend to power all of them from one single power supply using their Vin pins.

I think your problem here is that if you power down one Arduino, it isn't really powered down, because it will get "parasitic power" from the I2C line, particularly from the pull-up resistors which should be there. The protection diodes (internal to the processor) will allow power to flow from the A4 and A5 pins to the Vcc pin of the chip, which will then power up, probably in some sort of indeterminate state.
Since you are planning to power them from the same supply anyway, your problem should simply go away when you do that. Connecting a device with active inputs to a circuit (ie. a voltage present) when the device itself is not powered up, is not recommended. Exceptions would be devices that are specifically designed to handle that, for example, commercially produced printers via their USB input.

I am powering the slaves down to simulate failures. A slave may fail even if the rest of the system keeps working.

That's not a good model of a recoverable failure, as it imposes an unrecoverable electrical fault.  Holding a slave in reset, especially if you can trigger it mid-transfer might be.  Or put the failure simulations in the firmware of the slaves.

Indeed, but since the slaves are sensor modules that can be hard-reset in seconds and measure data for R&D, I thought I could treat all failures as unrecoverable. If I hard-reset the sensors, they do not lose calibration, and I thought later I could add relays for automatic hard-resetting. Is that a bad idea?

An I2C bus should use open drain lines or open collector drivers AND there should be only 1 (one) pull up resistor for each of the 2 I2C wires.  In this way, should a slave fail, it will not effect the I2C bus.
An Arduino does not truly have an open collector driven pin.  Instead people have been clever and either set the pin connected to an I2C line low pulling the I2C bus low or as an input allowing the I2C bus to float high through the pull up resistor. In this way multiple I2C devices (Arduino or not) can share the bus.
However, if you power down an Arduino, it can no longer operate in this manner.  In fact it will likely appear as a load or path to ground and effect the normal operation of the I2C bus.
In the end, I2C is designed for chips (usually) on the same board so that they can talk with one another.  It would follow that they are all powered off the same supply. It is an unlikely scenario for power to fail for only one device on the board.
Alternatives:
There are protocols designed to go between devices (as in separately located and separately powered).  RS485 is one such protocol and has been around for years.  A quick search show both sheilds made specifically for Arduinos as well as tutorials using generic RS485 interfaces.

Thanks for the response. As I said, I lack the necessary background so I am going to have to ask further stupid questions: "to drive an open collector configure transistor" -> what does that mean? A transistor has 3 terminals, right? What goes where? Would it be 1 transistor for every slave as an intermediate between the slave and which I2C wire? Would any transistor do the trick?

I think it would be difficult to design an I2C buffer that would  not inhibit the bus if it lost power.  I tried to describe one in the answer.  But w/o electrical experience, I think it would be difficult.  Also, it is an unlikely scenario given I2C devices are expected to be co-located on the same board.  So I offered up RS485 as an alternative in the answer.

RS485 is a good tip and I found that MAX485 chip being sold in my country! "transmit on one pin and receive on another" -> so if I only have 2 slaves and a lot of unused pins in the Master, would the SoftwareSerial library be a simple solution, instead of trying to use I2C? Like, using D7 and D8 as RX and TX for Slave1 and D5/D6 for Slave2?

This theory is simply wrong.  It appears based on guesses that were not checked but easily could have been, and as a result it only confuses readers without helping.  Please delete.

Agreed.  I was adding text based on the comments left by the O.P.  He appears to be happy.  Although he did not vote or accept my answer.  I'll edit it down to a normal stackexchange answer.

I couldn't vote because I didn't have enough points. Upvoted now

Appreciated.  (With enough points you can actually see the individual up/down counts.)  It is a difficult problem.  But, again, I2C is usually a bus which is on the same board as all the parts.  Its just not setup to (by its self) handle one part getting its power cut off.

Mikael has the correct answer above.
I had this same issue when using two Megas communicating over I2C, along with other items running on the I2C bus. I needed the system to continue running if one Mega went down due to loss of power. The other Mega should detect it and execute some abort commands for my mission.
Initially I wired the Megas up on the same I2C bus, just as I would any other device. When I unplugged one Mega, the other would freeze the next time it tried to address another device on the bus.
The solution was to use a hot-swappable I2C buffer. I used this one, and everything worked immediately without issue after wiring it up: http://www.mouser.com/search/ProductDetail.aspx?r=595-TCA4311ADR
To integrate the SOIC-8 package onto a standard DIP breadboard for Arduinos, I used an adapter from Adafruit.
Cheers and good luck
Chris
High Altitude Photography Platform 360 video from a jet-stabilized platform at the edge of space http://hialtphoto.blogspot.com
Facebook @hialtphoto


text:
File download from SD card hangs up my ESP-12E
I'm using ESP8266 Arduino for compiling and uploading my code to NodeMCU 1.0 (ESP-12E Module).
Flash Size: 4M (3M SPIFFS)
CPU frequency: 80 MHz
Upload Speed: 115200
I'm using portable arduino-1.6.9-windows extracted in my D: drive. I'm using the latest ESP8266 Arduino image brought by git command.
I've written this basic code to download 'datalog.txt' file (stored in the root of my SD card).
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "
Hello! from ESP8266!
"
                "
<button>Download</button>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: ");
    Serial.println(fsizeDisk);

    size_t fsizeSent = server.streamFile(dataFile,"text/plain");

    Serial.print("fsizeSent: ");
    Serial.println(fsizeSent);

    dataFile.close();
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}

But, when I press the 'Download' button, the ESP hangs, dumps some errors and then restarts as displayed below (from my Serial Monitor):
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

Panic D:\arduino-1.6.9-windows\arduino-1.6.9\hardware\esp8266com\esp8266\cores\esp8266\core_esp8266_main.cpp:98 __yield

ctx: sys
sp: 3ffffc80 end: 3fffffb0 offset: 01b0

>>>stack>>>
3ffffe30:  3ffefdf4 000003b9 000003b9 4010020c
3ffffe40:  00000000 3ffe9645 00000001 4020815d
3ffffe50:  3ffefdf4 00000481 3fff0d50 402077e5
3ffffe60:  3fff337c 00000b68 00000000 40207823
3ffffe70:  3fff3a74 3fff1480 3fff3a74 3fff1474
3ffffe80:  3fff337c 00000b68 3fff307c 40202a57
3ffffe90:  3fff3a74 00000b68 3fff2cfc 40202c07
3ffffea0:  00000000 3ffe9704 3fff337c 3fff1474
3ffffeb0:  3fff337c 3fff147c 3fff2cfc 40202d34
3ffffec0:  3ffeead0 0883f900 3fff1478 40202d54
3ffffed0:  3fff337c 3fff147c 3fff1478 4022670d
3ffffee0:  00000000 0104a8c0 00000010 00000000
3ffffef0:  00000000 00000010 3ffefe40 40221001
3fffff00:  40210000 00000000 0000007d 3fff151c
3fffff10:  3ffebae4 3fff1520 3fff3434 40224b39
3fffff20:  3fff1370 3fff1fac 3fff1fac 4021547e
3fffff30:  40215972 3ffed310 3ffebabc 3fff1fac
3fffff40:  3ffebad6 00000000 3fff3434 40223f35
3fffff50:  0204a8c0 3ffee318 02a93dee 00000000
3fffff60:  40104b62 02a93dee 3ffeead0 60000600
3fffff70:  4022d230 3ffeeaa8 3ffeead0 0884220c
3fffff80:  4022d256 3fffdab0 00000000 3fff2004
3fffff90:  3fffdc90 00000000 3fff3434 4022ce8b
3fffffa0:  40000f49 3fffdab0 3fffdab0 40000f49
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v00000000
~ld

Please visit:
192.168.4.1

Card Initialized.
HTTP server started

I tried updating the code by writing custom "server.streamFile()" function and adding
"Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";

to the header to allow downloading the txt file as an attachment.
The modified code is [Only handleDownload() function has been changed]:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;

const char *ssid = "tiny-esp";
const char *password = "password";

ESP8266WebServer server(80);

String home = "
Hello! from ESP8266!
"
                "
<button>Download</button>";

void handleRoot() {
    server.send(200, "text/html", home);
}

void handleDownload() {

    int32_t time = millis();
    File dataFile = SD.open("datalog.txt");
    int fsizeDisk = dataFile.size();
    Serial.print("fsizeDisk: "); Serial.println(fsizeDisk);

    String WebString = "";
    WebString += "HTTP/1.1 200 OK\r\n";
    WebString += "Content-Type: text/plain\r\n";
    WebString += "Content-Disposition: attachment; filename=\"datalog.txt\"\r\n";
    WebString += "Content-Length: " + String(fsizeDisk) + "\r\n";
    WebString += "\r\n";
    server.sendContent(WebString);

    char buf[1024];
    int siz = dataFile.size();
    while(siz > 0) {
        size_t len = std::min((int)(sizeof(buf) - 1), siz);
        dataFile.read((uint8_t *)buf, len);
        server.client().write((const char*)buf, len);
        siz -= len;
    }
    Serial.print(siz);
    Serial.println(" Bytes left!");

    dataFile.close();
    time = millis() - time;
    Serial.print(time); Serial.println(" ms elapsed");
}

void setup() {
    delay(500);
    Serial.begin(115200);
    Serial.println();

    WiFi.softAP(ssid, password);

    IPAddress apip = WiFi.softAPIP();
    Serial.print("Please visit: \n");
    Serial.println(apip);

    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
        Serial.println("\nCard failed, or not present");
        // don't do anything more:
        return;
    }
    Serial.println("\nCard Initialized.");

    server.on("/", handleRoot);
    server.on("/down", handleDownload);
    server.begin();
    Serial.println("HTTP server started");
}

void loop() {
    server.handleClient();
}

Now, when I press the Download button, a popup opens up in browser displaying "datalog.txt" has started downloading. But after about 20-30 seconds it says "Download failed". The esp freezes after printing the 'fsizeDisk'.
Meanwhile, the serial monitor reads:
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600

I don't understand what am I doing wrong. Please help!
EDIT: I added delay(2) and a Serial.println(cnt++) inside while(siz > 0) in handleDownload() for debugging:
int cnt=1;
delay(10);
while(siz > 0) {
    delay(2);
    Serial.println(cnt++);
    size_t len = std::min((int)(sizeof(buf) - 1), siz);
    dataFile.read((uint8_t *)buf, len);
    server.client().write((const char*)buf, len);
    siz -= len;
}

What happens now is, I get
Please visit:
192.168.4.1

Card Initialized.
HTTP server started
fsizeDisk: 28600
1
2
3
4
5
6
7
8

The loop may hang up at any count(e.g. 10, 15, 17, 23, etc). Also, in my browser, it reads as 28% downloaded (for cnt=8) or so. So, file starts downloading but hangs up midway. I've tried increasing the delay upto 10 ms, but there has been no progress.

Try running blink on you hardware for a few minutes to illuminate hardware/IDE issues.

Ultimately this may be something you need to pursue with the authors of the ESP8266 port.  Perhaps you can try downloading a file without saving it anywhere (just throw away the data) or generate dummy data in a file and saving that.  You could also try using a small test file of known contents.  And try a different SD card.  How are you powering this?  The card might consume more current when being written.

I've already posted this question in esp8266 forum. There has been no replies yet. I'm powering this (NodeMCU) using USB2.0 from my laptop. I don't think SD card is an issue here. I'm not writing anything on the card, just reading it. I'll try using a file of small size (~2kB). I'll also try downloading a file without saving it anywhere.

try to add a yield() command in to your wihle-loop.
With yield() the ESP hast time to do his background jobs.

I tried adding delay(2) in the while-loop. Now the download starts, but it does not finish. I've tried delay upto 10 ms, but there has been no improvement. I'll try adding yield() instead. In the meanwhile, please see the EDIT.

authors: Игорь Мурзин


text:
Need to turn on project twice in order for screen to work!
This problem is really stumping me. I made a simple printed circuit board with an ATtiny85, a 128x64 I2C OLED display, and a Sharp IR analog distance sensor. You can view the circuit here: circuits.io.
If I turn the system on using the simple 3-pin slide switch that I put on the board, the screen does not turn on. I can see that the system is powered though, because I can see a little bit of red light escaping from the IR sensor where some of the IR light borders on the visible end of the spectrum. If I turn the board off then immediately turn it back on, the display powers up just fine. If I upload a new program to the board and use the programmer's 3.3v power I don't need to do it twice - the screen works first time.
I'm using a 3.7v LiPo battery, so I know power is not an issue (everything is 3-5v tolerant, and the LiPo battery can deliver plenty of current). Why do I need to turn it on twice in order for the screen to work? Thanks!

Add a delay at the start of your program before you initialise the display. It sounds like the display is taking a moment to charge its capacitors and become ready.

@Majenko Awesome, thanks. A 100ms delay before starting the screen solved it nicely

Adding a 100ms delay before calling oled.init(0x3c); oled.clear(); oled.startScreen(); made this problem go away.


text:
Why do I get a compiler error when I'm pretty sure I have such method?
Code
(I've omitted much of the code, and left just the outline and code probably relating to the error.)
SelfDrivingCar.ino
#include "JKMain.h"
void setup() { JKMain::setup(); }
void loop() { JKMain::loop(); }

JKMain.h
#include "JKMotors.h"
class JKMain
{
  static JKMotors motors;
public:
  static void setup();
  static void loop();
};

JKMain.cpp
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
void JKMain::loop() { }
void JKMain::setup()
{
  motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

JKMotors.h
class JKMotors
{
private:
  const int leftMotorSpeedPin;
  const int leftMotorDirectionBit1Pin;
  const int leftMotorDirectionBit2Pin;
  const int rightMotorSpeedPin;
  const int rightMotorDirectionBit1Pin;
  const int rightMotorDirectionBit2Pin;
  const int leftMotorStraightSpeed;
  const int rightMotorStraightSpeed;
  const int leftMotorTurnSpeed;
  const int rightMotorTurnSpeed;
  const int turn90Time;
  void setSideDirection(JKDirection _side, JKDirection _direction);
public:
  JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t);
};

JKMotors.cpp
#include "JKMotors.h"
#include "Arduino.h"
JKMotors::JKMotors(const int lmsp, const int lmdb1p, const int lmdb2p,
    const int rmsp, const int rmdb1p, const int rmdb2p,
    const int lmss, const int rmss, const int lmts, const int rmts, const int t90t):
      leftMotorSpeedPin(lmsp), leftMotorDirectionBit1Pin(lmdb1p), leftMotorDirectionBit2Pin(lmdb2p),
      rightMotorSpeedPin(rmsp), rightMotorDirectionBit1Pin(rmdb1p), rightMotorDirectionBit2Pin(rmdb2p),
      leftMotorStraightSpeed(lmss), rightMotorStraightSpeed(rmss), leftMotorTurnSpeed(lmts), rightMotorTurnSpeed(rmts), turn90Time(t90t)
{
  pinMode(leftMotorSpeedPin, OUTPUT);
  pinMode(leftMotorDirectionBit1Pin, OUTPUT);
  pinMode(leftMotorDirectionBit2Pin, OUTPUT);
  pinMode(rightMotorSpeedPin, OUTPUT);
  pinMode(rightMotorDirectionBit1Pin, OUTPUT);
  pinMode(rightMotorDirectionBit2Pin, OUTPUT);
}

JKPin.h
#include "Arduino.h"
struct JKPin
{
  // Ultrasonic
  static const int UltrasonicEcho = A4;
  static const int UltrasonicTrig = A5;

  // Servo
  static const int ServoSignal = 10;

  // Motor
  static const int LeftMotorSpeed = 5;
  static const int LeftMotorDirectionBit1 = 7;
  static const int LeftMotorDirectionBit2 = 6;
  static const int RightMotorSpeed = 3;
  static const int RightMotorDirectionBit1 = 8;
  static const int RightMotorDirectionBit2 = 9;
};

Notes
I wouldn't worry too much about the SelfDrivingCar.ino file. I had it "encapsulated" with JKMain.h. Also, don't concentrate on JKPins.h, as it is mostly "factual" information likely unrelated to the problem.

Error

sketch/JKMain.cpp: In static member function 'static void JKMain::setup()':
JKMain.cpp:19: error: no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'
       leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
exit status 1
no match for call to '(JKMotors) (const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&, const int&)'

Request
As far as I see, I do indeed have the constructor that the error claims I lack. What's wrong with my code?

Update
(reply to jantje)
I when removing static from motors, I receive a new error:
In file included from sketch/JKMain.cpp:1:0:

sketch/JKMain.h: In static member function 'static void JKMain::setup()':
JKMain.h:10: error: invalid use of member 'JKMain::motors' in static member function
JKMotors motors;
JKMain.cpp:16: error: from this location
motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
exit status 1
invalid use of member 'JKMain::motors' in static member function

In your question you have two of JKMain.h - is one of them supposed to be JKMain.cpp?

static JKMotors motors; why are you making a class when you appear to be planning to have a single instance of the class? A namespace might be more appropriate and less work.

By "the class", what are you referring to: JKMain or JKMotors?

I'm referring to JKMotors, since you are making a static variable motors. If you do it like that, you have to then also make a static instance of the variable at global scope.

The idea to embed both setup() and loop() with an OOP instance is good, but why not pushing the use of class JKMotors and class JKMain deeper by removing static variables and functions.
Step1 - use a JKMotors * in a non-static class JKMain:

The default constructor JKMain() is just used to initialize
  motors.

class JKMain
{
  JKMotors *motors;
public:
    JKMain() { motors = NULL; };
  void setup();
  void loop();
};

Step2 - create the motors instance in the void JKMain::setup() as proposed by @Mikael Patel

But now, the JKMotors *motors; is accessible from the non-static
  void JKMain::setup().

void JKMain::loop() { }
void JKMain::setup()
{
  motors = new JKMotors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

Step3 - declare a global JKMain instance and call setup/loop method from static setup/loop functions.

The JKMotors *motors; is now accessible from both JKMain::setup()
  and JKMain::loop()functions.

JKMain glbMain;

void setup() { glbMain.setup(); }
void loop() { glbMain.loop(); }

Nice work! That compiles OK.

I don't like static functions mixed with OOP. Enjoy C++ with your Arduino.

+1 -- Oooh. I like this way. I'll give it a checkmark once I implement it and make sure it works.

I think the problem is related to the fact motors is declared as a static member which makes it a global variable. This means the constructor can not be in the setup method.
I'm not 100% sure about the format but you need something like
#include "JKMain.h"
#include "JKPin.h"
const int leftMotorStraightSpeed = 100;
const int rightMotorStraightSpeed = 100;
const int leftMotorTurnSpeed = 150;
const int rightMotorTurnSpeed = 150;
const int turn90Time = 700;
  JKMain::motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
void JKMain::loop() { }
void JKMain::setup()
{

}

See update to my question for my reply.

void JKMain::setup()

{
  motors(JKPin::LeftMotorSpeed, JKPin::LeftMotorDirectionBit1, JKPin::LeftMotorDirectionBit2,
    JKPin::RightMotorSpeed, JKPin::RightMotorDirectionBit1, JKPin::RightMotorDirectionBit2,
    leftMotorStraightSpeed, rightMotorStraightSpeed,
    leftMotorTurnSpeed, rightMotorTurnSpeed, turn90Time);
}

You can't call a constructor like that. A constructor is either implicitly called, eg. if foo is a class:
foo bar;   // constructor for foo called

Or:
foo bar (1, 2, 3, 4);  // pass arguments to the constructor

Or even as some people do:
foo bar = foo (1, 2, 3, 4);

The last example creates a temporary instance of foo that is then copied into bar.
But what you can't do is this:
foo bar;   // make an instance of the class
bar (1, 2, 3, 4);  // call the constructor later

It's too late! The instance already exists. In your case motors is the instance of the class JKMotors. You can't call the constructor later on in the code. It doesn't make sense.

Ah, that's right. If I remember correctly, it is possible to do this if I implement operator=. Am I correct? If so, how would I implement it?

J. Piquard's answer compiles OK without needing to implement operator=. He calls new to create the instance of the class (deferred because it is now a pointer) and thus we don't need operator=.


text:
millis() vs creating a "long" variable
I think my issue is not fully understanding how the millis() function works;
I am wondering the difference between simply creating a variable such as
long fake_millis  ++ ;

vs using millis()?

millis() returns an unsigned long, not a long. It is never negative.

Besides the unsigned issue, how would you manage to do fake_millis++; exactly once per millisecond? Think about it: it's not so simple, especially if the program is busy doing other stuff. Best solution would be to do it from a timer interrupt. Once you do that, you have essentially reimplemented millis().

millis() returns the ACTUAL time milliseconds since the start of the program. Wheter you put a delay, you do multiple tasks, millis() will still return the right time.
The other method that you mentionned will not work if, for example, you add a delay in the program. Then, for more complex tasks that might take more time, your "custom" counter will be very unacurate.
I short, just use millis(). It is easy to use and works great.
P.S. Use an unsigned long instead of a long.

appreciate the response.  I am wondering though for this basic formula where i just need to have a "second" counter, http://pastebin.com/raw/hxcVukR7    could  i just replace Millis() with my method ?

@danieljay, for that simple example, maybe, but for more complex programs, stick with millis()


text:
Implementing interrupts and timers on an Arduino Uno board
I am trying to implement interrupts on an Arduino Uno board.  My goal is to synthesize waves and play them via a 3.5 mm jack.  This is what I have so far, based on some code I was provided.  I have stripped it down to a somewhat barebones version in order to isolate what is wrong.  I have the audio jack plugged in to pin 9, which is what I was told is the PWM pin for this board.  However, nothing plays out of the audio jack at all.  I would really appreciate any advice or help! :)
#include "avr/pgmspace.h"
#define NUM_OSC 1    // number of oscillators
#define MAXVOL 255   // maximum volume of each oscillator

const byte sine256[256] PROGMEM = {
  128,131,134,137,140,143,146,149,152,156,159,162,165,168,171,174,
  176,179,182,185,188,191,193,196,199,201,204,206,209,211,213,216,
  218,220,222,224,226,228,230,232,234,236,237,239,240,242,243,245,
  246,247,248,249,250,251,252,252,253,254,254,255,255,255,255,255,
  255,255,255,255,255,255,254,254,253,252,252,251,250,249,248,247,
  246,245,243,242,240,239,237,236,234,232,230,228,226,224,222,220,
  218,216,213,211,209,206,204,201,199,196,193,191,188,185,182,179,
  176,174,171,168,165,162,159,156,152,149,146,143,140,137,134,131,
  128,124,121,118,115,112,109,106,103,99, 96, 93, 90, 87, 84, 81,
  79, 76, 73, 70, 67, 64, 62, 59, 56, 54, 51, 49, 46, 44, 42, 39,
  37, 35, 33, 31, 29, 27, 25, 23, 21, 19, 18, 16, 15, 13, 12, 10,
  9,  8,  7,  6,  5,  4,  3,  3,  2,  1,  1,  0,  0,  0,  0,  0,
  0,  0,  0,  0,  0,  0,  1,  1,  2,  3,  3,  4,  5,  6,  7,  8,
  9,  10, 12, 13, 15, 16, 18, 19, 21, 23, 25, 27, 29, 31, 33, 35,
  37, 39, 42, 44, 46, 49, 51, 54, 56, 59, 62, 64, 67, 70, 73, 76,
  79, 81, 84, 87, 90, 93, 96, 99, 103,106,109,112,115,118,121,124
  };

const byte square256[256] PROGMEM = {
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,
  255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255
  };

const byte* const wave_table[] = {sine256, square256, triangle256, sawtooth256};

// information about the current state of a single oscillator
struct OscillatorState
{
   unsigned int phaseStep;  // frequency of this oscillator
   unsigned int volume;     // volume multiplier for this oscillator
   unsigned int phaseAccu;  // accumulator that steps through this oscillator
                            // high byte = current sample index
   const byte* waveform;    // which waveform
};

volatile OscillatorState oscillators;
volatile byte valOut;

//********* interrupt routines ******

// set up timer 1 to do phase correct PCM at a nominal frequency of 31372.549
void setupTimer()
{
// Timer1 Clock Prescaler to : 1, set WGM22 to zero, and WGM12,13 for phase     correct PCM
  TCCR1B = (TCCR1B & 0b11100000) | 0b00001;

// set it to clear compare match mode on both pins, and phase correct PCM     (WGM21 and WGM20)
  TCCR1A = (TCCR1A &0b00001100)| 0b10100001;

// set overflow interrupts enabled for timer 1
  TIMSK1 |= (1<<TOIE1);

  Serial.println("hello");
}

// each timer 1 overflow, set the next sample value for the PWMs
ISR(TIMER1_OVF_vect)
{

  oscillators.phaseAccu += oscillators.phaseStep;
  valOut = highByte(pgm_read_byte(oscillators.waveform +     highByte(oscillators.phaseAccu)) * oscillators.volume);

  OCR1A = valOut; // replaced ... = valOut[0];  // write to pin 9
}

unsigned int hzToPhaseStep(float frequency)
{
  float phaseStep = frequency * 2.0886902978652881446683197032183;    // (pow(2,16) * frequency) / 31376.6
  return (unsigned int)phaseStep;
}

void setup()
{
  delay(1000);
  Serial.begin(9600);
  OCR1A = 0;
  oscillators.waveform = wave_table[2];
  oscillators.phaseAccu = 0;
  setupTimer();
  oscillators.volume = 200;
  oscillators.phaseStep = hzToPhaseStep(440.00);
}

void loop()
{

}

I have the audio jack plugged in to pin 9 ... However, nothing plays out of the audio jack at all.

As you are relying on the timer changing the pin you need to make pin 9 output in setup:
 pinMode (9, OUTPUT);

When I did that I heard stuff - I wouldn't exactly call it pretty but I heard stuff.

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


text:
How do I read data from Parallel port DB25 over my Arduino?
I am using this program. However, I am getting garbage values only.
Do revert as to how can I get proper values over my arduino.
/*****************************************************************************/
* PrinterCapturePoll.ino
* ------------------
* Monitor a parallel port printer output and capture each character. Output the
* character on the USB serial port so it can be captured in a terminal program.
*
* By............: Paul Jewell
* Date..........: 29th January 2015
* Version.......: 0.1a
*-------------------------------------------------------------------------- -     ----
* Wiring Layout
* ------------ -
*
* Parallel Port Output               Arduino Input
* --------------------               ------------ -
* Name      Dir.   Pin                Name    Pin
* ----             -- -                ----    -- -
* nSTROBE    >       1..........................2
* DATA BYTE  >     2 - 9.......................3 - 10
* nACK       <      10.........................11
* BUSY       <      11.........................12
* OutofPaper <      12................GND
* Selected   <      13.................5v
* GND        <>  18 - 25................GND
*------------------------------------------------------------------------------ -
******************************************************************************** /

int nStrobe = 2;
int Data0   = 3;
int Data1   = 4;
int Data2   = 5;
int Data3   = 6;
int Data4   = 7;
int Data5   = 8;
int Data6   = 9;
int Data7   = 10;
int nAck    = 11;
int Busy    = 12;
int led     = 13; // use as status led

void setup() {
  // Configure pins
  pinMode(nStrobe, INPUT_PULLUP);
  for (int n = Data0; n < (Data7 + 1); n++)
    pinMode(n, INPUT_PULLUP);
  pinMode(nAck, OUTPUT);
  pinMode(Busy, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  while (!Serial) {
    Serial.println("Waiting to Initialise");
  }
  //State = READY;
  delay(1000);
  Serial.println("Initialised");
  delay(1000);
}

void loop() {
  while (digitalRead(nStrobe) == HIGH) {
    digitalWrite(Busy, LOW);
    digitalWrite(nAck, HIGH);
    digitalWrite(led, HIGH);
    ProcessChar();
  }
  digitalWrite(Busy, HIGH);
  digitalWrite(led, LOW);
  digitalWrite(nAck, LOW);
  delay(5); //milliseconds. Specification minimum = 5 us
}

void ProcessChar() {
  byte Char;
  Char = digitalRead(Data0) +
         (digitalRead(Data1) << 1) +
         (digitalRead(Data2) << 2) +
         (digitalRead(Data3) << 3) +
         (digitalRead(Data4) << 4) +
         (digitalRead(Data5) << 5) +
         (digitalRead(Data6) << 6) +
         (digitalRead(Data7) << 7);
  Serial.print(char(Char));
}

The ProcessChar(); command should be before the DigitalWrite(nAck,LOW);

Thanks for this one. It is storing data. But, it is storing garbage bytes only.

When I try to print the output bits in char, they show - " " . When in int, they show: "1". And, the raw data when printed, shows like: 'ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ}}xa44=wwwwwÿÿÿÿÿÿÿÿÿÿÿ' . I have set the Baud Rate: 9600, Parity: None, Data Bits: 8, Stop Bits: 1 and Hardware Control: None

Do the hard-coded messages (Waiting to Initialise and Initialised) appearing correctly?

Yes. They appear properly. And after that when I switch on my DPU, it starts giving me : ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ...  And, when I print something from it to the Printer, over the DB25 port, it shows varied symbols like }}xa44=wwwww or i#%"%0#"`iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiggggggggggf*iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiâ+¾ioig8$iig ' etc

Try changing the 'byte Char' to 'char Char'. I can see that you have done the type conversion but Serial print just spits out the ASCII value of whatever is stored as a byte which is why you maybe seeing junk values. Also try using Serial.write instead of Serial.print.

What is the data rate of your parallel port? Your Arduino will not send more than 960 bytes/s. Also, I would connect the data lines to pins A8..A15, which allows the simplification void ProcessChar() { Serial.write(PORTK); }

I meant PINK.

I think I can see the problem - although I have no way to test it.
According to Wikipedia:

When the data was ready, the host pulled the STROBE pin low, to 0 V. The printer responded by pulling the BUSY line high, printing the character, and then returning BUSY to low again.

That's not what you're doing - you are repeatedly reading while the strobe is HIGH.
Here's my attempt at your loop() which I hope will at least get you started:
void loop()
{
    // Wait for strobe to go LOW, indicating a character is ready
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };

    // Strobe is now LOW - a character is ready.
    // Pull BUSY to high
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, HIGH);
    digitalWrite(led, LOW);
    digitalWrite(nAck,LOW);

    // Print the character
    ProcessChar();

    // Return BUSY to low again
    // (NB: I don't know what you're doing with nAct and led)
    digitalWrite(Busy, LOW);
    digitalWrite(led, HIGH);
    digitalWrite(nAck,HIGH);

    // Wait for the strobe to go HIGH again
    while (digitalRead(nStrobe) == LOW) {
        delay(1)
    };
}

You should also probably consider setting the initial values of your outputs (BUSY and nAck) rather than relying on them defaulting to some particular state.  I don't know what (n)Ack is for in this case -- Wikipedia doesn't mention it.

Do you know the printer is working properly?
You are trying to fix more than one thing at once and that's never a good idea.  What I suggest you do is get a breadboard and make your own printer simulator.  You need to connect and LED up to every output pin and a button to every input pin.
Then you can simulate data from the printer, i.e. just pressing the button for pin 3 and you should see 1 coming out on the serial monitor.  OK I agree this "simulator" is rubbish, but you probably have the bits to knock it up now.
If you are still seeing 'junk' values then have a look and see if there is a pattern to the data.  This would be helped by printing the values in hex.
Of course if the Arduino side works then the issue is that the printer is sending data that you are not expecting.  It might help stick LEDs on every pin, both directions, it will help you see what is being sent.
Its possible that you are expecting 1 to indicate the bit is set and the printer is using 0.


text:
IDE avoiding math operation
I have no idea why this has been happening:
byte potenciometro = 0;int redpin=9;

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

void loop() {
int valor=analogRead(potenciometro);  delay(50);
Serial.println();
Serial.print(valor, DEC);

analogWrite(redpin,valor);   }

This code above has been working just fine. However, i understand the LEDs will work properly with intensities that range from 1 to 255, so i replaced this line
Serial.print(valor, DEC);

for this
    Serial.print((valor/700)*255, DEC);
and all that the IDE has been returning since then is 0 as console output.
i tried also just
Serial.print(valor/700, DEC);

and i get nothing but 0s
anyone?
my arduino is the UNO version.

Why are you dividing the value by 700? The potentiometer is not connected between GND and 5V (I suppose 3.3V)? If you have full scale values (0..1023) it's possible just divide the value by 4 to get result between 0 and 255.

In the C family of programming languages, the division operator (/),
when used with integer arguments, provides an integer division. You
get the integer quotient, and you can use % to get the remainder.
If you want a floating point division, then at least one of the
arguments should be a floating point number. E.g.:
Serial.print(valor / 700.0 * 255);

(the DEC argument is redundant). The final result is then truncated to
an integer before being passed to Serial.print().
A better option, which is outlined in dhimaspw's answer, is to do the
multiplication before the division. This way you avoid costly floating
point operations. If you do that, however, you should be careful about
overflows: valor*255 can be as big as 1023 × 255
= 260865, which is larger than the maximum value an int can store
(215−1 = 32767). You should then write
Serial.print(valor * 255L / 700);

where the L suffix forces the operation to be carried using long
integers.
The simplest solution, however, is to use the Arduino function map(),
which does essentially the same as above:
Serial.print(map(valor, 0, 700, 0, 255));

Serial.print(valor / 700.0f * 255); would work better. 700.0 is a double not a float and so by the rules of the c language that entire calculation is done as doubles. Adding that f in turns it into a float. On a low end microcontroller you really want to avoid doubles as much as possible, double operations are twice as slow as a floats and floats are slow enough already.

@Andrew: The OP is working on an Uno. A double is the same as a float on the AVRs.

That in this particular case the standards aren't followed and so it doesn't make a difference isn't a good justification for inefficient coding. Pressing 1 extra key is a small price for a good habit and portable efficient code.

Not meaning to nitpick but I'd just point out that mapping floats to doubles on the UNO is a software choice implemented in the gnu compilers, not hardware-driven at all as the hardware has no support for floating point. A different tool-set might well implement a different choice. So could a programmer using gnu for that matter, by defining an 'sfloat' (small- or single-precision float) object and its arithmetic operators.

Using Serial.print (xx,DEC) will give you a number on decimal base (round number). That's why your first code works
To solve this, you just simply change to
Serial.print((valor*255/700),4) //4 digits behind comma

i tried adding this before the analogWrite
valor=((valor*255/700),4);
but the intensity of the led remains fixed

AnalogWrite only receive round numbers.

This solution overflows for values over the 128 (analog read returns values 0..1023) and it doesn't really explain why valor/700 is zero or one if the value is greater or equals to 700


text:
RF24Mesh master-base node communication delay
I'm trying to build a mesh network using 4 nRF24L01 modules directly connected with Arduino Uno where 1 module is master node and the rest are base nodes.
The workflow is exactly as follows
I'm sending a command in the Arduino IDE serial monitor. The master node receives this command and send it to other base nodes. There's no problem receiving the command on the base node side (from master node) as well as sending the command on the master node side (to base nodes). Upon receiving the command from the master node, base nodes successfully able to read the command and send the response. No problem at all.
But when the master node receives the response status from the base node(s), there's the problem. Master node is not receiving the data immediately. I have to send the command from the Arduino serial monitor repeatedly and on the 10th time, the master node is able to read the response status from the base node(s). Exactly on the 10th times every time.
Here's the source.
master node
// global variables
int dat2;
String temp1 = "";
boolean actualDataSent = false;

// get input from arduino serial monitor

 while (Serial.available() > 0) {
      // my command
      String temp1 = Serial.readString();
}

// write block
if (actualDataSent == false && temp1 != "") {

    // send this data to the base node one by one char
    for (int j = 0; j < mesh.addrListTop; j++)
    {
      for (int k = 0; k < temp1.length(); k++) {
        char ch = (char)temp1.charAt(k);
        Serial.print("NodeID: ");
        Serial.print(mesh.addrList[j].nodeID);
        Serial.print(" RF24Network Address: 0");
        Serial.println(mesh.addrList[j].address, OCT);
        RF24NetworkHeader header(mesh.addrList[j].address, OCT);
        Serial.println( network.write(header, &ch, sizeof(ch)) == 1 ? F("Send OK") : F("Send Fail"));
      }
      actualDataSent = true;
    }
    temp1 = "";
  }

// read block
else if (network.available() && actualDataSent == true) {
    RF24NetworkHeader header;
    network.peek(header);

    switch (header.type) {
      case 'M':
        network.read(header, &dat2, sizeof(dat2));
        Serial.print("Got: ");
        Serial.print(dat2);
        Serial.print(" from RF24Network address 0");
        Serial.println(header.from_node, OCT);
        actualDataSent = false;
        break;
      default: network.read(header, 0, 0); Serial.print("Not M case"); Serial.println(header.type); actualDataSent = false; break;
    }
  }

base node:
//global variables

String mypayload = "";
int res1;

// receive command from master
while (network.available()) {
    RF24NetworkHeader header;
    network.read(header, &payload, sizeof(payload));
    mypayload.concat(payload);
  }
  if (mypayload != "")
  {
    Serial.print("Received data: ");
    Serial.println(mypayload);
    if ((mypayload == "100%"))
    {
      res1 = 1;
      Serial.println("Turn ON");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    else if (mypayload == "0%")
    {
      res1 = '1';
      Serial.println("Turn OFF");
      if (!mesh.write(&res1, 'M', sizeof(res1))) {
      if ( ! mesh.checkConnection() ) {
        Serial.println("Renewing Address");
        mesh.renewAddress();
      } else {
        Serial.println("Send fail, Test OK");
      }
    } else {
      Serial.print("Send OK: "); Serial.println(res1);
    }
    }
    mypayload = "";
  }

What output are you getting on the terminal (on the base node) for tries 1 .. 9 ?

@KennetRunner - on base node's terminal the output is always same i.e. send is OK. Apparently it seems that there's no problem at the base node. The problem is only at the master node, I suppose. But the question is why the desired status would come on the 10th time?

You wrote res1 = 1 and res1 = '1'. What is it? And int or a char. What libraries are you using? Post your complete sketch.

The nRF24L01 "ACK_PAYLOAD" feature allows for two-way data transfer in a single radio transaction.  This is more complicated to set up but plenty of tutorials can be found online, on arduino stackexchange and of course another very helpful source is the nRF24L01 data sheet.  This should solve your problem by ensuring the master/slave radio messages are sent in the same, rather than independent, radio transactions.

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


text:
Using an Arduino for a Diorama Controller
Kind of new to the whole DIY electronics scene.
I'm building a diorama for my son.  It will include a length of track, a station, some other buildings, and scenery.  It will be HO scale.  The buildings came with these cool little LED lights and I've bought additional ones as well.  I want it to be of the period of the late 1800s to early 1900s.  So the additional LEDs I bought give off a more "yellow" light to simulate candle/lantern light.  The track is not a circuit and is not powered.  It is just "static" to sit a train so it appears to be at the station.
I have the following questions:

Could I hook up the LEDs to a Arduino and have the different buildings (or floors within a building) be controlled separately?
Could I make the LEDs "flicker" to simulate candle/lantern light?
Could I maybe hook up a little speaker inside the train station to give off train noises, whistles, conductor calls, etc?
Could this setup (Arduino with LEDs/speaker) be run off of batter power (not a custom battery, just off the shelf AAs, AAAs, or Cs, etc.)?
Is an Arduino instead the appropriate controller for this kind of project?

I think this is a great opportunity to teach my kids not only modeling but also electronics (myself as well on the electronics).
Thanks in advance for any help/suggestions.
EDIT:
A little more about the setup.  The LEDs are made specifically for this type of application (model buildings/railroads).  Hence, they already have an 1800 ohm resistor attached to the input side of the LED.  There will indeed be multiple LEDs per building (even per floor).  I would like to at least isolate the circuits by building and even better if I could isolate them by floor.  I think it would be cool to have the software cycle the buildings/floors on and off at different times.
A smaller form factor for the Arduino would be ideal as it will have to fit into one of the scale buildings.  I've never really worked with the Arduino so I don't know all my options.  I've done a little with the Raspberry Pi and originally posted this question there and was told the Raspberry Pi would be overkill for this type of application.

Yes, but use a compact one, like the Arduino Nano or Pro Mini. I'm not sure how many battery life you will get, but I can't think of anything more appropriate as Arduino.

Arduino itself doesn't really have good audio capabilities, but there is an "SD card audio mp3 shield" in adafruit, that can be triggered easily

The Arduino can safely output 20 mA per IO pin, so you may power about ten 1.8 kΩ LEDs per pin without a transistor. But beware of the 100 mA limit per pin group (two groups: pins 5 — 13, all other pins). The LEDs are likely to consume more power than, say, an Arduino Nano, so this will likely be the limiting factor for battery life.

Thanks everyone for all the great feedback.  I hope to provide a status to this post when I make some progress.  It could be a while though.  I got to build the actual building first.

@EdgarBonet Can you further explain what you mean by "pin group"?

See the datasheet of the ATmega328P, the small notes below table 30–1. Each one of these two groups can source up to 150 mA: (5 — 13), (0 – 4, A0 – A5). Each one of these three groups can sink up to 100 mA: (0 – 4), (5 – 13), (A0 – A5). The entire chip cannot source nor sink more than 200 mA (see Absolute Maximum Ratings).

First, since you didn't mention any kind of Arduino, my answer is based on using Arduino Uno/Nano (I think its the most common)
 1. Yes you can. You use 1 transistor per building as switch (if there are many LEDs in the building) to gives optimal current and prevent your Arduino pin. The value of R2 -- Rx is depend the LED colour. You can control each group with one Arduino pin.

simulate this circuit – Schematic created using CircuitLab

Yes you can, one in my mind is using PWM feature, like this project
Yes you can. But maybe the generated sound is not up to your expectation. Here is one of the simple example and this maybe a bit challenging.
The battery is up to your setup. More output (such as led and speaker) requires power source that can provide greater current. Arduino Uno voltage limit is 6v-20v
In my opinion, yes.

As for the form factor, I think Arduino Nano is small enough to hide in the building, while Arduino Uno size is just slightly less than a Raspberry Pi.
Good luck for your project :)

The Arduino Nano is essentially the same, but in another form factor, this this answer also applies for the Nano.

Please don't use a single resistor for multiple leds. One resistor for each led. For yellow leds you probably need a higher value resistor. Also R1 shouldn't be 100 Ohms, as that would result in 44mA of base-emitor current, which if a bit over the maximum rating of an Arduino pin. Use something like 1000 Ohm (i.e. 1 kOhm).

Thanks for this help everybody.  I failed to mention that the LEDs are specifically built for model buildings and they each have an 1800 ohm resistor already attached.  I'll update the original post.  This may change this answer a little.  But I like the info I'm getting so far.

@dhimaspw Thanks for the link to CircuitLab.  That's a pretty cool online application that I had no clue existed.

@Gerben thanks for the correction. Just asking, how if all the LED are the same colour? should it also use multiple resistor? *ps : I forget to edit the resistance value, but thanks.

@dhimaspw If the are all the same you might be able use a single resistor. But even then different batches of the same led could have slightly different forward voltages resulting in one led drawing more current than the other. This is more a problem if you trying to run the leds at their maximum. Also if one led fails the rest will have to handle the extra current and fail shortly after. Resistors are cheap. Just use one per led.

@Gerben Thanks for the info.  I updated my original post.  All the LEDs are the same color and they already come with an 1.8 KΩ resistor attached, so I think that aspect is taken care of.

The only point would be that all LED's would go on/off at the same time. It would be weird if all the candles on the station would be in sync :p But that would be an easy fix, but keep it in mind while building.


text:
Getting different results from function. How to retrieve values correctly?
Trying to implement PI controller in function.
Already worked for one controller.
However, for more than one controller, the results are shifting.
Suppose to get same values in the following code.
Any help I appreciate it.
float r_in_1 = 10.00;
float y_out_1 = 5.00;

float r_in_2 = 10.00;
float y_out_2 = 5.00;

float r_o_1;
float y_o_1;

float r_o_2;
float y_o_2;

float vi_1 = 0;
float vi_2 = 0;

void setup() {

 Serial.begin(9600);

  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

r_o_1 = pow_2(r_in_1);

r_o_2 = pow_2(r_in_2);

y_o_1 = pow_2(y_out_1);

y_o_2 = pow_2(y_out_2);

vi_1 = PI_1(r_o_1, y_o_1);
vi_2 = PI_1(r_o_2, y_o_2);

Serial.print(vi_1);
Serial.print(',');
Serial.println(vi_2);
delay(1000);

}

float pow_2(float x){

float z;

z = x*x;

return z;

}

float PI_1(float r, float y){

float e;
static float sum_e=0;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e =  sum_e + e;
vi = kp * e + ki * sum_e;

return vi;
}

What do you mean by 'more than one controller'? Please be detailed about what you are trying to achieve, and what is wrong the current result

The current result should become same value for vi_1 and vi_2. But it is shifting.

I mean when I comment out one of those  vi_1 = PI_1(r_o_1, y_o_1); or
vi_2 = PI_1(r_o_2, y_o_2); it is working fine. But when both of them are executing the result are shifting.

what is your current result? I am a bit confused by "shifting". Edit your question, add the result you got.

Ok, what I suppose to get is this  (vi_1,vi_2) is what I get in serial monitor. (900,900), (1650,1650), (2400,2400) ,(3150,3150), (3900,3900)

However, I am getting these (900,1650), (2400,3150), (3900,4650)

You see that  values are shifting, but they actually should  be identical.

Zalt, please edit the question to include that additional information, instead of just putting it in throwaway comments.

The problem is you declare static float sum_e in PI_1 function. The value of will increase everytime PI_1 function is called. In 1 loop, you call PI_1 two times, resulting first call always smaller than second call because of the value of sum_e. Sum of error should be declared as global variable, and each controller has its own "sum" variable.
Declare as global :
float sum_e[100]; //for 100 controller.

Your function
float PI_1(float r, float y,int number){

float e;
float vi;
float kp=2.00;
float ki=10.00;

e = r - y;
sum_e[number] =  sum_e[number] + e;    //integrator for controller number
vi = kp * e + ki * sum_e[number];

return vi;
    }

function call
vi_1 = PI_1(r_o_1, y_o_1,1);
vi_2 = PI_1(r_o_2, y_o_2,2);

Here is the rough example. There are lot more efficient ways than this, but this should gives you some idea. You can reduce the code yourself since the values should be correct already.

If I remove static then the integrator term will not work. I mean it just prints same values constantly.

I edit my answer

what I want to do is to reduce the code.

I would like to have only one PI function. As the matter of fact  i have more controllers.

use array. you can also use it for other variables like r_o y_o vi_ etc.

A PI controller has “state”: it has to remember the sum of all the
previous errors. If you want several controllers you have to
independently store the state of each one.
The traditional solution used by C programmers is to write a controller
function that takes an extra parameter which is a pointer to the state.
In C++ you can use a reference instead:
// PI controller.
float PIController(float &sum, float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

You would use it like this:
void loop()
{
    static float sum_1, sum_2;  // State of the controllers.
    // ...
    vi_1 = PIController(sum_1, r_o_1, y_o_1);
    vi_2 = PIController(sum_2, r_o_1, y_o_1);
}

The C++ language provides a nicer way of writing the same thing: you can
use a class to wrap the state and the controlling method together under
the same name:
// PI controller.
class PIController {
public:
    PIController() : sum(0) {}
    float operator()(float r, float y);
private:
    float sum;
};

float PIController::operator()(float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

Which you would use like this:
void loop()
{
    static PIController pi_1, pi_2;  // Controller instances.
    // ...
    vi_1 = pi_1(r_o_1, y_o_1);
    vi_2 = pi_2(r_o_1, y_o_1);
}

The generated assembly should not be much different. Note that in both
cases the static variables of loop() could be globals if you prefer.

authors: พงศ์พล วิภาสุรมณฑล


text:
Very strange power supply problem
So, I've put together my Christmas tree lights - a string of WS2811s driven by my Uno board. They are 12 volt WS2811s, so I have rigged a 12 volt supply to them and just using the Uno for the data channel, powered, initially by the USB port of the PC. So far, so good.
Then I take the whole arrangement to the tree and try to power the Uno from a USB charger - but that's where it all goes wrong! The LEDS start to flash madly, nothing like the pattern that I've programmed.
I've tried various USB chargers and various USB cables to no avail, I've tried powering with 6 volts to the DC in socket - same thing. When I go back to the PC and pick up the Uno power from the USB cable, all is good! I have no idea what can be causing this, please help!

Garbage chargers. Did you try powering the Uno from the 12V supply as well?

Also, 6V is out of spec for Vin.

If I don't get  an answer from here, I will try putting the 12 volt supply to the Uno too - but that will require soldering that  don't want to do if I can avoid it.

The chargers are actually very good quality ones - from an HTC phone and a Sony phone. Do you think the voltage could be too HIGH rather than too low?

I found a page on arduino.cc which said I could supply up to 20 volts to  the DC in - so I thought 6 volts would be fine.

You are using two different power supplies?  (PC + 12V or USB Charger + 12V)
Have you connected the grounds from the two power supplies?

@Gerben The power supply has been working perfectly well during all of my development - and will work again now if I power the Uno from the PC, so I don't think there's an issue there....?

@Matt I have NOT connected the 2 grounds and I was a bit worried about that - but again, it works fine with the PC. Do you have reason to believe it should be necessary?

Yes its necessary.  The fact that it worked with the PC confused me.

@Matt That worked! Thank you very much! This is one of those times when I have to just accept that I'll never really understand some of these subtle things that can happen with things like ground lines. If you want to enter this as an answer I will happily upvote and mark this as accepted.

@Matt most PCs have GND referenced to EARTH. If the power supply too, has it's ground referenced to earth, both grounds are effectively tied together (via the earth). Most phone chargers are isolated.

@Lefty I have written a blog post about the importance of linking the grounds together - why you do it, what happens, and what it means to your circuit: https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

@Majenko Thank you, I read your blog and I mostly understand it - the main problem I have is understanding how the grounds are connected through the mains of the house given the nature of the step-down transformers that are powering both my 12 volt side and my 5 volt side. There is no sense in which the grounds are even connected to the 240 volt supply at all!

...They are actually both connected to coils which are in the presence of other coils that have one side of their AC supply connected together through the earth. This is where it needs explaining for me.

@Matt - you should turn your comment into an answer, as it is the correct solution to the OP's issue

[Turning my comment and other peoples replies into an answer to make it easier to read]
You are using two different power supplies? (PC + 12V or USB Charger + 12V) Have you connected the grounds from the two power supplies?
I have a limited understanding of why, but I know that unless the two power supplies have a common ground level the values for 0V and 5V may not be the same across the two feeds and you get odd and unpredictable behaviour.
Gerban explained that the reason it works on your PC is that most PC Power supplies reference Gnd from the Earth.  If you 12V supply is an ex-PC PSU, or similar, that will be doing the same which is why that setup works, they share a common ground via the mains earth.  The 5V phone charge probably has a plastic earth pin, which means it doesn't do this and therefore the Gnds are not tied to each other.
Majenko's blog will provide a more detailed, less hand wavey explanation:
https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

The Arduino Uno barrel jack input connects to a linear 5 volt regulator.  These types of regulators require a several volt difference between the input and output.  So you need to supply 5 volts + several more volts or at least 7 volts at the barrel jack.
From the Arduino Uno web page:

The board can operate on an external supply from 6 to 20 volts. If
  supplied with less than 7V, however, the 5V pin may supply less than
  five volts and the board may become unstable. If using more than 12V,
  the voltage regulator may overheat and damage the board. The
  recommended range is 7 to 12 volts.

Good theory - I assumed this myself when I first saw the behaviour I was getting - but the Sony USB charger I tried next is the highest power one I have - I once used it to power the Uno AND 100 5 volt WS2811s drawing about 2 amps between them.

I deleted the part of my answer concerning a power supply as I re-read your question and am not clear on how you connected everything together.  From my understanding, are you using 2 power supplies?  One for the LEDs and one for the Arduino?  And is the Arduino power supply a USB power supply connected to the Arduino's USB port?  And is the ground of the Arduino connected to the ground of the LED strip?

Also, are you sure WS2811 are 12 volt parts?

I've been using 5 volt WS2811s most of the time, powering them direct from the Uno, the Uno was, in turn just powered from the USB cable from the PC. I found that having even 100 in a string meant that I couldn't get power from 1 end to the other. I got a string of 200 12 volt ones and, obviously needed to power them from an external source. I wired a 12 volt laptop supply to the + and - of the string but leaving the rest as it was - i.e. USB to Uno, data channel from Uno to string AND NO OTHER CONNECTION to Uno. That worked fine...

...so I thought I would be able to just power the Uno from a USB charger and all would be OK - but then hit the problem exactly as I have described in the question. So it seems that from Gerben's comment at the top, the PC worked fine because its ground was connected through the mains power to the ground of the 12 volt supply - but when I used an   isolated USB charger, this broke the connection between the 2 grounds. When I now connect the ground from the 12 volt line to the ground of the Uno, the problem goes away.

Thanks for answering my questions.  I'm glad it worked out for you.  However, you should avoid assuming if a power supply is floating or connected to earth.  Certain situations can result in ground loops.  Think about what would happen if the ground of the LEDs were, say, 20 volts different than the ground of the Arduino. Something would almost certainly blow out.  I'm saying this because I don't want you to think it is normal to go back to your PC and not connect the grounds.

I'm afraid the whole concept of ground is something that I still have trouble with. I will have to do some research I think. I tend to just try these things and see what works - which is why I get confused when it works - then doesn't!


text:
Update custom library
I've recently made a custom library. Then, I've imported the library into the IDE via the add .zip library. Once I tried to compile the code, I've realised that I made a small typo. Once I changed the error and then retried to compile the code, the error still appeirs and I'm quite sure that I've changed it.
So my guess is that the library is not updating. I've tried to go to manage library and then seeing if there is an other version of the library. There wasn't any.
So is there an easy fix to this solution that doesn't involve updating or downgrading the IDE?

I've never used that option but normally you just need to delete the compiled files in the library.  So assuming they aren't in the zip file, are they somewhere in you profile's temp directory?

I actually found this answer on Stack Overflow.

In the Arduino GUI on windows, if I click on Sketch --> Import Library, at the bottom of the menu there is a section called "Contributed".
Unfortunately, I had misclicked and added a library I did not want to that list.
How can I remove it from that list?
The help page only mentions that "If a sketch no longer needs a library, simply delete its #include statements from the top of your code" but it does not mention how to remove the library from the list of contributed libraries.

By : @merlin2011 from Stack Overflow.

Text from here says this:

In Arduino v16 and earlier, libraries were stored in the
  ArduinoInstallDirectory/hardware/libraries folder, which also
  contained all the built-in libraries (like Wire and Serial).
In v17 and up, the user libraries are now stored in the
  ArduinoSketchDirectory/libraries folder.

Check your version of the Arduino SDK and then look in the appropriate directory for your library source code.  Then change it there.
The Arduino SDK is fairly simple and often compiles everything to avoid problems like this.  The installing from a zip file feature (unless it has changed) is more for convenience when downloading a single zip file.  I have often developed & edited custom library source code where the SDK expects to find it.

Thanks, but I'm using the IDE from Arduino.cc and not the one from Arduino.org.

If you could elaborate what difference that would make I would appreciate it.  I would learn something and possibly make the answer better.

Also, you might check the time stamp on your source files to make sure they are newer than the compiled files.

I there is no real difference except that the .org version is all orange compared to the more user friendly .cc. No real diferrences. 1.7 is the latest of .org. I believe and it hasn't changed much. .cc` on the other hand has regular IDE updates. Heck, one just got released around 2 weeks ago. Its IDE version 1.6.13.


text:
Interfacing IMU and GPS with Arduino
I am using an Arduino UNO board and trying to interface IMU sensor (GY-521) and GPS sensor (Ublox Neo-6M) at the same time. The connections of the IMU and GPS are as follows
IMU to Arduino:
Vcc --> 5V
Gnd --> Gnd
SDA --> A4
SCL --> A5
INT --> D2
GPS to Arduino:
Vcc --> 5V
Gnd --> Gnd
Tx --> Rx
Rx --> Tx
Now when I used the IMU sensor alone and tested it with the Jeff Rowberg library, it was working fine. But as soon as I make the connections with the GPS and upload a program, the IDE gives the following error:
Arduino: 1.7.10 (Windows 7), Board: "Arduino Uno"

Build options changed, rebuilding all

Sketch uses 3,970 bytes (12%) of program storage space. Maximum is 32,256 bytes.

Global variables use 313 bytes (15%) of dynamic memory, leaving 1,735 bytes for local variables. Maximum is 2,048 bytes.

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xa5

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xa5

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

I can't seem to spot the problem. Kindly help me out as I am new to the Arduino development. Thanks.

Remove the GPS from RX/TX during the sketch upload. It is confusing the USB connection. The alternative is to use SoftwareSerial for the GPS.
Cheers!

Not enough to comment yet, but to add Mikael Patel's answer, using Software Serial  might help here to take the gps off the Arduino's serial lines


text:
Arduino USB Host Shield with joystick
I'm building my own quadcopter and going to use an Arduino for this. An Arduino Micro for the quadcopter and an Arduino UNO for the controller. I want to use an USB host shield with a Logitech Extreme 3D Pro to control the quadcopter.
I have the joystick already working with de example from the USB host shield example, but I can't get the values to my void loop(). There is not much information on the internet about this.
The link to the library and example I'm using: https://github.com/felis/USB_Host_Shield_2.0/tree/master/examples/HID/le3dp
.INO file:
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    Usb.Task();
}

.cpp file:
#include "le3dp_rptparser.h"

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

.h file:
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <hid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

So I hope that someone can give me a solution how I can get the value out of the code below (I changed the code a bit, so that I get decimal values) into the void loop().
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    Serial.print(evt->x);
    Serial.print("\t Y: ");
    Serial.print(evt->y);
    Serial.print("\t Hat Switch: ");
    Serial.print(evt->hat);
    Serial.print("\t Twist: ");
    Serial.print(evt->twist);
    Serial.print("\t Slider: ");
    Serial.print(evt->slider);
    Serial.print("\t Buttons A: ");
    Serial.print(evt->buttons_a);
    Serial.print("\t Buttons B: ");
    Serial.print(evt->buttons_b);
    Serial.println("");
}

I've some experience with Arduino programming but not much.
Please ask me if you need more information.

The following assumes you are seeing OnGamePadChanged being called.
One way you could get the values you want (GamePadEventData *evt) into the loop() would be to add a member variable to the JoystickEvents class, so that class would become something like
class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
    static GamePadEventData mostRecentEvent;
};

In OnGamePadChanged, make a copy of evt:
GamePadEventData JoystickEvents::mostRecentEvent;
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    mostReventEvent = *evt;
}

Now you can read it from loop() using something like
Serial.print("X: ");
Serial.print(JoystickEvents::mostReventEvent.x);

A significant limitation of this method is that it will only keep the most recent event.  Maybe that's OK for your purpose.
It's probably not quite what the author of that code had in mind: he probably expected you to do the work in OnGamePadChanged: his implementation of that method looks like an example so you can see how it works.

I got it working a few minutes ago in a bit different way. I will post my way as an anwer so other people can find and use it. I'm also going to try it your way so I can learn from it. Thank you!

I've tried it but I get an error which says: base operand of ' ->' has non-pointer type 'GamePadEventData'. Do you know what I did wrong?

My typo, now fixed. I used -> instead of .. The former is used if you have a pointer to an object, the latter is you have the object itself. (In future it would be useful to indicate the line where the error occurred.)

Sorry, my bad. I got it working right now. Thank you very much!

After trying some other things I came up with the following idea:
I moved this piece of code from the .cpp file to the .INO file:
void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
    Serial.print("X: ");
    PrintHex<uint16_t>(evt->x, 0x80);
    Serial.print(" Y: ");
    PrintHex<uint16_t>(evt->y, 0x80);
    Serial.print(" Hat Switch: ");
    PrintHex<uint8_t>(evt->hat, 0x80);
    Serial.print(" Twist: ");
    PrintHex<uint8_t>(evt->twist, 0x80);
    Serial.print(" Slider: ");
    PrintHex<uint8_t>(evt->slider, 0x80);
    Serial.print(" Buttons A: ");
    PrintHex<uint8_t>(evt->buttons_a, 0x80);
    Serial.print(" Buttons B: ");
    PrintHex<uint8_t>(evt->buttons_b, 0x80);
    Serial.println("");
}

After I changed some of the code in the .INO file the code looks like this:
/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */

#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>

#include "le3dp_rptparser.h"

int joyX = 512;       // min: 0 | max: 1023 | center: 512
int joyY = 512;       // min: 0 | max: 1023 | center: 512
int joyHat = 8;       // up: 0 | right-up: 1 | right: 2 | right-down: 3 | down: 4 | left-down: 5 | left: 6 | left-up: 7 | center: 8
int joyTwist = 128;   // min: 0 | max: 255 | center: 128
int joySlider = 0;    // min: 0 | max: 255
int joyButtonsA = 0;
int joyButtonsB = 0;

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1)
      Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );
}

void loop()
{
    //Print all the values into the serial monitor:
    Usb.Task();
    Serial.print("X: ");
    Serial.print(joyX);
    Serial.print("\t Y: ");
    Serial.print(joyY);
    Serial.print("\t Hat: ");
    Serial.print(joyHat);
    Serial.print("\t Twist: ");
    Serial.print(joyTwist);
    Serial.print("\t Slider: ");
    Serial.print(joySlider);
    Serial.print("\t Buttons A: ");
    Serial.print(joyButtonsA);
    Serial.print("\t Buttons B: ");
    Serial.println(joyButtonsB);
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  //Put the values from the joystick in another variable:
  joyX = evt->x;
  joyY = evt->y;
  joyHat = evt->hat;
  joyTwist = evt->twist;
  joySlider = evt->slider;
  joyButtonsA = evt->buttons_a;
  joyButtonsB = evt->buttons_b;
}

It works very good for me and I'm now able to send the values to another Arduino with the nRF24L01+.


text:
Arduino Uno: how to increase distance of serial communication to PC
Does Arduino Uno's serial communication to  PC has the same distance as USB communication? (if I'm not mistaken 5m) If it is, what are the options for me to be able to communicate from Arduino Uno to PC with a longer distance? Thank you for any help!

One alternative is to use a Bluetooth module.

There are many options of varying complexities, pros, cons and prices.
The simplest method is to use powered USB hubs to extend the range. It's 5m per run of cable between powered hubs, so if you have access to power at 5m intervals (or can provide power at 5m intervals) you can chain hubs together to increase your distance. That rapidly becomes unwieldy and expensive though.
Assuming you want to keep the ability to directly program your Arduino from the PC without having to mess with swapping cables around, etc, other options include:

USB over CAT5 adapters (up to 100m length)
Bypass the USB altogether and use RS-232 (MAX-232 chips, about 15m length)

There are also some bluetooth adaptors that allow programming of the Arduino, but that gets a bit tricky.
If you're not too worried about programming there are far more options:

Radio options, such as using XBees, nRF24L01 modules, etc.
Networking - connect to an Ethernet or WiFi network
GSM modem
RS-485 / RS-422 - similar to RS-232 but longer distance, and without the signals needed for rebooting the Arduino for programming

The "distance" of the fully networked options is, literally, global. Once on a network you have the option of arranging access from anywhere on the globe with an internet connection
It all depends, really, on what you want to be able to do over the connection.
(I am sure there are many more options I have forgotten - feel free to suggest them in comments, or even go ahead and edit this answer to add them if you like.)

Thank you for such comprehensive answer! I find the USB over CAT5 adapters more appropriate to what I'm trying to do, since I'm trying on sticking to wired and don't really know how to use rs232 communication for arduino and USB hubs are expensive. When you mean USB over CAT5 adapters is this what you mean? If I'm going to use this, will the power from my computer's usb enough?

I can't tell from that image. If it is the same as this then yes - up to 50m or something. Note that you (usually) need to power the Arduino separately.

oops sorry, yes the image I sent is the same as that. Ok noted, thanks for your help! now I gained hope in finishing my project


text:
How to use potentiometer data from slave to master Arduino?
I'm trying to make a game where i can use one Arduino as a controller (the controller is a potentiometer) and the other Arduino sending the signals to the computer. Im trying to figure out communication with two Arduino's so i would like to use two instead of one although using one would be logical and easier. Ive tried looking into I2C but cant seem to figure it out.

Why are you using 2 Arduinos? You could do all of this in just one Arduino.

Please also improve the formatting of your question.

Start by reading the potentiometer. Add a Wire request service function and that makes the Slave:
#include <Wire.h>

const uint8_t controllerAddress = 8;
const int controllerPin = A0;
volatile int controllerValue = 0;

void setup() {
  Wire.begin(controllerAddress);
  Wire.onRequest(requestEvent);
}

void loop() {
  int value = analogRead(controllerPin);
  noInterrupts();
    controllerValue = value;
  interrupts();
}

void requestEvent() {
  Wire.write((const uint8_t*) &controllerValue, sizeof(controllerValue));
}

This is minor update of the Arduino Wire Master Reader tutorial. The sketch for the Master is left as an exercise.
Cheers!

I would assign 'A0' to controllerPin instead of '0', to avoid any confusing with digital pins: const int controllerPin = A0;

Nice catch. I will fix that.