text:
IR Receiver interrupt and arduino sleep mode
I need to put my arduino into the sleep mode in order to consume less power. My arduino receives IR data and do some work with it, but I need to make it sleep until there is no data. If the data has appeared it should wake up and do something with data and go back to sleep mode.
Is there any way to do this.
I would be grateful for any help.

Is this the IRLib library from http://playground.arduino.cc/Main/IRLib ?

Actually I didn't know it that one. I use an adaptation of Ken Shirriff library made by Chris Young. Is very generic I found it in a lot of examples.

More info can be found at this stack exchange http://arduino.stackexchange.com/questions/6753/choosing-right-sleep-state/6755#6755

This is what I have managed to achieve ...

Library
IRLib - GitHub

Version 1.51 March 2015
  Copyright 2013-2015 by Chris Young http://tech.cyborg5.com/irlib/
This library is a major rewrite of IRemote by Ken Shirriff which was covered by GNU LESSER GENERAL PUBLIC LICENSE ...

Code
Modified code (from the demo IRrecord example):
/* Example program for from IRLib – an Arduino library for infrared encoding and decoding
 * Version 1.5  June 2014
 * Copyright 2014 by Chris Young http://cyborg5.com
 * Based on original example sketch for IRremote library
 * Version 0.11 September, 2009
 * Copyright 2009 Ken Shirriff
 * http://www.righto.com/
 */

/*
 * IRrecord: records IR signals
 * An IR detector/demodulator must be connected to the input RECV_PIN.
 * Record a value by pointing your remote at the device
 */

#include <IRLib.h>
#include <avr/sleep.h>
#include <avr/power.h>

const byte LED_PIN = 8;
const byte RECV_PIN = 11;
const unsigned long BAUD_RATE = 115200;
const unsigned long NO_ACTIVITY_TIMEOUT = 2000;  // milliseconds

IRrecv My_Receiver(RECV_PIN);
IRdecode My_Decoder;
IRsend My_Sender;
/*
 * Because this version of the library separated the receiver from the decoder,
 * technically you would not need to "store" the code outside the decoder object
 * for this overly simple example. All of the details would remain in the object.
 * However we are going to go ahead and store them just to show you how.
 */
// Storage for the recorded code
IRTYPES codeType;          // The type of code
unsigned long codeValue;   // The data bits if type is not raw
int codeBits;              // The length of the code in bits

// These values are only stored if it's an unknown type and we are going to use
// raw codes to resend the information.
unsigned int rawCodes[RAWBUF]; // The durations if raw
int rawCount;                   //The number of interval samples

bool GotOne, GotNew;

// added by Nick Gammon
EMPTY_INTERRUPT (PCINT0_vect);

void setup()
{
  GotOne=false; GotNew=false;
  codeType=UNKNOWN;
  codeValue=0;
  Serial.begin(BAUD_RATE);
  while(!Serial);//delay for Leonardo
  Serial.println(F("Send a code from your remote and we will record it."));
  Serial.println(F("Type any character and press enter. We will send the recorded code."));
  My_Receiver.enableIRIn(); // Start the receiver
}

// Stores the code for later playback
void storeCode(void) {

  // added by Nick Gammon
  pinMode (LED_PIN, OUTPUT);
  digitalWrite (LED_PIN, HIGH);

  GotNew=true;
  codeType = My_Decoder.decode_type;
  if (codeType == UNKNOWN) {
    Serial.println("Received unknown code, saving as raw");
    // To store raw codes:
    // Drop first value (gap)
    // As of v1.3 of IRLib global values are already in microseconds rather than ticks
    // They have also been adjusted for overreporting/underreporting of marks and spaces
    rawCount = My_Decoder.rawlen-1;
    for (int i = 1; i <=rawCount; i++) {
      rawCodes[i - 1] = My_Decoder.rawbuf[i];
    };
    My_Decoder.DumpResults();
    codeType=UNKNOWN;
  }
  else {
    Serial.print(F("Received "));
    Serial.print(Pnames(codeType));
    if (My_Decoder.value == REPEAT) {
      // Don't record a NEC repeat value as that's useless.
      Serial.println(F("repeat; ignoring."));
     }
     else {
       codeValue = My_Decoder.value;
       codeBits = My_Decoder.bits;
     }
     Serial.print(F(" Value:0x"));
     Serial.println(My_Decoder.value, HEX);
  }

  // added by Nick Gammon
  pinMode (LED_PIN, INPUT);
  digitalWrite (LED_PIN, LOW);

}

void loop() {

  // added by Nick Gammon
  static unsigned long lastActivity;  // when we last woke
  // sleep if no activity for a while
  if (millis () - lastActivity >= NO_ACTIVITY_TIMEOUT)
    {
    Serial.flush ();  // wait for Serial to finish outputting
    Serial.end ();    // shut down Serial
    noInterrupts ();  // timed sequence coming up

    // pin change interrupt for D11
    PCMSK0 |= bit (PCINT3);  // want pin 11
    PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
    PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

    set_sleep_mode (SLEEP_MODE_STANDBY);
    sleep_enable();

    byte old_ADCSRA = ADCSRA;
    // disable ADC to save power
    ADCSRA = 0;
    power_all_disable ();  // turn off various modules
    interrupts ();
    sleep_cpu ();
    sleep_disable();
    power_all_enable ();   // enable modules again
    ADCSRA = old_ADCSRA;   // re-enable ADC conversion
    Serial.begin(BAUD_RATE);
    lastActivity = millis ();
    }  // end of no activity for a couple of seconds

 if (My_Receiver.GetResults(&My_Decoder)) {
    My_Decoder.decode();
    GotOne=true;
    storeCode();
    delay(500);
    My_Receiver.resume();
  }
}

Explanation
Main changes are in loop (near the bottom) where it sleeps if there is no activity for two seconds. This "no activity" test gives it time to catch an incoming pulse stream.
Before sleeping it turns off Serial (to save power), and sets up to detect the pin-change interrupt. It also turns off the ADC, and calls power_all_disable to disable various internal modules.
Note that it uses pin-change interrupts on Arduino pin D11 (pin 17 on the chip). For a different processor than the Atmega328P, or a different input pin, you would have to change which pin-change interrupt is used.
I found that I had to use SLEEP_MODE_STANDBY rather than SLEEP_MODE_PWR_DOWN, otherwise it seemed to take too long to wake up and handle the incoming pulse.
For testing, I flashed D8 pin to make sure it was working when hooked up in low-power configuration.

Power consumption
I tested with an AX-1838T IR-receiver that I had to hand (same pin-outs as in the Adafruit article).
Measured stand-alone (ie. not connected to the Arduino) it consumed 630 µA, so therefore we could not expect lower power consumption than that.
Connected up to a "bare-bones" board (ie. just the Atmega328P chip, decoupling capacitors, etc.) I measured 1.158 mA when idle.

My tests on my page about power indicate that SLEEP_MODE_STANDBY uses 480 µA more power than SLEEP_MODE_PWR_DOWN, so this sounds about right.
630 + 480 = 1110 µA

You might be able to save more power by operating at a lower voltage. This particular receiver can operate at a lower voltage. As an indication, I tried the setup at 3.3 V (which is out of spec for the processor, but whatever, I was just testing) and it consumed 978 µA when idle. This is a modest saving over the 5 V test.

References

Power saving
Interrupts
Adafruit IR library
IR library source

oh my god, this is an answer! I need time to understand and test it ! Thanks a lot Nick !

Great page. About the low power mode: the low frequency clock is useful in scenarios where one has to do relatively frequent operations, like debouncing: the debouncing can happen at low frequency and then the clock gets cranked up only if the wakeup was real. So that a noisy environment doesn't kill the battery.

LOL !!! Nick, you are the author of that page, is really great !!! I didn't notice it.

@IgorStoppa - indeed, however in this particular case the IR receiver uses the bulk of the power. Still, it may well be possible to get a lower powered one.

Sorry @NickGammon for maybe ask a very noob question. (I'm pretty new into this) I understand that you check for 2000ms if there is no activity, but I didn't get why you sleep and the next command is power all enabled. Are you suggesting that the only way is turn off 2 secs, turn on, watch if something happenning every 2 secs? There is no way to turn off until signal?

Oh I read it from your web. I think I can do the same with the example of
Sketch J

I didn't get why you sleep and the next command is power all enabled - the sleep call is the one where it stops, maybe for hours.

Connect the IR receiver to INT0 or INT1 (pins 2 or 3 respectively). You can use the attachInterrupt function. E.g. attachInterrupt(0, yourfunctionname, LOW). The function being called can be empty, if you only use it to wake up the MCU.
To wake from sleep you need to use the LOW trigger mode. Once waken up you probably want to remove the interrupt handler (detachInterrupt), or it will swamp the cpu with interrupts.
(Note that most IR receiver will still use something like 3mA.)

It has been confirmed by Atmel that any level change will wake the processor from sleep. See Interrupts for a quote of their email.

@NickGammon I never got it to work on anything other than LOW trigger. The datasheet says in table 10.1, note 3; For INT1 and INT0, only level interrupt. The example on the page you link to also only uses LOW triggers.

Most of my examples were written before someone on the Arduino forum raised the issue. Until then I had believed the datasheet. I raised a ticket at Atmel and got this response: "Our design team has confirmed that “Note-3 mentioned under Table 10-1” is a datasheet bug. So you can use any type of interrupt (Rising edge/ Falling edge / Low level / Any logical change) to wake up from sleep mode. Sorry for the inconvenience caused."

For example see this thread External RTC to wake Arduino up on interrupt. The poster there said, after I recommended changing from LOW to FALLING: "Wow. Nick you were right. Tried it with FALLING and it works like a charm. Thanks!" As you noted @Gerben, using LOW has its own problems.

I guess I need to give it another try on my next project. Thanks


text:
Arduino Sainsmart uno communication problem
I'm trying to communicate with my arduino uno but it seems to have troubles to understand characters. For example, printing things with Serial display weird things, changes characters, removes some.
For exemple printing "test !" every two seconds results in that :

Every characters have been removed except "!"...
Is my arduino broken ?  Thanks in advance

Use Serial.print() instead of Serial.write().

You are doing 2 things wrong in your program:
First is using serial.write(), which writes bytes rather than ASCII.
Second is you are declaring a string literal as a char instead, you must declare a string using  double quotation marks (which is ") so that your program should read:
Serial.print("Test!");

When you declare 'Test !'  you are doing it wrong, and it will only take the last char in the string, which is '!' - using single quote marks is for a single char declaration, like '!' or 'T', and you can make an array of chars into a string if you wanted, like this:
char array[] = {'T', 'E', 'S', 'T', '!' };
Serial.write(array, 5);

but why would you when the earlier one works better?

The single vs. double quotation marks is a good catch. Serial.write("...") should still work though according to the documentation, as an ASCII string is just a sequence of bytes like any other.

@PeterR.Bloomfield indeed, however they are not formatted as ASCII human-readable bytes for proper use in the terminal viewer - the issue the OP had was junk bytes being displayed, or just '!' due to the compiler and it's string literal vs const char declaration behaviour

Serial.print("...") is literally just a wrapper for Serial.write("..."). They send exactly the same thing.

@PeterR.Bloomfield well it depends what you are sending, and to what - if you are doing serial to an external serial device you may not want ASCII conversion of your bytes, so Serial.write should be used. For nice terminal output, and lots of extra functionality of specifying the format of data in ASCII (such as the HEX formatter) using Serial.print() is better. The OP in his case should be using print, just for convenience sake. I've pointed out why it's not technically working, and indeed if he understands how both work then he CAN use both for reading terminal data.

It inevitably comes down to both ways using .write() but .print() has cool stuff, and for noobs I suggest they use it until they get better at programming.

Thanks a lot !! It was just the simple quote that was making it act like this !

source: Stack Exchange

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

sort: votes


text:
How to correctly use functions that return pointers to multiple typedef'ed types in Arduino IDE?
I have a program that typedef's two structs. Each one has a corresponding function that returns a pointer to it....
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

This program produces the following error when compiled under the Arduino IDE...
sketch_nov10a:18: error: 'y' does not name a type

 y *g(void)

If we copy/paste to switch the order of the two blocks like so...
typedef struct {
    int  y1;
} y;

y *b;

y *g(void) {
  return b;
}

typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

void loop(void) {

}

void setup(void) {

}

...then we instead get the following error...
sketch_nov10a:18: error: 'x' does not name a type

x *f(void)

...so apparently the Arduino IDE only supports functions that return pointers to the first typedef'ed type defined in the file?
Is there a rational to this? How would you implement the above code to get it to compile under the Arduino IDE (it works fine in gcc).

The Arduino IDE, rather annoyingly, tries to "help" you by generating function prototypes for functions, something it sometimes fails to do.
You can make your code compile by adding one yourself:
typedef struct {
  int x1;
} x;

x *a;

x *f(void) {
  return a;
}

typedef struct {
    int  y1;
} y;

y *b;

y *g(void);    // <------------------ ADD THIS
y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

I have a post about how to avoid the quirks in the IDE which may help you.
If you just move your code into a separate .CPP file and leave the main sketch blank, it will compile, if you add this line to the start of the .CPP file:
#include <Arduino.h>

The Arduino IDE uses gcc, so it isn't a problem with the compiler exactly, it is a problem with how it "helps" you.

This is the correct answer and solves the problem, but so unsatisfyingly... :/ Thanks!

but so unsatisfyingly - yes, I know. In order to save teaching newbies about function prototypes they have created a monster that behaves in a way that confuses non-newbies. :)

I tracked this down and I'd classify it as a logic bug in the arduino-builder tool. See this new answer for details.

Cause
Ok, I've pinned down the root of this issue.
The arduino-builder program is responsible for mangling the sketch INO file into a cpp file to be fed into gcc. Among other things,  it scans the file for function definitions and then adds prototypes for all the found functions.
The prototypes are added as a block just before the first function declaration in the file.
Unfortunately this strategy fails any time there is the following sequence....

a function definition
a type definition
a function definition that depends on the type defined in #2

...since the prototype for the function defined in #3 ends up being added before the type definition in #2 on which it depends, creating the compilation error.
The code responsible for this behavior is here...
https://github.com/arduino/arduino-builder/blob/b91cea8c8a42803b0b40dcdde2d1165c4e225457/src/arduino.cc/builder/ctags_runner.go#L83
A more robust strategy would be to add each function prototype before the first function definition that calls the function being prototyped.
Workaround
In the meantime, a workaround is to move all type definitions to be before the first function definition in the source code.
Rearranging the above example program like so...
typedef struct {
  int x1;
} x;

typedef struct {
    int  y1;
} y;

x *a;

x *f(void) {
  return a;
}

y *b;

y *g(void) {
  return b;
}

void loop(void) {

}

void setup(void) {

}

...resolves the error, at the expense of code clarity.

It would be hard to get the builder to work in all circumstances (for example if you use #define to obscure your intent). Effectively it needs to know what the compiler knows, so effectively they need to turn it into a compiler to do the job properly. Your suggestion works (as does mine) but this is not something people normally expect to have to do.

bigjosh, Thank you for a small and working sketch that shows the problem !
It is probably a bug of the Arduino preprocessing before handing it over to the compiler, as @nick-gammon wrote.
When I rewrite the code in my own way (in a normal sketch, a *.ino file), the error message is gone. I use a more modern style of the struct typedefs, and I declare first the typedefs and after that the variables and after that the functions.
I suppose that when multiple include files are used, then this might not be possible.
// declare the typedefs.
struct x {
  int x1;
};

struct y {
  int  y1;
};

// create variables (pointers)
x *a;
y *b;

// Arduino functions
void loop(void) {
}

void setup(void) {
}

// Your own functions
x *f(void) {
  return a;
}

y *g(void) {
  return b;
}

I hope the data of the struct is located somewhere, because the sketch has only pointers and no valid memory location that they can point to.

You wrote x and y struct definitions, rather than typedefs.  That approach is not "newer" than that in the question; if anything, it's older.   Note, the code you show shouldn't compile correctly unless you add struct before x *a; and y *b;.  See the first answer to Difference between 'struct' and 'typedef struct' in C++?,

@JamesWaldby-jwpat7 Did you try to compile it ? I'm using the C++ way where the struct/union/enum create a new type. I understand that it can cause a problem, when a similar name gets hidden. That's about how far my knowledge stretches. It is not wrong, and I consider it even as normal C++ programming. I'm happy to learn new things though.

Ignore the “shouldn't compile correctly” part of my comment (which is true in C not C++, as I noticed too late to edit) .  It might be worthwhile to ignore the whole comment :) but I'll leave it there for the link.

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


text:
Auto detecting Baud Rate of Arduino
I'm trying to detect baud rate of Arduino Mega2560 by using C#. My code is below:
SerialPort SP=new SerialPort();
SP.BaudRate = 115200;

BaudRate is specified as a constant like this, but I would like to automatically detect it.
For instance, if Arduino code includes Serial.begin(xxxx), program should declare SP.BaudRate = xxxx.
How can I do it?

I'm not a C# programmer but this StackOverflow answer might be what you're looking for.

Note that to do this, there has to be a way to get an expected response from the device.

True, but you'll probably want some sort of basic handshaking anyway.


text:
Addressable RGB strip works fine individually but cannot set all LEDs to full white
I have a 5 meter strip of 12V digital RGB LEDs. The chip is WS2811 (see photo of IC). There are 50 addresses on the strip.

Using the FastLED library, I am able to run the "FirstLight" example that chases full white with a single address at a time, up and down the length. That works fine. So I know they individually perform properly.
However, if I set all LEDs to full white (255), the first few addresses look white but then the higher the address, the more red it is. See photo below. The strip starts in the center of the reel.

#include <FastLED.h>

// How many leds are in the strip?
#define NUM_LEDS 50

// Data pin that led data will be written out over
#define DATA_PIN 5

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidentally blowing power w/leds
    delay(2000);
    Serial.begin(115200);
    Serial.print("### SETUP ###");

      //Both strips are ordered BRG
      FastLED.addLeds<WS2811, DATA_PIN, BRG>(leds, NUM_LEDS);
      //FastLED.addLeds<UCS1903, DATA_PIN, BRG>(leds, NUM_LEDS);

}

void loop() {

   for (int i = 30; i < NUM_LEDS; i++) {

       leds[i] = CRGB::White;

   }

   FastLED.show();
}

To debug, I tried turning on just the last half. The result was still problematic:

for (int i = 30; i < NUM_LEDS; i++) {

    leds[i] = CRGB::White;

}

I then tried setting all LEDs to white at half brightness, and that looks much better, but the LEDs at the outside are still off-color compared the inside:

I've tried setting the whole strip to full blue, and that works fine.
I also have another nearly identical LED strip that instead uses the 1903 chip. The same code (initialized for 1903 instead of WS2811) works just fine on the 1903 strip!
Other things I've ruled out:

I'm using a bench power supply capable of 5A, this strip pulls less than 1.5A on full white.
I have verified the supply holds at 12V
I have not let the LEDs heat up while coiled in the reel. I make sure to unplug them after observing their color.

What could cause this on the WS2811 strip while the 1903 strip works perfectly?

I would suspect that it is a voltage drop in the power rails caused by the current draw. Probably cheap construction with copper tracks that are just too thin and so have too high a resistance.
To combat it you will need to inject power into the strip at various points along it.  Initially to prove the theory you can try connecting the power to both ends of the strip and see if the "dull" spot is half way along the strip.  If it is, then it's certainly a voltage drop.  (incidentally, a voltage drop will cause the blue LEDs to fade out first making it go yellow-red. Then the green ones would probably be next, making it go red).
Then, once proved, you will need to add extra power connections into the strip at the middle of any dim sections and feed the voltage directly in at those points.

You were right! I connected both ends and the middle was only slightly off-color. I thought that such a simple product couldn't possibly have this issue, and yet here it is. I've never seen such a dramatic drop on such a short strip before.

@Bort It certainly looks worse than on my 5V, 5 metre strip with the same number of LEDs. Maybe they skimped on the track size (which is silly because PCB makers don't charge based on the amount of copper)

BTW, this strip was sold as IP67 and sealed in a single continuous rubber tube. Thus it wasn't really meant to be cut down to a shorter length.

@user253751 Knowing copper is expensive, why wouldn't more copper increase the price? Maybe things work differently in Asia?

@Bort PCBs are usually made with a subtractive process where the board is fully covered in copper and then some is removed and discarded. So you pay for all the copper you use and all that you discard. I dont know if this applies to flexible substrates.

@Matt - Wouldn't the baseline amount of copper change the cost though? Example: Starting with a PCB 1 unit thick of copper and then subtracting, vs starting 3 units thick and then subtracting. While the subtraction doesn't save the buyer money, the initial choice of thickness would, right? Or am I missing something?

@Bort Yes, you are correct, thickness changes the cost. I assumed we were just talking about copper trace widths.

@Matt - Oh, I now see that user253751 was referring to width, not thickness! But then I wonder why they didn't consider thickness...

@Bort You can still cut it, but you'll have to find something to seal the end with, which might take some research or experimentation (you can't just assume that filling the end with hot glue will keep it waterproof - though it might be sufficiently waterproof for your use, if it's only a small amount of water)

@user253751 Silicone sealant (bathroom sealant) is the normal method...

It's not necessarily cheap construction.. but the ws2811 strips where 3 RGB LEDs are controlled by 1 chip need quite a lot of traces routing on just 1cm of strip width. This in turn limits the width that the two power traces can have, which results in a rather high voltage drop over distance. For this reason, vendors of those strips usually advise to put secondary power injection points after each 1 or 2 meters of strip. This problem is less noticeable with ws2812 LEDs with their integrated controllers, as they can have two rather broad power traces runnng straight along the whole strip.

(but the ws2812 in turn are sold in variants with up to 144 LEDs per meter, which draws so much power that secondary power injection does become necessary again.. albeit with a much higher light output)

@WooShell That would explain the difference. The strip I had used WS2812s.

@Bort another trick you could try is connection only the ground at 1 side of the rail, and only the positive at the other side, this should mostly self balance the voltage any led sees

I've got a fair bit of experience with these strips. In theory, for the 5V, 60LEDs/M types, you need to power them every 1M or so along their length, in practice I find that every 2-2.5M is plenty - so long as you have a sufficiently high current power supply (although it's manufacturer specific). For 12V I'd imagine you could stretch to 2.5-3M between taps. The silicone jacketed types do need a small hole sliced out of the jacket to attach the power "taps", which should then be comprehensively filled with exterior silicone sealant.

@Majenko, the poster has not specifically said he is using Arduino. Do you not think you should close down the question, as it might be off-topic, or is that just a rule for anyone that mentions the word MicroPython?

@PrestonDocks No, I count this as on topic. 99.999% of people using these are using them with Arduino. You don't need to specifically mention it. But using a non-Arduino microcontroller with non-arduino code is obviously off topic. If you don't like this question then exersize your close vote. That's what it's there for.

@Majenko 99.999% of people using ESP32 boards are using them with the Arduino IDE, but because I mentioned the word MicroPython in a question related to ESP32 you closed my question. Also most people using Arduino, are not using Arduino, they are using clones.

@PrestonDocks An ESP32 is not an Arduino. If you use it with Arduino code then we are happy to assist you. But since you aren't, then we can't help you. If you continue to moan and whinge I'll ban you.

Majenko's answer is correct, and you could also verify it with the test performed.
Since it is an issue I encountered myself in the past in a similar case, I want to share some measurements I took on the LED strip I have, in case it can be useful for you or other people.
Premise: the tests were done with a 5m 60 leds/m RGBW strip (SK6812, natural white).
The first test was done to measure the current from each LED. These are the results:

All LEDs off: 230 mA (0.77 mA/led)
10 LEDs to max RED, GREEN or BLUE (one color): 320 mA
10 LEDs to max WHITE: 410 mA

This means that each R, G or B led absorbs at max 9 mA, while the W ones have a 18 mA current. Each LED, whether on or off, has a 0.77 mA current flowing through it.
In order to evaluate the voltage drop, I then turned on to full white the first 100 leds, then measured the current, the input voltage and output voltages of the strip. I got a voltage drop from 4.8 V to 4.16 V with a current of 2.11 A (which is almost equal to 230mA + 18mA/led * 100led).
I then modeled the strip as a sequence of ideal current generators joined by resistors:

simulate this circuit – Schematic created using CircuitLab
Calling R the resistance introduced by the strip, I_Led the current flowing into one LED and N the number of LEDs turned on (and ignoring the effects of the standby current), the voltage drop on the first resistor is dV1 = RNI_Led, the one on the second is dV2 = R*(N-1)I_Led and so on, up to dVN = RI_Led. The total voltage drop is dV = RN(N+1)*I_Led/2.
Using the measured data, we can calculate the resistance between two consecutive LEDs:
R = (2*dV)/(N*(N+1)*I_Led) = (2*0.64V) / (100*101*0.018A) = 7mOhm
NOTE: this is neglecting the effects of the standby current. However in my calculations I was searching for a worst case, and by excluding these effects I was in fact making worst assumptions, so I did not care about them
So, with this resistance I was able to calculate the voltage drop for arbitrary strips and consequently plan where to put the power supply joints. In my case I planned to have at max stubs 1.2m long (80 LEDs), so that the voltage at the end, in the very worst case (all LEDs on in RGBW, at max brightness), I had a voltage drop of slightly more than 1V.
Note that in my setup the voltage drop on the first element (the one with the largest drop) is (80*0.045A*0.007mOhm) = 25mV, with a power dissipation of 90mW.

This strip was sold as IP67 and sealed in a single continuous rubber tube. I would have to break that seal to get those measurements, though I guess there's not much to lose at this point.

@majenko, this answer is about Electronics Theory, it is definitely not about Arduino so it is off-topic. Can we close it, please?

For completeness, I want to include an RGB circuit simulation I made a while ago, along with some data. It's for analog RGB strips, but the concept regarding voltage drop is the same. I've since added a few more LEDs to show the effect of voltage drop across the length, and added the ability to switch the power connection as well.
The simulation shows the current through each 3-LED segment. 12V strips typically have 3 LEDs in series, and repeat that along the strip.
When I created this simulation, I chose exaggerated resistance values, however, this WS2811 strip may be rather close. I haven't modeled it with particular measurements though.
There are switches in simulation circuit that you can click on to switch the connection to 12V and ground at either end of the strip.
[Link to simulation]

Results:
With 12V and ground on the same end:  28.389mA - 27.892mA = 2.123mA difference
With 12V and ground on both ends:        28.389mA - 27.892mA = 0.497mA difference
With 12V and ground on opposite ends: 27.310mA - 26.834mA = 0.476mA difference
While both power and ground can be connected at both ends of the strip, this simulation actually shows a better balance by simply moving the ground to the opposite end of the strip that receives 12V.
The only way for each LED segment to be truly balanced would be for each to have it's own connection to power and ground.

@majenko Another Electronics Theory answer, we are getting very of topic again. Can you please moderate appropriately.

The LEDs require 12v but the chips require lower voltage.
The WS chip requires 3.3v to 5v unlike the 6-7v that the IC require, the added resistance along with the fact that the last led has to run  10 metres on a return trip (5m on positive, 5m on negative = 10m total) could mean the drop is to much.
Easier way to find out is to connect in the middle, if it the problem persists (both ends are bad) it's the power supply

When you say the WS chip requires 3.3v to 5v [and the IC requires 6-7V], which IC are you referring to? IC and chip are pretty much the same to me.

Those types of strip are simply not sized for full-on on all LEDs. It's expected that if you wanted that, you'd be running a parallel LED strip for lighting that is not addressible and that uses a much higher voltage such as 12 or 24V, where voltage drop is less critical.
Generally addressible LEDs aren't meant to be used in long strips, but are expected to be fit into an array of some kind with numerous short strips, where each can be fed individually.
Running a long stretch isn't a problem, but you will need to feed power at many locations if you want this level of illumination. And you will get murdered on either wire size or voltage drop because voltage drop is so critical when your voltage is only 5 volts.  Crunch the numbers but you can find yourself buying big 1/0 feeder wire in a hurry. I recommend instead carrying power at 24V or mains and converting to 5V in many locations.
I would suggest rethinking the design intent and if illumination is also desired, run a separate strip just for that.  Those are dirt cheap.

Actually, it is a 12V strip, I'm not sure where you got "5V" from. As the question also states, I have another 12V strip that is nearly identical except that it uses the 1903 IC, and that strip works fine with all white.

As others have answered, it is because of voltage drop.
If you feed positive to the connector at one end, and negative to the other end, all leds will see the same voltage drop, as all leds have 5m connection to the power supply.
If we call the ends L and R with L+ and L- and R+ and R-:
Connect + to L+ and - to R-
If you want to be advanced, get a power supply with separate output and sense connections.
Then connect sense+ to R+ and sense- to L-
This will ensure that the voltage across the LEDs are 12V, by raising the voltage to compensate for the voltage drop.
I started a drawing in CircuitLab, but they want money now?! How rude...

Note that if power and ground are connected at opposite ends, there will still not be a perfectly even voltage for each LED segment. I have added an answer of my own with a simulation to address this

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


text:
How do I send non-ASCII keys over the BLE HID connection using an Adafruit nRF52 Feather?
The hid_keyboard example sketch shows how to send ASCII characters, but how can I send non-ASCII codes like the F1 key, or keys with shift/control modifiers?

Yo can use the keyboardReport() function to send key-codes with modifiers. Here is an example that will send an ! by sending the keycode for 1 plus a shift key modifier...
    // The keyboardReport() function takes an array of 6 keycodes. From what I can tell, it does not
    // press the keys consecutively,. it presses them simultainiously.

    // Here we only want to send one code, so we back-fill the array with HID_KEY_NONE

    uint8_t keycodes[6] = { HID_KEY_1, HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE , HID_KEY_NONE };
    blehid.keyboardReport( KEYBOARD_MODIFIER_LEFTSHIFT , keycodes );

    // This release seems to be required. Without it, the last pressed key just repeats forever.
    blehid.keyRelease();

The possible modifiers are listed here...
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L188
...and the possible keyscodes are listed here..
https://github.com/adafruit/Adafruit_nRF52_Arduino/blob/200b3aaefb3256ac26df82ebc9b5b58923d9c37c/cores/nRF5/Adafruit_TinyUSB_Core/tinyusb/src/class/hid/hid.h#L212
Unfortunately the hid_keycodes example does not compile, but bere is a ready-to-run example sketch showing how to send keycodes directly...
https://gist.github.com/bigjosh/5d8575f26988228dcf9d40c3795d0928

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


text:
How can I make my custom board use the programmer selected in "Tools->Programmer" when the Upload button is pushed?
I've created a custom board that can be programmed using any one of several programmers defined in programmers.txt. I would like the user to be able to choose which programmer to use via the "Tools->Programmer" menu options.
I tried using {protocol} and {upload.protocol} in platform.txt to pass the programmer to the upload tool, but neither seem to be defined when the Upload button is used to initiate the upload (they are defined if Upload using programmer is selected from the menu).

Make sure you do not have a protocol listed in the boards.txt file. If the uploader sees protocol is null then it will fall back to using the same code that "Upload using programmer" does.
Relevant code in SerialUploader.java:
    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }


text:
Why is the Arduino IDE ignoring my replacement start up code?
I am trying to replace the standard startup code to save flash space.
I've put the new startup.s in my core directory and added the -nostartfiles parameter to the linker reciepe in my platform.txt.
When I compile with the IDE, it does not include my start code at all.
When I use Atmel Studio or a makefile, the code assembles and is included just fine.
How can I get the Arduino IDE to use my new start up code?

to which board package does this apply? I don't have an startup.S file in any of the many installed packages

@Juraj I am using a custom AVR board, but this applies to any board with an architecture that requires a startup file - which is all that I know of. The standard startup file is usually included as an already compiled .o file. For example, the AVR start code lives in the hardware/tools/avr/lib tree as crtXXXX.o where the subsirectory and the XXXX depends on the selected platform/board/chip/variant. This file is automagically included by the linker is -nostartfiles is not specified.

is it a bug in Arduino builder?

@Juraj I'd call it more of an "unexpected, undocumented, and undesirable behavior" than a bug. :)

The Arduino builder is case sensitive and will only see files that end in .S and not files that end in .s.
Renaming the new start up file to startup.S and then deleting the precomplied core archive fixed the problem.
Note that committing this change to git slightly complicated!


text:
How to program LCD shield?
So I'm using the DFRobot LCD Keypad shield to make a text-based game. Can someone give me an example? Let's just say i want to make the LCD display "text1" and then press up then select, it displays "text2". If I press down then press select, it displays "text3".

File -> Examples -> LiquidCrystal -> HelloWorld

The program isn't running.

I clicked upload and nothing happened.

You probably have to tailor the pin settings for your specific shield.  RTFM.

Wait will I need to solder for this?

No, you need to read in the manual for your LCD which pin is which and put them in the constructor for the Liquid Crystal object.

I tweaked the pins and still nothing.

Attach the shield to arduino then run the following code to check if everything is ok.
Wiring is made default.
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);           // select the pins used on the LCD panel

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

int read_LCD_buttons(){               // read the buttons
    adc_key_in = analogRead(0);       // read the value from the sensor

    // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
    // we add approx 50 to those values and check to see if we are close
    // We make this the 1st option for speed reasons since it will be the most likely result

    if (adc_key_in > 1000) return btnNONE;

    // For V1.1 us this threshold
    if (adc_key_in < 50)   return btnRIGHT;
    if (adc_key_in < 250)  return btnUP;
    if (adc_key_in < 450)  return btnDOWN;
    if (adc_key_in < 650)  return btnLEFT;
    if (adc_key_in < 850)  return btnSELECT;

   // For V1.0 comment the other threshold and use the one below:
   /*
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;
   */

    return btnNONE;                // when all others fail, return this.
}

void setup(){
   lcd.begin(16, 2);               // start the library
   lcd.setCursor(0,0);             // set the LCD cursor   position
   lcd.print("Push the buttons");  // print a simple message on the LCD
}

void loop(){
   lcd.setCursor(9,1);             // move cursor to second line "1" and 9 spaces over
   lcd.print(millis()/1000);       // display seconds elapsed since power-up

   lcd.setCursor(0,1);             // move to the begining of the second line
   lcd_key = read_LCD_buttons();   // read the buttons

   switch (lcd_key){               // depending on which button was pushed, we perform an action

       case btnRIGHT:{             //  push button "RIGHT" and show the word on the screen
            lcd.print("RIGHT ");
            break;
       }
       case btnLEFT:{
             lcd.print("LEFT   "); //  push button "LEFT" and show the word on the screen
             break;
       }
       case btnUP:{
             lcd.print("UP    ");  //  push button "UP" and show the word on the screen
             break;
       }
       case btnDOWN:{
             lcd.print("DOWN  ");  //  push button "DOWN" and show the word on the screen
             break;
       }
       case btnSELECT:{
             lcd.print("SELECT");  //  push button "SELECT" and show the word on the screen
             break;
       }
       case btnNONE:{
             lcd.print("NONE  ");  //  No action  will show "None" on the screen
             break;
       }
   }
}


text:
Arduino ligths on/off clapping hands
I'm new to Arduino and I'd like to realize a system using Arduino One and SparkFun Electret Microphone Breakout (BOB-09964) to turn on/off lights clapping my hands. https://www.sparkfun.com/products/9964
What are the components I need? I'm going to buy them and I don't want to buy components which I will not use soon (so no starter kits but only a breadboard, resistors, LEDs, etc...).
Sorry for this basic question but as I said I'm new to this world.

If you start from the beginning of the project, instead of trying to jump in half way through, you'll know precisely what components you need.
Your first step shouldn't be trying to order components, but to identify (through research) how the technology works.
Second is to find out how it can be implemented, by looking at existing schematics and designs that other people have created.
Third is to design your own schematic.
Fourth is to prototype it.  It's only at this stage that you should be thinking about what components to order.
Go back to stage one and do the research. Thanks to the likes of Google it'll probably only take you a few minutes.

See the Arduino tutorial for a Sound Sensor Example.
This is a very similar project that shows the breadboard layout and code needed for a clapping sensor based on an electret microphone breakout board.
The website listed above has a list of parts needed, the circuit diagram as well as the code needed.

I was able to get this project working. I built just the sound sensor side, and used the onboard LED instead of building an LED circuit. At first I had problems getting a clear analog signal, due to poor connections to the microphone breakout board. After soldering the header pins to the breakout board the connection was good and the system worked.


text:
Failed to read DHT22 sensor using Arduino Uno
why do I end up with the display "Failed to read from DHT sensor!" in the serial monitor in most cases when I run the code given below?? In case I reduce the delay to 1000ms the reading shows 0.00 for both temperature and humidity which, as well, is pretty much false......Any help would be highly appreciated...
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include "DHT.h"

#define DHTPIN 2     // what pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);
// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
// might need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// Example to initialize DHT sensor for Arduino Due:
//DHT dht(DHTPIN, DHTTYPE, 30);

void setup() {
  Serial.begin(9600);
  Serial.println("DHTxx test!");

  dht.begin();
}

void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index
  // Must send in temp in Fahrenheit!
  float hi = dht.computeHeatIndex(f, h);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hi);
  Serial.println(" *F");
}

Please provide me the solution for this problem as i am also getting this type of error.. -Thanks

Make sure you define the digital pin number, I didn't and I got that error // Example testing sketch for various DHT humidity/temperature sensors // Written by ladyada, public domain #include "DHT.h" #define DHTPIN 12 // what digital pin we're connected to

Have you tried loading the Adafuit_Sensor library before DHT?

what changes occurr if i use LM35 instead of DHT22.
Anyone would help...

If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review

Please share the sketch that you have used and worked. - Tharani

I suggest you to modify the following lines of code to check which reading has issue.
if (isnan(h) || isnan(t) || isnan(f)) {
   Serial.println("Failed to read from DHT sensor!");
   return;
}

Have you put a  4.7kOhm  resistor between data pin and Vcc on the dht22? i had problems with a reading until i did. see this
HTH

Yeah, I have that 4.7k plugged in but it didn't quite work....now I have made it work using a different sketch and library altogether( courtesy Rob Tillaart)....


text:
DHT22 Does not update
Good evening :)
I am fairily new to coding the fabulous Arduino UNO. My project right now are consisting of reading Temperature from a DHT22 (AM2302) and writing to a 4-digit 7-segment display. I have got the display to work, but the system does not update the temperature at all. Just the first reading are displayed
#include <DHT.h>
  #include <TimerOne.h>
  #include <SevenSeg.h>

  #define DHTPIN 4    //Defines the temp-pin

  /* DHT22- Pin1 (left) - 5V/3.3V
  Pin2- DATA
    Connect a 10K res from pin1 to pin2
  Pin3 - NC
  Pin4 - GND
  */

  //#define DHTTYPE DHT11   // DHT 11
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  //#define DHTTYPE DHT21   // DHT 21 (AM2301)

  DHT dht(DHTPIN, DHTTYPE);

  SevenSeg disp (13 ,2 ,3 ,8 ,5 ,6 ,7);
  //            (11, 7, 4, 2, 1, 10, 5)
  const int numOfDigits =4;
  int digitPins [ numOfDigits ]={9,10,11,12};  // uten transistorer
  //                            (12,9,8,6) Alle med 220 Ohm seriemotstand
  //int digitPins [ numOfDigits ]={12,11,10,9};  // med transistorer

  void setup ()
  {
    Serial.begin(9600);
    Serial.println("DHT22");

    disp . setCommonCathode();  // uten transistorer
    //disp . setActivePinState(HIGH,HIGH);  // med transistoere
    disp . setDigitPins ( numOfDigits , digitPins );

    Timer1.initialize(15);   // 0.015 sek
    Timer1.attachInterrupt(loop);
  }

  void loop() {

    dht.begin();

    delay(300);
    float t = dht.readTemperature();

    disp.writeFloat(t);
    Serial.println(t);

  }

How do I get the Sensor to update regularly?

Try moving dht.begin(); to setup().
The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In dht.begin() an internal timer is reset that is used in readTemperature() to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling dht.begin() every 300 ms you're making this meachanism inoperative. You're supposed to call dht.begin() only once at start-up.
Edit: And please also remove the Timer1 that calls loop. loop is already an infinite loop, so no good in calling it additionally from an interrupt...

Yaay, It worked!! And makes completely sense :D Thanks :D

Try this in your loop method
The while loop will read the temperature, write to the display and write to the console.
void loop() {
  dht.begin();
  float t;
  while(1)
  {
    t = dht.readTemperature();
    disp.writeFloat(t);
    Serial.println(t);
  }
  delay(300);

}

Thanks for a quick answer :D Buuut it did not do any difference

Do you get anything on the console?

@Gerben , I did get the first reading repeated over and over again


text:
FastLED library: How can I adjust the brightness of a single pixel on an absolute scale?
I'm using the FastLED library to control a digital RGB LED strip.
While this library seems very comprehensive in capability and ease of use, I do not yet see a way to simply set the brightness value of a individual pixel on an absolute scale. In other words, I want to simply set the brightness of a pixel, without passing a hue or saturation, and without it effecting other pixels.
FastLED.setBrightness() scales down the brightness of all pixels.
leds[i].fadeLightBy() scales down an individual pixel, but if it's called again for the same pixel before updating the LEDs, then the pixel will be faded again from it's already-faded value.
Is there truly no built-in method for setting the brightness of individual pixels to a particular value?

There is no dedicated function to adjust brightness.
You can (however) do this by using the HSV color model.

Breaking HSV (Anachronism) into Parts:
H (Hue) Controls the Color itself.
S (Saturation) of the Color.
V is called Lightness or Value.
'V' is what you want to control.
Just set the LEDs color to a HSV value and change it's V value.
leds[i] = HSV(color, saturation, brightness);

While 'Color' and Saturation' remain the same (to keep the same color), you can change the 'Brightness' directly on the third parameter.
Note that 'leds[i]' is still defined as 'CRGB', not as 'HSV'.
This assignment uses an implicit conversion, that is defined in the library.
You can see the 'HSV' usage example within the 'Cylon' example on the FastLED library.
There you will find the Hue value that gets changed; but it is the same principle as 'brightness'.

Now there is a problem to solve.
The FastLED library can convert 'HSV' Colors to 'RGB' Colors; but not the other way round.
So you cannot simply get the 'hue' and Saturation from an 'RGB' Color with this library.
You have 2 Alternatives:
1. You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a 'HSV' color in the second array, convert that array to 'RGB' by using 'CRGB(hsv_leds[i])' and save that in the first array, which get's used by the FastLED library).
This is relatively easy, but you effectively need double the memory for storing the color values.
This is not an issue, if you have enough memory or few enough LEDs to control.
2. You can write your own function to convert 'RGB' values to 'HSV'; then use it to access the 'hue' and 'Saturation' values for the targeted 'RGB' Color, create a new 'HSV' Color with it and the new 'Brightness' and use it to set the 'RGB' values for the FastLED library.
In this forum thread there is a brief discussion about that, though it leaves you with the implementation yourself.
I think there are suitable implementations, that can be found on the web.
A quick search gave me this code from github gist.
I have not tested it, so I cannot say, if it really works correctly, but you should give it a try.
I'm sure there are also other implementations.

I realize that HSV let's you pass brightness, however I have applications that call for changing just brightness alone, given a certain trigger. It seems to me now that the solution is to do something like the following pseudo code: leds[i] = HSV(leds[i].color, leds[i].saturation, 127); so that I can manipulate the brightness to 127 without knowing offhand the current color, saturation, or brightness of that pixel at that time. I'll have to look around for the actual syntax of it. I certainly hope it can be done that way.

@Bort I added a short explanation for that topic.

I think your answer is misleading when you say "you can just do exactly this" because I think your answer then goes on to explain that I cannot do that and I have to do something else. For your solution #1, why would I need to convert to RGB when the library already takes HSV as input? I'll try #2 in a bit.

It's more of a "you can do exactly this, but it is a bit more complicated, than you wanted", since you can control the brightness of a single pixel with this, but it is more complicated than simply using one dedicated inbuild function. About #1: All examples, that I have seen, use CRGB as the array type, that is passed to the FastLED constructor. I tried using the construcktor with the HSV type, but that resulted in a corresponding compilation error. Thus I deducted, that the library works only with RGB, but also gives you HSV, which can then be converted to RGB

That deduction may be wrong. If you are able to directly use HSV for the array, please tell us and I will change my answer.

I just meant that if I already have what I want in HSV, I can just use leds[i] = HSV(color, saturation, brightness); so why convert to RGB? ....I must be misunderstanding you.

The array element leds[i] is then still defined as CRGB, thus you cannot get the color and saturation back from it via leds[i].saturation etc. The line above uses an implicit conversion from CHSV to CRGB, that is defined in the library. That exactly is the problem, why I added the two possibilities. I will add a bit more to the answer to make this clear.


text:
Controlling bigger motors with an arduino board
i am german and my english is not the best, anyway i hope you will understand my problem.
At the moment i construct a little car with some friends. We have still completed the frame and now we think about controlling it in a electronic way. For example with a controller of a playstation or with our smartphones, however, it should be electronic, so i think about to do this with an arduino board.
We have two motors. One for the direction and the other one for the movement.
The first has about 8 ampere and about 12 volt, the other has 800 watt, so around 40 ampere and 24 volt.
My question is, whether it is possible and if so how to control them (or one them) with an arduino board and what do i need in addition?
It would be great if you could help us :)

How much money do you have and how much are you ready to invest? It is totally possible.

Until 600 euro it is okay

Nice :)) In this case if yo do not have much experience in electronics i would suggest to buy ready to use DC motor controller. Like this http://www.pololu.com/product/1383 and control it with android

okay, thank you, i will try :)
if there are questions, could i ask you?

Sure why not. There will be about communication between arduino and android or any other device

DC motors are typically driven with some sort of BJT/MOSFET solution that will be able to sink enough current to drive the motor because a microcontroller pin can only usually provide a few mA of power.  See this link for info on basic microcontroller DC motor control.  If slow response is acceptable and only one level of power is required (i.e. no PWM) even power relays could be used to turn on off the motor.  Some applications could use this.  However, for your application, it sounds like you will want more responsive control over the motor and need a particularly high power MOSFET to properly drive your application as your motor is very high power.  Such FETS such as these could be used to properly control such a motor using the microcontroller.  Do note additional protection circuitry will be necessary and is probably the topic of another feed, but this would be a place to start if you wanted to build it from scratch.  Otherwise go with an over the shelf driver board which will probably have something like the link above used on it.

One of the best ways to controll a motor is to look in to the motor shields from the arduino. You can buy seperate motor controllers with different throughput, some advanced with breaking and some without.
But motorshield is about the best way to get started.


text:
C++ Pointer Issues - Mangled Data
I am having trouble getting my head around pointers in C++, specifically how they behave when passed around or used within objects. As far as my understanding goes as long as pointers, or more specifically values/objects pointed to - do not go out of scope, I should be able to use that pointer.
I have been playing around with some test code on my Arduino Uno and I am bumping into behaviour I cannot explain.
I have read rather a lot on the topic of pointers in C++ and thought I had a good grasp of it. However, practice doesn't seem to match the theory in my head. I don't know if this is a lack of understanding or if the Arduino platform has idiosyncrasies that I am not aware of.
In my test code I have created two classes, Alpha and Beta. Alpha simply holds a C-type string in a member variable called alpha. Beta is designed to hold two Alpha instances in an array*.
*While this is "toy" code, the general structure mirrors my actual project. I have used this toy code as it more succinctly describes the set up and the issue I am facing.
pointers.h
#import "Arduino.h"
class Alpha {
    private:
        char alpha[20];
    public:
        Alpha();
        ~Alpha();
        char* getAlpha(char* s, int size=20);
        void setAlpha(char* value, int size=20);
        void debug();
};

class Beta {
    private:
        Alpha** alphas;
    public:
        Beta();
        ~Beta();
        Alpha* getAlpha(int index);
        void setAlpha(Alpha* alpha, int index);
        void doStuffWithAlpha(int index);
};

pointers.cpp
#import "pointers.h"

Alpha::Alpha() {
    setAlpha("Initial");
}

Alpha::~Alpha() {}

char* Alpha::getAlpha(char* s, int size/*=20*/) {
    *s = *alpha;
    return s; //return not strictly needed here since s is passed in
}

void Alpha::setAlpha(char* value, int size/*=20*/) {
    strncpy(alpha, value, size-1);
    alpha[size-1] = '\0';
}

void Alpha::debug() {
    Serial.println(alpha);
}

Beta::Beta() {
    alphas = new Alpha*[2];
}

Beta::~Beta() {}

Alpha* Beta::getAlpha(int index) {
    return alphas[index];
}

void Beta::setAlpha(Alpha* alpha, int index) {
    alphas[index] = alpha;
}

void Beta::doStuffWithAlpha(int index) {
    Alpha* alpha = getAlpha(index);
    /* Alpha* alpha = alphas[index]; */ //This doesn't work either - same outcome.
    alpha->debug();
}

sketch.ino
#import "pointers.h"
Alpha a1;
Alpha a2;
Beta b1;

void setup() {
    Serial.begin(9600);
    Serial.println("SETUP()");
    Serial.println();

    a1 = Alpha();
    a1.setAlpha("Hello");

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    a2 = Alpha();
    a2.setAlpha("Goodbye");

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); a2.debug();
    Serial.println();

    Beta b1 = Beta();
    b1.setAlpha(&a1, 0);
    b1.setAlpha(&a2, 1);

    Serial.println("----- b1.doStuffWithAlpha -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println("Expected: Goodbye");
    Serial.print("Actual: "); b1.doStuffWithAlpha(1);
    Serial.println();
}

void loop() {
    Serial.println("LOOP()");
    Serial.println();

    Serial.println("----- a1.debug -----");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); a1.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(0) ------");
    Serial.println("Expected: Hello");
    Serial.print("Actual: "); b1.doStuffWithAlpha(0);
    Serial.println();

    Serial.println("----- a2.debug -----");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); a2.debug();
    Serial.println();

    Serial.println("----- b1.doStuffWithAlpha(1) ------");
    Serial.println("Expected: Goodbye");
    Serial.print("Actual:   "); b1.doStuffWithAlpha(1);
    Serial.println();

    delay(10000);
}

This sketch is quite straight-forward. It creates 2 Alpha objects and a Beta object and passes the two Alphas into Beta. The myriad Serial.print() statements produces the output below.
output
SETUP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha -----
Expected: Hello
Actual:   Hello

Expected: Goodbye
Actual:   Goodbye

//everything is fine up to this point...

LOOP()

----- a1.debug -----
Expected: Hello
Actual:   Hello

----- b1.doStuffWithAlpha(0) ------
Expected: Hello
Actual:   CÃoçëyc=Lä^ÜŽYw¸Nv†Ý¿  //uh oh...

----- a2.debug -----
Expected: Goodbye
Actual:   Goodbye

----- b1.doStuffWithAlpha(1) ------
Expected: Goodbye
Actual:   ÿß/ï //uh oh again...

Everything works as expected when running a1 or a2.debug() or b1.doStuffWithAlpha() in the setup() function.
The result of a1.debug() and a2.debug() works as expected in the loop() function.
The issue, as you can see, is when running b1.doStuffWithAlpha(0) or b1.doStuffWithAlpha(1). The output is usually junk, which suggests to me the pointer has been mangled and points in the wrong place.
I don't understand what is happening between the transition from setup() to loop(). At first I thought the issue was the "Hello" and "Goodbye" strings going out of scope, but Alpha::setAlpha() makes a copy of the C-string. Also, accessing Alpha::debug() in loop() works, as shown above.
I have tried variations on the above code, such as using a struct or an int for alpha instead of a C-string and the results are the same: Mangled values.
Have I done something obviously silly that my scant C++ experience hasn't picked up on, or is there some fundamental Arduino shenanigans at play?

Problem is local shadow variable b1 in setup() function declared as Beta b1 = Beta();. In loop() is considered uninitialized global variable b1.

I agree that is probably the problem. Also in your destructor for Beta you should delete the pointers you allocate in the constructor. I'm not wildly keen on doing new in a constructor at static scope either because of the static initialization order fiasco.

@TMa I can't believe I missed that! I must have been looking at my own code for too long! @NickGammon I agree that I should have a destructor, it was left out for just this example. Regarding the use of new in a constructor, how else would I do it? Reading the link you gave, the initialisation fiasco only affects classes/types declared in different compilation units. My code has both classes defined in the same file.

If the project ever gets large enough that you have more than one compilation unit, it may affect you. What you can do is have a begin method which is called from setup (eg. like Serial). Alternatively (or as well) you could set the pointers to NULL in the constructor (which is safe) and then allocate them with new when they are needed.


text:
ATtiny85. How do I burn a bootloader? What is the process?
I want to use all six I/O pins of an ATtiny85, that means also using the reset pin as an I/O pin, however, I found out that if I disable the RESET pin, I can no longer program the ATtiny using an ISP programmer.
However, I found out that there are bootloaders for ATtiny which, as far as I understand, allow me to program the ATtiny through USB, without the need of the RESET pin.
My question is: How do I burn such a bootloader (such as micronucleus for example) to the ATtiny85? And how do I need to connect the ATtiny to USB after that (like this?)? How do I program it after that? Keep in mind that in terms of burning bootloaders and modifying fuses, I am a complete newbie.
Also, I'm using the ArduinoISP sketch as my ISP programmer since I don't have a real ISP programmer, but as far as I read, that won't be a problem.
EDIT: I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

Burning a bootloader is the same as burning any other program.  But, if you get a bad one in there and change the reset fuse, you'll be stuck with it until you either get another chip or a high voltage programmer.  So I'd recommend you test your USB bootloader before changing the fuse.  Your software-USB code probably comes with a recommendation for a circuit to approximate the USB electrical interface.

I have just finished my Arduino-Plugin with full integration of TinySafeBoot (TSB) for ATtiny84A, ATtiny85 and ATmega328P.
The project can be found here:
https://mesom.de/atflash/index_english.html
https://mesom.de/atflash/tinysafeboot/index_english.html
You could use it as it is now, and then use the Reset Pin as an analog in. Only watch for the voltage never to go below 0.6 * VCC.
As an alternative you could modify the fuses in boards.txt to have this pin available:
Go to Arduino Preferences and click on the link to preferences.txt (Mine: /Users/stefan/Library/Arduino15/preferences.txt). In this folder navigate to /packages/atflash/hardware/avr/0.1.0. Open the boards.txt and go to the section
ATTSB85.name=ATtiny85 (TSB)(Int. 8 MHz)
Change the line
ATTSB85.bootloader.high_fuses=0xdf
to
ATTSB85.bootloader.high_fuses=0x5f
Restart Arduino and burn bootloader via Arduino menu.

If you even then want to get another Pin from ATtiny85: you can change the bootloader to use just one Pin for RX and TX (see the TSB website). But why all the effort? Simply take the ATtiny84A. It has 14 Pins instead of 8 and costs nearly the same.
Stefan

Yes, there are USB interfaces for ATtiny85. Just look at one of the open hardware designs out there, e.g. Digispark.
An USB interface is going to require two pins, so using one to save one pin doesn’t strike me as cost effective.
I agree with @FAD, that you don’t really need an USB stack, and simply could do a time-delay-at-boot thing with the UART pins.
HVSP (the high voltage programming) is not hard to do. If you’re already comfortable with ArduinoISP, you can try ScratchMonkey, which uses the same approach (with a 12V power supply and one transistor) to do HVSP programming.

The USB interface can be shut down e.g. with a jumper when not programming, or can be put to a use that doesn't interfere with programming. Reprogramming is normally done immediately after a reset.

True, if you use the reset pin as IO then you need a special programmer that I believe provide high voltage (12v if i remember) or something like that to apply a 12v source to that pin to force it into programming mode then program using a normal programmer (or another arduino). However, what you are looking for is something like what is being done in the Arduino. The arduino is programmed with a special bootloader through ISP so when you power the microcontroller that bootloader will execute first and for few milliseconds will check the UART pins for activities and if it sees something valid it switched into programming mode where it waits for the new code to come through UART (not ISP) and write that into the program location, otherwise the bootloader will simply hand the code execution to the existing program if any.
Here is a simple explanation of how it works:
Let say your microcontroller flash size is 1KB, and the bootloader is 100B so your program can be stored at location 101B+, and its max size is (1KB-100B).
So when the bootloader starts and there is no activitiy on the UART pins it jumps to the location of your program (at 101B) while if programming activity is detected it starts reading the new code and overwrites the flash starting at 101B (so it won't over write itself).
And you will need the USBASP to program the bootloader for the first time. And you don't program the ATtiny85 through usb since that chip doesn't support USB, however, you use a USB to serial chip/module that emulates serial protocol over the USB. Some atmel microcontrollers have built in serial support and others can be done through software emulation.

And as Chris suggested, don't disable the reset pin until you test and validate that your bootloader works.

http://www.obdev.at/products/vusb/index.html

You can also burn a bootloader to an ATtiny through a Arduino (UNO or equiv). Here are some instructions: http://highlowtech.org/?p=1695 or if you prefer a video: https://www.youtube.com/watch?v=qz-YMPY4_z0

Here is a nice page about programming ATtiny4 5 9 10 20 and 40 using SPI from an Arduino so it is not ATtiny85 but I thought it is related. Also one thing the blog mentions is that if you use the reset pin as I/O all you need is 12v source to trigger programming mode and you still can program it the same way, so no special programmer as I thought before. http://junkplusarduino.blogspot.com/p/attiny10-resources.html

@FAD, the 4/5/9/10 are completely different beasts from the ATtiny85. It’s true that they speak the same programming protocol (TPI) for high voltage and regular voltage programming, but that’s emphatically NOT true for any other ATxxx microcontroller.

I do have this thing I bought for a couple dollars on eBay, which I don't know how and if I need to to use:

it is infinitely better than your arduinoisp.
google avrdude / avrdudess.


text:
Can I simply unplug the Arduino usb if serial communication is active?
So, after the sketch is uploaded, and I want to turn the Arduino off while it is running a sketch, all I have to do is unplug it.
Should be safe as long as nothing is uploading.
But I wonder, if I use serial communication between the Arduino and my Computer in a sketch, does it harm either if I simply unplug it?

No, it won't harm your PC or arduino. Microcontrollers are actually pretty good at abruptly stopping and starting. The PC is just reading the stuff you send to it and at some point he won't receiver stuff anymore, but he won't care.

if the sketch is uploaded, it wont hurt it to unplug. Just give it another source of power and it will run its sketch.

So, even if there is serial communication, it won't harm them? Because, if I unplug my external hard drive during communication with my Computer, it can be very harmful. I don't want to fry the little one...

If you unplug the Arduino when it is running it will just shut off and no new data will be recieved or sent, the connection would just stop. So un plugging it wont do anything negative to the Arduino it's self but if the Arduino is using memory like an eeprom or flash, it may store corrupt data. Thats why it isn't advised that you disconnect things like hard drives when they are running. Although in reality just disconnecting the hard drive from usb wont damage anything because of safety features that are built in. Removing a built in hard drive while it was running would likely corrupt data.

You can unplug it, it does not harm.
If your arduino does not need power, eg. for writing EEPROM or FLASH, then no danger there.
(in case it was writing EEPROM/FLASH it could write it faulty but usually even that is not a problem either)

Yes, you can unplug it directly whether if serial communication is active or not if you dont need power supply anu more using usb cable


text:
delayMicroseconds- error?
running a very short program on a mega, just to generate a 8 microsecond wide clock pulse on pin 18, every 250 microseconds-
closest 'delay' values I can get are delayMicroseconds(3), and (83) off, gives a 7.5 microsecond wide pulse every 249 microseconds- any suggestions on a better way?
here is whats running:
int i=0;
int req=18;

void setup(){
Serial.begin(115200);
 DDRD = DDRD | B10000010;
 interrupts();
pinMode(req,OUTPUT);
}

void loop(){
i=1;
digitalWrite(req, HIGH);
delayMicroseconds(3); //gives 7.5 microsecond pulse?
digitalWrite(req, LOW);

while(i<83){//gives 249 microseconds start of pulse to start of next pulse?
 delayMicroseconds(1);
 i=(i+1);}
 }

Is there any particular reason why you don't want to use PWM?

from what I understand, PWM frequency is 'roughly' 490 hz, I need exactly 4000 hz. is there a listing of instruction processing times published somewhere for calculating overhead? Micros will give the whole thing, but not just the while-loop

Only if you stick to what Arduino gives you. Breaking outside the box makes things more flexible all around.

Try out the TimerOne library.

thanks guys- rethinking, reading Micros at various parts of the program can let me shift timing as needed to read next bit in the next byte- will only work for static conditions, but thats OK for now. Thanks for suggesting PWM- yes standard it clocks very slow, but it is accurate- the pulse duration of 1% just happened to give a 8 microsecond tick, triggering the device to send- the extremely long off time it didnt mind at all. thanks for the comments- this things all pretty new to me, but i see a ton of potential for building tools to repair our CNC components :)

This a very partial answer. I do not know your requirements, whether or
not PWM can do the job, etc... I just wanted to point out that you can
make a pulse exactly 8 µs long with this:
#include <util/delay.h>
#include <util/atomic.h>

// Pulse PD3 (digital 18 on Mega 2560)
// for exactly 8 us (128 clock cycles @ 16 MHz)
static void pulse() {
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        PORTD |= 1 << 3;
        _delay_us(8 - 0.125);
        PORTD &= ~(1 << 3);
    }
}

The _delay_us() function from avr-libc is actually cycle-accurate
inline assembly. The 0.125 µs I subtracted is the time needed by
the actual port writes: both the sbi and cbi instructions take two cycles
(0.125 µs), but that delay should only be counted once.
digitalWrite() should always be avoided in time-critical code.
The 242 µs delay between pulses would be harder to generate without
PWM. A timer interrupt at 4 kHz seems like the simplest option, but
it is not cycle-accurate.
Edit: here is the scope trace, showing a quite accurate timing:

Unless you want program PWM timer as suggested in comment then for short delays you need calculate how many instruction cycles are needed to make such a delay based on clock/crystal frequency and make that delay in inline assembler to have code under control. To manipulate digital output use writing data to PINx (which is equal to xoring PORTx).
To satisfy exact 250ms you need compensate errors because of rounding. Arduino's delay/tick functions do it. For the long delays you need a simple scheduler not to spend all the CPU time for pulse generating.


text:
Arduino as serial 'snoop' tool for 77 bits at 100k baud?
curious if a Arduino could be configured to read and serial print raw binary bits from a proprietary serial encoder used on machine tools and robots... if so, might have a lot of other possible uses.
I made up a 120 volt servo drive for manually moving big fanuc machine/robot servos, handy during rebuilding/service to be able to move a axis without a control...but the older drives read 4 gray code channels kinda like a set of halls for brushless commutation...on the serial versions, same drive could move the motor if I could decipher the commutation bits and output graycode to the drive... a tiny Arduino looks like a ideal little thing to try doing this.
Scoped out the signals long ago, kinda know where the bits are, but need to be able to actually print them out thru 90 degrees of shaft rotation to find the 12 steps for commutation required by the drive.
Arduino is new to me, but in the past few days have been quite impressed with its abilities. If anyone can suggest a way for Arduino to read a repeating 77 bit data stream at ~100K baud, I'm all ears... I think a 'serial snoop tool' with easily changed baud rates(including non-standard) and 'word length', then serial print out could be really handy. to prevent overflow in my case, could only do the serial print every X milliseconds, and I could just rotate slow enough to get a decent sample.

It should be possible, monitoring the I/O in software if not with the UART block.  But there are better tools for such a job, such as a CY7C68013A-based logic analyzer or possibly a bus pirate - the idea there is you stream an excess of data continuously to the PC, and then decode it in PC software.

thanks & I agree, that might be easier tool to read the data- but I also want to use the data to emulate 4 TTL outputs, and put it in the drive cable permanently...not really wanting to add a computer, just a small decoder- all I need is to extract the bits, and drive outputs emulating the old school brushless servo commutation tracks with a small stand-alone device. I truly think finding the signal and manipulating/outputting 4 digital signals will be the easy part- getting a 100K baudrate/77 bit word into the little Arduino (or another similar device with a few outputs) will be the hard part

Note that, for this to work, you'll need to maintain a 5V logic level signal for the UART to operate on.

not a problem, the drive has a regulated 5v supply for the encoder

getting 100k baud sorted out is my concern, as i dont know if i can use the serial monitor if using the rx pin to monitor the encoder- dont think so as it looks like the serial monitor will require standard 8 bit/'normal' baud selections...so may still need a logic analyzer to pick apart the bits initially. I'm thinking as a alternative, just to do a 115200 repeat dump of some 77 bit patterns I have already stored from a old laptop. just need to get the arduino to receive it.


text:
Duplicate libraries while compiling for ESP32 in the Arduino IDE
I have just added the ESP32 toolchain to the Arduino IDE (v1.8.0) on Windows 10.  To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" (Yes my C drive is called D, its a long story)
I managed to compile and run Blink and after several minutes of celebration I tried the ESP32 Example Wifi->WifiScan.  It failed to compile because
WARNING: Category '' in library OneWire is not valid. Setting to 'Uncategorized'
In file included from D:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\spi_drv.cpp:21:0:

D:\Program Files (x86)\Arduino\libraries\SPI/SPI.h:16:26: fatal error: avr/pgmspace.h: No such file or directory

compilation terminated.

Multiple libraries were found for "WiFi.h"
 Used: D:\Program Files (x86)\Arduino\libraries\WiFi
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\WiFi
Multiple libraries were found for "SPI.h"
 Used: D:\Program Files (x86)\Arduino\libraries\SPI
 Not used: D:\Program Files (x86)\Arduino\hardware\espressif\ESP32\libraries\SPI
exit status 1
Error compiling for board ESP32 Dev Module.

If I am reading this correctly, there are a couple of duplicate libraries, Arduino versions and ESP32 versions and the IDE picked the Arduino versions.
Is there a way of telling the IDE to prefer the ESP32 libraries rather than Arduino ones?  I suspect all I need to do is change the order of the -I and -L commands, but I don't have a clue how, or if that's the right thing to do.

Why do you have WiFi and SPI libraries in your contributed libraries folder...?!?!

In an attempt to rename the directory I found that the espresiif\ESP32 directory is locked by a system process PID:4 which is holding handles on 10 of the files within those directories.  I uninstalled the drivers for the esp32, no joy, logged on as admin and ran as admin, but no joy.  I had to alter the security permissions so that System couldn't access that directory reboot and then delete espressif\esp32.    At this point I also unistalled Arduino IDE and re-installed a fresh copy of 1.8.3. [continued]

I followed the installation instructions (without using GIT) and 'installed' the esp32 pack to D:\Users\***\Documents\Arduino\hardware\espressif\esp32 and again, the same result the IDE does not pick up the ESP32 boards, but does pick up the esp8266 boards.    If I move the libraries to D:\Program Files (x86)\Arduino\hardware then the IDE detects the boards and when I compile the example I get a duplicate WIFI.h BUT it now picks the esp32 version.  I think the problem is why doesn't it work when the esp32 folder is in My document?

"I think the problem is why doesn't it work when the esp32 folder is in My document". Probably because you have a different sketchbook folder configured (see File > Preferences > Sketchbook location).

"when I compile the example I get a duplicate WIFI.h BUT it now picks the esp32 version". OK so you correctly named the architecture folder and it solved the problem, just as I said in my answer, so why didn't you accept it?

Please don't delete your question after someone has taken the trouble to answer it. I have undeleted it.

#include "filename.h" will look in the sketch folder
#include <filename.h> will look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path

So the system library path (-L) is defined in perferances.txt, thanks for that.

#include <filename.h> will only look in the path, defined in File | Preferences, edit preferences.txt, search for sketchbook.path this is wrong. The libraries subfolder of the sketchbook is only one of 6 folders in the include path in a standard hardware package, none of which are configured in preferences.txt. There is no need to edit preferences.txt, you can just do File > Preferences > Sketchbook location. Also, take a second to actually view your answer before submitting it to see how the markdown is being rendered.

The problem is that you have incorrectly installed the ESP32 hardware package. If you look at the official installation instructions:
https://github.com/espressif/arduino-esp32/blob/master/README.md#installation-instructions
you'll see that the architecture folder should be named esp32, not ESP32 as you have named your folder.
When multiple libraries contain a header file of the same name, one of the factors the Arduino IDE uses to decide which gets precedence is architecture matching. The architecture of the selected board is determined by the name of the architecture folder of the hardware package of that board. So because you named your architecture folder ESP32, that's the architecture value of the selected board. The architecture of the library is determined by the architectures property value found in the library.properties file of the library. In this case that value is set to esp32:
architectures=esp32

So because the architecture value of the library in the ESP32 hardware package doesn't match the architecture of the selected board, the SPI library found in the Arduino IDE installation folder is used instead.
If you rename the architecture folder to esp32 the correct library will be used.
A few other notes:
For some reason you have put a copy of the SPI library at D:\Program Files (x86)\Arduino\libraries\SPI. This makes no sense because that library is architecture specific. Each hardware package has its own version of the SPI library bundled.
In addition to using the incorrect architecture folder name in your installation of the ESP32 hardware package, you installed it to the Arduino IDE installation folder instead of the sketchbook folder, as recommended in the instructions.
You seem to have a bad habit of messing with your Arduino IDE installation folder. You should never modify or add files to the Arduino IDE installation folder. The reason is that all changes you make to that location will be lost anytime you upgrade to a new version of the Arduino IDE and it also makes troubleshooting more difficult since you are working with a non-standard installation. Instead you should always install libraries and hardware packages to the sketchbook folder where they will persist through IDE updates. I recommend you to move any customized files out of the Arduino IDE installation folder and then reinstall the IDE to make sure you are working with a stock installation.

per1234, I'm sorry but you are wrong.  I have never altered anything in the Arduino install folder.  Everything that is in there was installed in there by the installer or the board manager.

To get the IDE to allow me to select ESP32 chips I had to place the Espressif folder in "D:\Program Files(x86)\Arduino\hardware" "D:\Program Files(x86)\Arduino\hardware" is your Arduino IDE installation folder, correct?

Then where do you have the Arduino IDE installed?


text:
Serial Communication over Desktop to Arduino
I have a USB 2 Serial adapter and the device is working fine. I see the device perfectly configured in my System.
I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter. Below is my Arduino code:
int i = 0;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  for(i=0;i<6;i++)
  {
  Serial.write('H');
  delay(100);
  }
}

But when I try to read thru terminal software of data received at my COM port I see some junk character incoming. I am pretty sure that I am using same baud rate / flow setting both side. Why am I facing this issue - do I need to connect any other pins also as I just need to receive data at system side?

I have a USB 2 Serial adapter...I have connected the TX0 pin of Arduino to DB 2 pin (read pin) of the adapter.

You must not connect Arduino pins directly to a D-SUB connector of a USB-Serial adapter, as those connectors traditionally carry higher voltage, opposite sense RS232 signals.

The voltage is too high, and likely to cause damage to your Arduino's processor
The signal is inverted in sense from the logic-level signaling used by your Arduino's processor.

If you actually needed to make this connection, you would need to either use a "logic level" USB serial adapter (sometimes informally called a USB-TTL adapter).  These terminate in various types of connections such as bare wires or header pins/sockets - but basically never in an D-SUB connector.  Or you can use an inverting line driver and receiver such as the MAX2232 type devices, or even an old 1488/1489 pair.
But it's not clear that you should be doing this at all - an Arduino Mega already has a USB-serial converter onboard - that is the interface you use to program it, and it would ordinarily be simplest to use that for runtime communication as well.


text:
Data at Serial Port Avaliable
I am interfacing a GSM modem via Arduino at Serial port 2.
I have seen that responses fron GSM modem are subject to time. Sometime its response are fast and sometime it are slow. I  have a code like below which checks for response from GSM modem based upon a user configurable timeout value:
sendATcommand(str_at_cmd, str_ok, 500);

int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
    uint8_t x=0;
    char response[100];
    unsigned long previous;
    int answer = 0;
    memset(response, '\0', 100);
    answer = 0;;
    delay(100);
    ClearSerialData(); // read and flush all data
    debug_println(ATcommand);
    Serial2.println(ATcommand);
    delay(200);
    x = 0;
    previous = millis();
    do {
       if(Serial2.available() > 0){
       response[x] = Serial2.read();
       delay(100);
       debug_print(response[x]);
       response[++x] = '\0';
       if (strstr(response, expected_answer) != NULL)
       {
           debug_print("\nAnswer Mathced");
           answer = 1;
       }
       }
    }while((answer == 0) && ((millis() - previous) < timeout));
    debug_println("\nReturning from AT Command");
    return answer;
}

I was never able to set the correct timeout value - as at random test it failed once or twice and not received 100% success.
My question if I change the code like below
while(Serial2.available() > 0){
   response[x] = Serial2.read();
   delay(100);
   debug_print(response[x]);
   response[++x] = '\0';
   if (strstr(response, expected_answer) != NULL)
   {
       debug_print("\nAnswer Mathced");
       answer = 1;
   }
}

So when does Serial2.available() method returns <= 0 value. Is my above code correct - this way I overcome the timeout issue and all my GSM responses are being read - are there scenarios that I will end up in infinite loop?

You will end up in an infinite loop if you never receive the expected response.  If you are receiving other responses, or noise, you could easily overflow your array, so you should put a hard limit on the growth of x.

Your code is flawed in that you are waiting a fixed time, and then hoping that the entire response will arrive quickly. Personally I would send the query, and then exit the function. Test for incoming data in your main loop, and process it when it is all received. Techniques described here: http://www.gammon.com.au/serial
The whole thing should be able to be written without delay().


text:
Servo limitations vs SoftwareServo
I heard that Servo library cannot send and receive from other arduinos without inturrupting the timer and messing up the motors. SoftwareServo is supposedly the answer to this. Is this true? Neither libraries are working for this problem at the moment.

What is your question, exactly?

You'll have to be specific about how they are not working.  Also, how are you trying to communicate with the other boards?  A software serial might use a timer conflicting with some version of servo code.

I'm not sure which SoftwareServo library you are talking about, but with regards to the built in "Servo.h", no, it will not disrupt the arduino's other communication abilities, and they will not disrupt it.
I've used servos simultaneously with Serial, I2C, and SPI before and never had any problems.
The servo library does use a timer, but it will only conflict with an external library or code that uses the same timer. Which timer it uses depends on the board, just look in libraries/Servo/src/avr/ServoTimers.h to see which it uses, in what order as they fill up. Filling one up takes effort though, by default it puts up to 12 servos on each timer. The processing overhead is very low since they only update at 50Hz, so that will not become a problem.


text:
Arduino error in code Stack smashing protect failure!
I get the error when I compiled my code below. I am making an application to read temperature on board ttgo esp32 oled lora
stack smashing protect failure!

abort() was called at PC 0x400da3e8 on core 1

Backtrace: 0x4008b8f4:0x3ffb1ec0 0x4008bb21:0x3ffb1ee0 0x400da3e8:0x3ffb1f00 0x400d0f69:0x3ffb1f20 0x400d0f73:0x3ffb1f50 0x400d366e:0x3ffb1f70 0x400d12f7:0x3ffb1f90 0x400d68a9:0x3ffb1fb0 0x40087a71:0x3ffb1fd0

Rebooting...
ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 188777542, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1100
load:0x40078000,len:9344
load:0x40080400,len:6348
entry 0x400806a8
Node v0.2
Trigger Temps
Read Temps = 25.50
Read Temps = 25.50
Send Temp: 25.50
Packet queued
238190: EV_TXCOMPLETE (includes waiting for RX windows)

Code is in => https://github.com/Mangulomx/ds18b20_lora1/blob/master/ds18b20_1_lora.ino

why are you using the arduino-uno tag?

when I compiled my code below - a) there is no code below, and b) that doesn't look like a compilation error, more like a runtime error


text:
Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors
I am using two motors ( from old two drill machines - same kind, these are 3.6v motors ), connected to arduino + arduino motor shield seeed studio v2.
When I measured the both motors (indvidually) using a multimeter in series with your motor and an about 3.6V power supply, I found that the both are varying from 1.46A-1.47A, (I supposed it as 1.5A)
I tried to use 18v/1.2a battery that was laying at home (from old machine ) what I have noticed is that motors are running for 3-5 seconds than stop, one of the red lights start blinking in the motor shield, then it stops for 3-5 seconds then it works again and loop.
Notes:
- The motors are working when I connect them directly to 4.5 or 6v battery. But when I try to assemle everything , it doesn't work (I am adding this just to say that motors are in good health).

I tried 14v battery I noticed the same thing.
The drill machine is small one (as big as a human hand). Motors from electric drills are designed as high-speed high-torque motors, but I don't think it's too high in my case to be a huge problem. It's 200 RPM DC motor
I spent a week looking for answer before posting this thread, I tried every single solution I came across on the web.

What are things that I should consider here, any thoughts.
What did I miss? And what kind of battery should I use ??

I have run into similar weirdness myself, and the solution that worked for me is to have separate batteries for the Arduino and the motors. This is more important if your motors run at a different voltage (e.g. 6v or 12v motors), but is useful in any case. This means that, when the motors draw to much from the batteries, the motors will slow down. If the same battery is used for the motors as for the Arduino, then the voltage drop from the motors will also apply to the Arduino; if the voltage drops in the Arduino, it will turn off (and turn back on when the voltage is restored). This is likely what you are seeing.

i've just run to try what you have said. I used 9v battery for arduino and ten (10)*1.2v batteries in serie to make a battery of 12v. WHat I ve noticed is that the motors are taking some time before they move (say 5-10 seconds). I don't use sleep() in my program. What I have made is a one command (to debug the problems) to make the both motors moving at 255. Is there any raison behind that ?? One more thing, the motors are moving slower than they supposed to do ? 12v is good voltage to make them run fast.

Check the voltage across the batteries used to power the motors, a high load may cause a voltage drop. Also, in your sketch, try turning the LED on immediately after or before turning on the motors - there may be a delay for some reason you're not expecting.


text:
Which IDE should I use to write Pythonic-programs for Arduino
I'm doing my first baby-steps to build tools using Arduino. I'd like to know if there is a way to write python scripts to build programs for Arduino. Most of IDEs I found are non-supported IDEs. Is there any "recommended" IDEs that I should use.

Before asking about an IDE you should ask if it's even possible in the first place.

The recommended IDE for writing C/C++ for Arduino for beginners is the formal Arduino IDE, of which you can read more on the arduino.cc website.
Python is an interpreter language, and as such, require an interpreter running on the target machine. Unfortunately, the Arduino does not natively support running an Python interpreter, although some efforts has been made in that direction, for example the Python on a chip project, or the Python Arduino Proto API v2.
See this SO question for more details. If you go with any of these options, the IDE you would use would be your favorite Python IDE.
Note that both projects have their downsides, and actually there is no real alternative equivalent to running compiled C/C++ code on the Arduino. If you have strong Python programming abilities, this shouldn't be too hard for you as well :)


text:
Using a relay to control a lamp
Okay, so I'm using an Arduino Uno R3 and I wanted to start of my own home automation project. I have a 4 channel 12V relay board and I normally connect it to a 12V 500mA adapter. What is the maximum wattage bulb (or CFL) that I can power with this configuration?

The ampere rating should be printed on the relays. Watts = Amps x Voltage

@Gerben. Thanks for the heads up! It says 5A 240V AC and the coil is 12V DC.

Than that's 1000Watt if you're on 220V AC, 500Watt if your on 110V AC (e.g. US). Good luck finding a 1000Watt CFL :-P

Unless you feel like starting a fire, none. Find a 220V 2A relay with a 5V coil and use that instead, switching the hot wire and not the neutral.

Huh? If the OP builds a circuit to switch 12v (with a flyback diode) why would the relay board in question start a fire?

@DuncanC: There aren't many CFL bulbs that run on 12V, and the asker hadn't given the contact specifications yet.