text:
Turning my GPS logger shield off and on
I have a Sparkfun GPS Logger Shield and I want to save power by shutting it off when I do not need GPS readings. Now reading the hookup guide it says that the "EN" pin can do this: "Active-high chip-enable – pull low to reset or turn off".
I wanted to ask some advice as to what this actually means and how I safely go about it. Is it as simple as:
pinMode(pin, OUTPUT);

//turn off
digitalWrite(pin, LOW);

//turn on
digitalWrite(pin, HIGH);

Where the pin is a digital pin on the Arduino and it is connected to the "EN" pin of the GPS shield.

Please note that when the GPS is turned off, it is not tracking satellites. That means that when you turn it back on again, it doesn't have the faintest idea where it is. To find out, it has to listen on all channels looking for one satellite to at least tell it what time and date it is. Once it has that, it can start to calculate satellite orbits and guess as to which satellites are where. As it gets more and more information, it will finally start to resolve its location. According to the GP3906 datasheet, this can be as much as 35 seconds from Cold.

Yeah, I figured it would require a little run up time to determine where it is. I also have a GPRS module that will also need a run up time to obtain signal. I was planning to test out a number of different wake times to ascertain an effective, but still short duration.Thanks for the extra detail on the 35 seconds for this GPS module, that should come in quite helpful!

Take a look at SparkFun's datasheet. It's got all sorts of info: https://cdn.sparkfun.com/assets/learn_tutorials/4/6/8/GP3906-TLP_DataSheet_Rev_A01.pdf

Yes, it is as simple as that.
However, since the pin is pulled up already you could also do this:
pinMode(pin, INPUT);
digitalWrite(pin, LOW);

// Turn off
pinMode(pin, OUTPUT);

// Turn on
pinMode(PIN, INPUT);

That then emulates an Open Drain pin which means you're not actively driving the pin when turned on, only when turned off.
Personally I prefer system that are active low not active high, and are pulled down by default (normally off) so that you don't waste power driving the pin in order to save power (it's kind of silly really) - you drive the pin to turn on and let the pin float to turn off (especially good with deep deep comatose sleep on some MCUs where the IO pins all switch off).
However the designers of this module decided otherwise, so you're stuck with driving the pin LOW to make it sleep.

I'm just trying to understand your example and how an open drain works. So an INPUT of LOW is pulling down (0v)? How is an OUTPUT of LOW pulling up?

Sorry, other way around (coffee hasn't kicked in yet).  Output of LOW pulls down. Input of LOW floats (internal pullup disabled) allowing module's pullup to pull it high.

Ok that makes a bit more sense to me! Where you say 'internal pullup disabled', is that something I actively have to do?

I think I found the relevant information with the fact that using pinMode INPUT automatically disables the internal pullup.

INPUT with the output LOW has the pullup disabled. INPUT with the output HIGH has the pullup enabled. Or INPUT_PULLUP is the same.

When the pin is set as an input, it can be set to have a pullup or not to have a pullup. The difference is whether you pass INPUT or INPUT_PULLUP to pinMode()


text:
Stepper Motor Power Supply
Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.
Ordering:
2 x Stepper Motor
2 x EasyDriver
An article says

You need some 12V source to the EasyDriver (the motor in this article
  is 12V) - This will be powering the stepper - Im using a 12V adapter -
  similar to the one in the illustration. Just make sure it is rated at
  least 750ma - A higher rating is better, and just means it wont burn
  out.

So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?
Just don't want to break anything! Thanks

This is the article.

To clear things up also:
I was just trying to combine the project into one single power supply as it currently sends data wirelessly and this would mean I wouldn't need the USB to PC. Any suggestions as to what type of power supply I could use so I only have a single wall plug?

As generic rule: avoid powering one device through another.
It can cause strain on the middle-man device and it will be inefficient.
The only few cases where this might make sense are when it's topologically inconvenient to connect everything to the centralized power supply.
Or if the cascaded device requires a voltage that is not available from the power supply.
In your case you can power both the easy driver and the Arduino from the regulated 12v.
And you won't risk drawing too much current through the Arduino.

If I had a 12V 1A plug like this cut off the 2.1mm plug, exposed the wires and applied power to a breadboard rail. Would it be sensible to then power the arduino using the VIN pin and then use the same rail to power the easyDrivers?

I'd rather use something like this http://www.ebay.com/itm/MB102-Breadboard-Power-Supply-Module-3-3V-5V-For-Solderless-Bread-Board-IN-/181803793177?hash=item2a5459bb19 where you can power the breadboard with a voltage that will not heat up the regulator in the Arduino and you cna still access the raw 9V from a pin header. But yes, what you propose will work too.

Where is the raw 9V pin on that board? I can only see the 5V and 3.3V jumper for each rail and the 5.5V/3.3V/GND pins?

Sorry, I mistook the component south of the switch for a pin header.
No, you would have to solder a pair of wires from the pins of the connector, on the bottom side of the board.

You should not run your stepper motor power through either the Arduino or (except for extremely small motors) a breadboard.

Stepper Motor Control - one step at a time
This program drives a unipolar or bipolar stepper motor.
The motor is attached to digital pins 8 - 11 of the Arduino.
The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.
Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.
#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0;         // number of steps the motor has taken

void setup() {
    // initialize the serial port:
    Serial.begin(9600);
}

void loop() {
    // step one step:
    myStepper.step(1);
    Serial.print("steps:");
    Serial.println(stepCount);
    stepCount++;
    delay(500);
}

The Vin pin is after the M7 protection diode, so you won't get quite 12 V out of Vin. Also, depending on the load, the diode might get warm.
I've also found that powering an Arduino from 12 V input (the maximum recommended) tends to get the voltage regulator hot.
Your other issue is that the motor power will be going through the Arduino board, to an extent (in the plug, through the diode, and out Vin) so any noise generated by the motor will be close to the processor.
I don't think your idea would break anything, it just might not be particularly reliable.

source: Stack Exchange

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

sort: votes


text:
HUGE deviation in Sharp IR sensor values if other pins are defined in void setup()
I wrote this code for a project -
int sensorpin = A5;
int val = 0;
double avgval = 0;
int E1 = 11;
int brake = 12;
char data = ' ';

void setup()
{
  Serial.begin(115200);
  pinMode(E1, OUTPUT);
  pinMode(brake, OUTPUT);
  pinMode(sensorpin, INPUT);
}

void loop()
{

  if (Serial.available()>0){
      data = Serial.read();
    }

  val = analogRead(sensorpin);
  avgval = average(val);
  double volt = (avgval*5)/1023;
  Serial.println (avgval);
  Serial.println(volt);
  delay(1000);

  if (data == 'G'){
    analogWrite(E1, 255);
    digitalWrite(brake, LOW);
  }

  if( volt > 1.5 && volt < 1.75 ){
    digitalWrite(brake, HIGH);
  }
}

double average(double adc){
  int n = 1;
  double avg = 0.00, sum = 0.00;
  while(n<=23){
    sum = sum + adc;
    avg = sum/25;
    n++;
  }
  return avg;
}

The code works fine, except for the fact that the Sharp IR sensor (GP2Y0A710K0F) outputs values which are wrong (by a HUGE distance), ONLY if in the void setup() function, the commands -
pinMode(E1, OUTPUT);
pinMode(brake, OUTPUT);

are left uncommented. If I comment the above two statements, the sketch works fine.
What on earth is wrong here? I can't make out anything.

Not sure why commenting out those two lines makes a difference.  I think we need to see a schematic to resolve this.
However...
You do not use "pinMode" to setup an analog input!
Look at the examples on the "analogRead" page.  Notice there is no setup needed for the analog pin.  Just call "analogRead" like you are doing and everything should be fine.

And that was it! Removing the line pinMode(sensorpin, A5) and uncommenting the two lines solved my problem. Getting the expected readings now. Thanks very much! That was something I should have noticed long ago.

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


text:
How to modulate my IR sensor?
I'm looking to use a simple IR sensor out in bright sunlight, which means hell lot of distortion. Is there any way I can modulate it using my Arduino UNO so that it isn't affected by sunlight and other ambient light sources?
The IR sensor is just like this one.

You modulate the source, not the sensor.  Modulation is basically blinking an LED really fast, typically around 36-40 KHz - and is ideally done with a hardware timer rather than delays, but the latter is possible.

@ChrisStratton and is that possible with my sensor? If yes then how?

If you want to do analog IR measurement in the presence of noise, you probably want not only a modulated source, but a synchronous detector or lock-in amplifier.  I don't see much engineering detail of your board, but it looks a little simple to implement that.  An almost entirely software solution should be possible, but will require learning quite a bit in order to write.

There is little information on the Amazon page about these devices.  Only that the output is digital (only on and off) and that the sensitivity is controlled manually by an on board pot.  It would appear impractical to enhance this type of device with out detailed specifications and / or a schematic.
If you would prefer using software to solve some of the problems you listed, I would suggest you use an IR parallax (not the company, the technique) distance sensor with an analog output.  That way the Arduino Uno's analog input can be used to read the sensor and software (sketch) can process (filter) the data before it is put to use.
Added later...
Here is an article describing how to use an IR parallax distance sensor.  Here is an Arduino library design to work specifically with the Sharp IR parallax distance sensor.

I tried reading this sensors data with analog input, all I got were 3 digit numbers which made no sense to me. Any idea of what to do?

The web page you linked to in your question said the sensors' output is digital.  It gave the voltages to expect.  As such, using the complex ADC feature of the Arduino gives no advantage to using a simple digital input.  If you do use the ADC input, you should expect to see only numbers around 0 and numbers around 255.  If you want an analog output from a distance sensor get a Sharp IR parallax distance sensor as suggested in the solution.

Yeah I already was looking for one, will this be good enough?
http://robokits.co.in/sensors/sharp-ir-rangefinder-gp2y0a710k0f-100cm-to-550cm
Also please consider that these sensors are to run in bright sunlight...

No sensor will always work.  Bright sunlight is only 1 problem.  A surface that does not reflect IR radiation is another.  I have not used this specific sensor but other similar sensors work well in bright room light.  The only problem I have had was when a bad florescent light bulb that was failing.  Evidently it was also radiating similar IR modulated signals.  You might consider using ultrasonic range sensors if these IR parallax sensors are difficult to use under bright sunlight.

I used an ultrasonic sensor but the doppler's effect renders them unusable

Moving too fast for ultrasonic?  Well, I'm now starting to think LIDAR or stereo cameras and computer vision.  But now we are talking expensive solutions well past what one would use an Arduino Uno for.


text:
Did I fry my servo?
I got a new servo a few days back (RC Servo, Futaba FP-S148). I first tested it out with the Sweep sketch on Arduino, powering it with the Arduino 5v and GND pins only. It was working, just fine.
Today I was trying to use it in my robot and I tried powering it with 2 LiPo batteries (Samsung ICR16850 2200mAh, from an old laptop battery) connected in series, giving 8.32v. As soon as I connected my servo, it started rotating randomly, I had not connected it to my Arduino yet. I quickly took it out.
Next, I used a L7805 to get 5.13v regulated supply out of my batteries that I used earlier. When I connected my batteries to the servo, and the servo to the Arduino, uploaded the sketch, the servo started behaving rather strangely, it first did a complete turn and then stopped. Only a humming sound came from the servo. Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire.
Otherwise, the servo just gives a humming sound.
I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.
Have I fried my servo? Or is it some other issue?

If it doesn't work and it used to, under the same conditions. It's broken.

@Paul broken in the sense burned out by using higher voltage than the limit?

@YaddaVirus I meant in general. In a device that does not have memory. If something did work, it should still work. And if it doesn't, it's of no use. (If you can't repair it)

8.32v is greater than 6v. You can expect it to do horrible things.

@Majenko which means a fried servo?

@YaddyVirus it is extremely hard to answer that definately. Given the information, it seems very likely.  But, more than often, only the weakest component will fail, you might troubleshoot it and replace that component.

As soon as I connected my servo, it started rotating randomly,

The random movement could be from a floating control line, i.e. random voltages signals are being interpreted as random positions, and the servo is responding.

I stripped down the servo and checked the motor. It is working fine. Moreover now the servo doesn't even makes the humming sound. It just sits there, no movement, no sound.

Assuming it was put back together properly, then it sounds like the control circuitry has been damaged.

I had not connected it to my Arduino yet. I quickly took it out.

Have you tried it on the sweep example again, or a servo tester? It could be working.

Strange thing is, whenever I connect one of my Multimeter leads to the power cables, the servo immediately turned in the opposite direction only as long as only lead was in contact with either the positive or negative wire.

Sounds like you are accidentally sending it control signals with your multimeter.

Your servo is dead if:

it is properly connected and doesn't respond to any control signals
it is properly connected and responds randomly to control signals
it is properly connected and responds randomly to a grounded control line

n.b. unconnected (floating control lines could cause random behavior in an otherwise good servo).

I did try it again with the sweep example, it didn't work. Most probably gonna have to get a new servo.

Since a servo is basically the combination of this components:

Motor
Gearbox
Position sensor (i.e a potentiometer)
Motor control electronics (e.g some useful stuff to protect the system and to relate d.d.p. over it's node to position => angle[i.e could by just an operational ampifier])

The unusual behaviour could have been raised by a single component of the system, most likely the variable resistor.
There's no guarantee of sucess, but maybe we can use this event to discover soimething!
My advce is try to discover the potentiometer used by the producer of the servo by looking at related datasheet. Then solder/attach temporarly an half-value or a quarter-value, resistor if the servo change it's orientation consider a replacing, if not just get rid f it.
Hope helps :)
Reference https://www.pololu.com/blog/15/servo-servo-motor-servomotor-definitely-not-server

Umm thing is, a replacement isn't very easy for me. Servos here cost a lot, both offline and online. I did open up my servo and I didn't find any signs of burns or something on the PCB under the motor.. And the motor is working just fine.

@YaddyVirus How you mean? I can order a 3$ servo off e-bay with free shipping to almost everywhere. It's logical that a better quality servo will cost a little more. But if you can't repair it, it'll be the only way to go. Test the potentiometer and motor individual. And/or contact the manufacturer for a replacement control-circuit.

@Paul the cheapest servo I found, (not talking about Mini servos) costed about 350 Rupees (roughly 5.25 $) + shipping. Both on Amazon and E-bay. While that may not sound expensive, for a teen who blasts away all his already little pocket-money on electronic components, that sure is expensive.

@YaddyVirus "blast away" indeed. If it's that expensive, why didn't you check the datasheet, a quick search told me it's 6V max. You've now "wasted" about 1 to 3 hours debugging a dead servo, you could've used that time to wash your parent's car for some money ;)

@YaddyVirus It's good to see that you're at least using your money for something good. Learning electronics can come in very handy! You should convince your parents of this matter, they might support you (financially).
I have the feeling that you're quite sure the servo is broken, but just don't want to accept it. If you can get a little more money (with work or by funding) you'll be able to make mistakes and re-order stuff (or take on bigger/other projects). If you've learnt to first check the rating, you might say it was worth even more than 5$ (could've blown up a $30 part).

@Paul You got me there dude. Actually this servo was given to me by my Robotics teacher, I'll be representing my school ( CMS ) in an international robotics competition in July, hence my parents are supporting me more than they ever did until now (dad bought me a RPi 3, got me an internet connection) etc. My school's helping me as well. As for the servo it was my mistake... I assumed that 8v should be enough and didn't check the datasheet. I didn't waste 1 to 3 hours but 2 entire days. All in which I could have done a lot more work as well as studies.

But I guess this is the experimental phase for me, I gotta learn from my mistakes. My parents think that I should focus on my academics more and hence keep a check on my R&D by limiting my finances. :P

@YaddyVirus true, let's say you earn 5$ an hour, if you've got a 20$ part, it won't be worth to troubleshoot it for more than 4 hours (4x5$ = 20$) more than often, buying a new one will be more profitable. I would donate/sponsor you the servo if there is an easy way. Burning a 5$ servo to learn to check the datasheets first is a 5$ well spent. It's good to hear that people support you. Learning on how to interface with a servo is more usefull as a lot of "academic things" I learnt. Isn't your study related to electronics/embedded systems then? (Also, this isn't really the place to chat).

You might also want to accept one of the answers, since I think you figured out you should buy a new one. Based on if the new one will, or will not work in the same conditions, you can tell that the other one is defective. (If they're both working, they should both behave the same.)

Well, I'm still in 12th standard as of the ISC board of education in India. I'm still in normal school, a science student with Physics, Chemistry and Mathematics, along with Computers. I'm readily looking for work here though, I gotta build this project asap! @Paul ;)


text:
'dynamic_cast' not permitted with -fno-rtti
class A {
    virtual ~A();
}

class B : public A {
    public:
      int foo;
}

void bar(A *foo_){
    B* b = dynamic_cast<B*>(foo_);

    if(b != nullptr){
         cout << (*foo_)->foo << endl;
    }
}

int main(){
    B b{};
    bar(b);
}

Compiling error:
error: 'dynamic_cast' not permitted with -fno-rtti

I thank sincerely for the help.

What board are you trying to compile for?

Arduino Mega2560

What IDE version and boards package version do you have?

PlatformIO and arduino-1.8.5

It seems avr-gcc version 4.9.2 that is used by the Arduino IDE has been compiled without RTTI support. It defaults to -fno-rtti, and if you try turning it on with -frtti you just get other horrible linker error messages instead.
So it looks like you can't use dynamic_cast on AVR boards.
Googling around it looks like numerous people have tried to enable FTTI on Arduino, but they have either failed and given up, or they have succeeded and never bothered to tell anyone else how they did it (numerous forum posts of "how do you do this?", a bit of discussion, and then they tail off...)
The solution? Either don't use RTTI, or use a more capable microcontroller whose compiler has RTTI enabled.
One way to not use RTTI is to fake it yourself:
#define CLASS_A 1
#define CLASS_B 2

class A {
    public:
        virtual int classType() { return CLASS_A; }
};

class B : public A {
    public:
        virtual int classType() { return CLASS_B; }
        void bar() {
            Serial.println("Baaaah!");
        }
};

void foo(A *foo) {
    if (foo->classType() == CLASS_B) {
        B *foob = (B *)foo;
        foob->bar();
    } else {
        Serial.println("Sorry, I can't bar.");
    }
}

void setup() {
    Serial.begin(115200);
    A a;
    B b;
    foo(&a);
    foo(&b);
}

void loop() {
}

Output:
Sorry, I can't bar.
Baaaah!

You gave a band-aid solution. It is already valid.

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


text:
Why does the Arduino Uno WiFi network connection drop when requesting a page?
I see frequent errors where the network connection to my Arduino Uno WiFi drops when I am requesting a web page. I wrote a simple REST server, and some of the pages will load as expected, but others will fail after loading half of the the text, and I notice that the network connection drops in the middle of these events. Why is the network connection dropping like this?

Hard to tell without code.

I saw this error when I was running low on RAM. The Arduino Uno WiFi appears to drop the network connection in low memory situations. One fix that made a significant difference for my program was to wrap all of the string literals in the F() macro. This moves the strings from ram to flash storage, and in my case quickly freed 500 bytes of SRAM (25% of the available RAM on this board).
For example, replace:
client.println("HTTP/1.1 200 OK");

with
client.println(F("HTTP/1.1 200 OK"));

Some other memory optimization may also be necessary.
Another possible cause of these symptoms would be low voltage, possibly from trying to draw too much power from the board to power external devices, but in my case there were no external connections, and I confirmed it was a low-memory issue.


text:
FT232RL Chip pinout to flash Arduino Pro Mini
Looks I have a FTDI USB to TTL adapter that doesn't follow the standard Arduino FTDI pinout order. The chipset is FT232RL and here is the link to Amazon page.
https://www.amazon.com/Adapter-Serial-Converter-Development-Projects/dp/B075N82CDL#customerReviews
Please can someone tell me the right pinout to connect this to Arduino Pro Mini 3.3v Thanks!

All the pins are clearly labelled, and they are exactly the same as any other FT232 board. Where is the confusion?

This is the standard FTDI Basic connections. CTS is an input to the module and is typically just connected to Gnd as seen on the right side here from the Arduino Promini schematic (so the FT232 is always Clear(ed) To Send, i.e. no flow control is used).
DTR may be broken out on one of the side holes.  RTS may work for you in place of DTR to create the reset pulse to start the bootloader code.  If not,  you may have to cut the trace and wire the RTS header pin to DTR. DTR is pin 2 on the FT232, use a meter and confirm it goes to one of the side holes, that way  you don't  have to try a solder a wire on to a pin.

Thank you @CrossRoads for clearing this up. The DTR was indeed broken out on the side.

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


text:
Reading a 10-byte buffer out of a PROGMEM string stored in a string table
I'm storing a large snippet of text in three separate PROGMEM char arrays:
const char script1[] PROGMEM = "....";
const char script2[] PROGMEM = "....";
const char script3[] PROGMEM = "....";

The first two are 32766 characters, and the last one is 23867 characters (the whole string is 89400 characters in total). I store these in PROGMEM on an Arduino Mega 2560 (which then uses about 90K of 256K of available program memory).
I stored these three strings in a table, together with their lengths:
const int TABLE_SIZE = 3;
const char * const scriptTable[] PROGMEM =
{
  script1,
  script2,
  script3
};

const int scriptLengths[] {32767, 32767, 23867};

I have some issues trying to chunk up the string into 10-byte buffers, and processng it that way. I want to iterate through the table, process the first part in 10-byte chunks first, then move on to the second part, and finally the last part.
For a single string (code), the following works fine:
const char code[] PROGMEM = "....";

// Chunk up large code string in PROGMEM.
const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
char workingSpace[CHUNKSIZE + 1];
int baseIndex = 0;

while (baseIndex < sizeof(code)) {
    int chunk;
    if (baseIndex + CHUNKSIZE > sizeof(code)) {
        chunk = sizeof(code) - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        memcpy_PF(workingSpace, ((uint_farptr_t)code) + baseIndex, chunk);
        workingSpace[chunk] = '\0';

        // for debugging
        Serial.print("#");
        Serial.print(baseIndex);
        Serial.print("– Got a chunk [");
        Serial.print(workingSpace);
        Serial.println("]");

        baseIndex += CHUNKSIZE;

However, I'm having some difficulties doing the memcpy_PF call using the table.
int tableIndex = 0;
// for each of the three script strings
for (tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++) {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    int baseIndex = 0;

    // we can only use sizeof if it's a static var.
    // strlen should only be calculated once, expensive operation (loop until we encounter '\0').
    // now stored statically in scriptLengths table.
    Serial.println("tableIndex: ");
    Serial.println(tableIndex);
    int strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
        int chunk;
        if (baseIndex + CHUNKSIZE > strLength) {
          chunk = strLength - baseIndex;
        }
        else {
          chunk = CHUNKSIZE;
        }
        // do memcpy_PF call here

I have tried several options here, mostly having difficulties with the second parameter (how to address the string stored in the table, and increase its indexing parameter). I read that the way to get a string out of a string table is to use pgm_read_word. However, with both of these below, I either get gibberish in the buffer string, or it seems to start in an incorrect location in the string.
memcpy_PF(workingSpace, ((uint_farptr_t) &scriptTable[tableIndex][baseIndex]), chunk);
memcpy_PF(workingSpace, ((uint_farptr_t) (char*)pgm_read_word(&(scriptTable[tableIndex])) + baseIndex), chunk);

Any help would be greatly appreciated!
Thanks!

The first thing you need to fix is this:
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino: In function 'foo()':
/home/nick/Arduino/Large_Progmem_test/Large_Progmem_test.ino:42:27: warning: iteration 3276 invokes undefined behavior [-Waggressive-loop-optimizations]
     baseIndex += CHUNKSIZE;

You are adding 10 to 32760 hoping to be >= sizeof(code) however now baseIndex will become negative as an int goes from -32768 to +32767.

There were some interesting subtleties to getting this working. :)
One of your major problems is this:
const char * const scriptTable[] PROGMEM =

That will give you 2-byte pointers (const char *) which will not be large enough to index into 89400 characters.
So you need to have an array of 4-byte pointers like this:
uint_farptr_t  scriptTable [TABLE_SIZE] =

However you can't just initialize those like you tried to. That has to be done procedurally with a macro that pulls in the full address. My working code is below:
#include "code.cpp"

const int TABLE_SIZE = 3;
uint_farptr_t  scriptTable [TABLE_SIZE];  // values calculated at runtime
const int scriptLengths[TABLE_SIZE]
  {
  sizeof (script1),
  sizeof (script2),
  sizeof (script3)
  };

void foo ()
{
  // for each of the three script strings
  for (byte tableIndex = 0; tableIndex < TABLE_SIZE; tableIndex++)
    {
    // Chunk up large script strings in PROGMEM.
    const int CHUNKSIZE = 10; // CHUNKSIZE *must* be an even number!!
    char workingSpace[CHUNKSIZE + 1];
    long baseIndex = 0;

    Serial.println ("----------------");
    Serial.print("tableIndex: ");
    Serial.println(tableIndex);
    long strLength = scriptLengths[tableIndex];
    Serial.print("length script string: ");
    Serial.println(strLength);

    while (baseIndex < strLength) {
      int chunk;
      if (baseIndex + CHUNKSIZE > strLength) {
        chunk = strLength - baseIndex;
      }
      else {
        chunk = CHUNKSIZE;
      }
      memcpy_PF(workingSpace, scriptTable [tableIndex] + baseIndex, chunk);
      workingSpace[chunk] = '\0';

      // for debugging
      Serial.print("#");
      Serial.print(baseIndex);
      Serial.print("- Got a chunk [");
      Serial.print(workingSpace);
      Serial.println("]");
      delay (50);
      baseIndex += CHUNKSIZE;
    } // end of while
  } // end of for
} // end of foo

void setup()
{
  // get proper pointers to the various pieces of progmem
  scriptTable [0] = pgm_get_far_address (script1);
  scriptTable [1] = pgm_get_far_address (script2);
  scriptTable [2] = pgm_get_far_address (script3);

  Serial.begin (115200);
  foo ();
}

void loop()
{
}

The file "code.cpp" just has the actual data in it (generated at http://www.lipsum.com).
As in:
#include <Arduino.h>

const char script1[] PROGMEM =  {

"Lorem ipsum dolor sit amet, consectetur adipiscing elit.  ... " };

const char script2[] PROGMEM =  {

"Aliquam erat volutpat. Praesent aliquet accumsan arcu,  ... " };

const char script3[] PROGMEM =  {

"Ut neque dolor, condimentum ut odio iaculis,  ... " };

Output:
----------------
tableIndex: 0
length script string: 32767
#0- Got a chunk [Lorem ipsu]
#10- Got a chunk [m dolor si]
#20- Got a chunk [t amet, co]
#30- Got a chunk [nsectetur ]
#40- Got a chunk [adipiscing]
#50- Got a chunk [ elit. Pro]
#60- Got a chunk [in sit ame]
#70- Got a chunk [t purus cu]
#80- Got a chunk [rsus, dict]
#90- Got a chunk [um magna q]
#100- Got a chunk [uis, place]
#110- Got a chunk [rat dui. I]
#120- Got a chunk [nteger ali]

...

#32700- Got a chunk [, eget tem]
#32710- Got a chunk [por dui te]
#32720- Got a chunk [mpor a. Do]
#32730- Got a chunk [nec malesu]
#32740- Got a chunk [ada mi et ]
#32750- Got a chunk [dolor cras]
#32760- Got a chunk [ amet.]
----------------
tableIndex: 1
length script string: 32767
#0- Got a chunk [Aliquam er]
#10- Got a chunk [at volutpa]
#20- Got a chunk [t. Praesen]
#30- Got a chunk [t aliquet ]

It successfully transitioned from the first array to the second one.

Good point, I missed that, thanks! Probably best to limit the size of script1,script2,script3, etc. to avoid overflows (e.g., to 30.000)?

Or use a long as an index.

Right, thanks! Any thoughts on the memcpy?

Maybe the avr-gcc compiler can not handle a PROGMEM section beyond 64kbytes. With a test sketch I am able to declare a lot of data (150kbytes), but the pointers in the Table[] stay 16-bit. They should be forced to 32-bit, but I don't know how. Even then, the memcpy_PF might not read beyond the first 64kbytes of the PROGMEM segment. So far I can't even read script3 directly with a function (when it is at the end of 150kbytes data).

See my amended answer.

I have tried a few things, and it it possible to create a 32-bit list of pointers with "const uint_farptr_t Table[] PROGMEM = ", but filling them during initialiazation will not fill them with the proper 32-bit addresses. I can't find another way to make it work than the workaround by Nick Gammon. The memcpy_PF() can retrieve data from PROGMEM that is beyond the 64kbytes border. It is the table that causes the problem. Also sizeof() and declaring too much data in a single array will cause trouble beyond the 64kbytes border, sometimes there is not even a compiler warning.

Thanks Nick and Jot! Nick's version is the solution we used eventually, and it seems to work. Particularly pgm_get_far_address seemed to be the missing puzzle piece. When reading data byte by byte from the strings in the table, it's also important to use pgm_read_byte_far() (vs. pgm_read_byte()).
As you mentioned Jot, there is an open Arduino bug where built-in macros stop working once you go beyond 64K: see http://forum.arduino.cc/index.php?topic=455577.0 & https://github.com/arduino/Arduino/issues/2226 We have reduced our strings to 40K in total to avoid that.


text:
Arduino Uno (or Teensy 3.2) programmatically powering an external USB connection
I'd like to create a process to programmatically turn-on/activate a separate USB device connected to my computer...Thinking another way to state the problem, I want the Arduino to complete the USB power circuit and then "turn off" on a schedule.
In an essence, I'd like to have my Arduino facilitate the manual process of un-plugging a USB into my computer (lets say for 5 seconds) and then re-plugging it in (let's say for 5 mins)-- rinse and repeat on a schedule....I'd like to have this coded/programmed though (I'm ok in the Arduino IDE -- sample code would really help me out a ton though) -- I'm not going to setup an actual servo to do this.
I thought getting a Arduino Shield would be the right place to start but I'm really lost.  I also thought getting a USB cable with a flip power switch might be another way to tackle the problem too-- but I haven't started to mess with it yet.
Any ideas or resources to point me in the right direction are greatly appreciated.  Thanks so much.

I'm not aware of any off the shelf "shields" which would accomplish this goal.  Since you do not seem to want your Arduino device to play either the USB host or client role, but rather to interrupt power to a difference device, a traditional USB shield is probably not going to help.
Rather it would be useful to look at how the small minority of USB hubs that implement software control of downstream power on a port-by-port basis do it - USB allows for this, but doesn't require it, and most hub ICs have output pins to drive power switches, but don't include them.
Switching the 5v USB VBUS needs to be a done with a "high side switch" - a P-channel MOSFET would be an obvious candidate, but it has been historically harder to find good ones.  Some time ago I ordered a few Richtek RT9701GB USB power switch ICs - apparently they are actually more effective N-channel FET's packaged with surrounding circuitry to make them usable on the high side - but that project was shelved so they remain untried.  If you are up for creating an extremely simple surface mount board to hold them (or can find one already made) they might be worth a try.
At the crude end you could probably use a relay board. There are hubs sold with mechanical power buttons that can be very useful when debugging USB-based embedded systems as you can power cycle them without constant unplugging, and this would be a sort of automated version of that.
It's an interesting question however, if removing the power to a USB peripheral while the data lines remain connected is proper.  This is problematic in the simplest design of an ESD protected input, as the built in protection diode means that the data signal ends up trying to power the unpowered IC, something it isn't usually rated to do, but actually USB circuitry may be more complicated.  An original USB "A" connector is made with the power and ground pins longer than the data ones, in the intent that they connect first.   Pragmatically, I've seen numerous USB devices survive data connection without power - but it could be interesting to read the specs (both USB and of the data sheets of particular devices implementing it) and see what they say about this.
Another tactic could be to get one of the hubs with buttons, take it apart, and wire a relay across one of the buttons.
Or, if you did get one of the rare USB hubs that actually includes controllable downstream power switches, an investigatory dive into the depths of your computer's USB stack should theoretically yield a way to control them from software there, potentially eliminating the need for the Arduino/Teensy.


text:
RFID Code (and setup) works on an UNO but not on the Yun
We're using two RDM6300 RFID readers for this, and the code works when plugged into an UNO, but not when connected to the Yun. We have one of the rfids plugged into the rx pin (0 on the digital side) and the other plugged into pin 2 (same exact way we had it working on the UNO). Anyway, is there something majorly different between working with just sketches on Yun vs UNO? This code doesn't even involve using the Linux side yet as we couldn't get this major part figured out. Any help would be appreciated
#include <SoftwareSerial.h>

    //2nd RFID using SoftwareSerial
    SoftwareSerial RFID(2, 3); // RX and TX

    // define constants for pins
    int UNLOCK = 8;

    // variables to keep state
    int readVal = 0; // individual character read from serial
    unsigned int readData[10]; // data read from serial
    int counter = -1; // counter to keep position in the buffer
    char tagId[11]; // final tag ID converted to a string

    char* authorizedTags[4]; // array to hold the list of authorized tags

    // fills the list of authorzied tags
    void initAuthorizedTags() {
      //tags
      authorizedTags[0] = "02006750B7";
      authorizedTags[1] = "02006750B1";
      authorizedTags[2] = "02006750B2";
      authorizedTags[3] = "02006750B3";
      authorizedTags[4] = "02006750B4";
    }

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

      //start serial to RFID reader2
      RFID.begin(9600);

      pinMode(UNLOCK, OUTPUT);
    //  pinMode(SUCCESS, OUTPUT);
    //  pinMode(ERROR, OUTPUT);
      initAuthorizedTags();
    }

    // check if the tag ID we just read is any of the authorized tags
    int checkTag() {
      int i;

      for (i = 0; i < 4; ++i) {
        if (strcmp(authorizedTags[i], tagId) == 0) {
          return 1;
        }
      }
      return 0;
    }

    // convert the int values read from serial to ASCII chars
    void parseTag() {
      int i;
      for (i = 0; i < 10; ++i) {
        tagId[i] = readData[i];
      }
      tagId[10] = 0;
    }

    // once a whole tag is read, process it
    void processTag() {
      // convert id to a string
      parseTag();

      // print it
      printTag();

      // check if the tag is authorized
      if (checkTag() == 1) {
        tagSuccess(); // unlock solenoid
      } else {
        tagFailed();
      }
    }

    void printTag() {
      Serial.print("Tag value: ");
      Serial.println(tagId);
    }

    // perform an action when an authorized tag was read
    void tagSuccess() {
      Serial.println("Tag authorized.");

      //activate solenoid,
      digitalWrite(8, HIGH);
      delay(3000);
      digitalWrite(8, LOW);
    }

    // inform the user that the tag is not authorized
    void tagFailed() {
      Serial.println("Unauthorized access!");

    }

    // this function clears the rest of data on the serial, to prevent multiple scans
    void clearSerial() {
      while (Serial.read() >= 0) {
        ; // do nothing
      }
    }

    void loop() {

    //RFID 1
      if (Serial.available() > 0) {

        // read the incoming byte:
        readVal = Serial.read();

        // a "2" signals the beginning of a tag
        if (readVal == 2) {
          counter = 0; // start reading
        }
        // a "3" signals the end of a tag
        else if (readVal == 3) {
          // process the tag we just read
          processTag();

          // clear serial to prevent multiple reads
          clearSerial();

          // reset reading state
          counter = -1;
        }
        // if we are in the middle of reading a tag
        else if (counter >= 0) {
          // save valuee
          readData[counter] = readVal;

          // increment counter
          ++counter;
        }
      }

    if (RFID.available() > 0)
    {
        // read the incoming byte:
        readVal = RFID.read();

        // a "2" signals the beginning of a tag
        if (readVal == 2) {
          counter = 0; // start reading
        }
        // a "3" signals the end of a tag
        else if (readVal == 3) {
          // process the tag we just read
          processTag();

          // clear serial to prevent multiple reads
          clearSerial();

          // reset reading state
          counter = -1;
        }
        // if we are in the middle of reading a tag
        else if (counter >= 0) {
          // save valuee
          readData[counter] = readVal;

          // increment counter
          ++counter;
        }
    }

    }

Does it work for one reader?

Nope. Please don't tell me it's incompatible with the Yun...

I doubt that. Its a basic serial device. Have you communicated with anything over serial with the Yun?

Are you using the Yun over WiFi?

it does have wifi access currently, but it's not in use. When we present the project it will be connected via ethernet. And I have not, this was the only thing I've tried using serial with it.

If you're using it over USB then, try communicating with your PC with a simple sketch to print something to Serial

yep, Serial.prinltn("whatever"); works

From what I found, Serial is reserved for comms between the atmega32u4 and the PC, while Serial1 (on pins 0 and 1) is reserved for comms btw the Arduino and Linux parts of the Yun. You have to use 2 SoftwareSerial ports for your project; and it seems even that option is buggy on the Yun. But try with one reader anyways; disconnect the other from pins 0 and 1 and try printing whatever you read from the SoftSerial reader to the PC; keep the sketch simple

Okay so, I was already using the SoftwareSerial for the second (and tested it when testing one or the other) and it didn't work on pin 2,3. So I searched that issue and apparently you can't use pins below 8 for rx/tx so I moved it to 8,9 and now works. http://forum.arduino.cc/index.php?topic=228470.0  But now the issue will be to use two software serials as I hear that's annoying too, but that's also a different question I guess

You'll just have to call listen() whenever you want to read from a particular reader. You're already reading them in order in your code, so it shouldnt be too much trouble, to call listen() and then prompt a user to present a card for reading


text:
UNO Power supply to USB
If UNO is supplied with 9VDC to Power Jack.
Will it supply power to USB connector?

No

As you can see in the schematic, the USBVCC is only connected (via a MOSFET) to the 5V line, when the voltage on VIN (barrel jack) is LOW.
If you connect 9V to the power jack, the mosfet will turn of, and disconnect the USB power from the 5V on the UNO.


text:
What is the output of Software Serial .read() function
Hi I am new to arduino development i was using esp8266 using software serial library

here is the code

#include<stdlib.h>
#include <SoftwareSerial.h>

SoftwareSerial monitor(2, 3); // RX, TX

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

  sendDebug("AT");
  delay(5000);
  Serial.println("Hello");
  if(monitor.find("OK"))
  {
   Serial.println(monitor.available());
   Serial.println((int)monitor.read());
   Serial.println((int)monitor.read());
    Serial.println(monitor.available());
   Serial.println("RECEIVED: OK");
    //connectWiFi();
  }
  else
  {
    Serial.println("RECEIVED: None");
  }
}

void loop(){

}

void sendDebug(String cmd){
  monitor.println(cmd);
  Serial.println("Command: "+cmd);
}

Output

Command: AT
Hello
2
13
10
0
RECEIVED: OK

All I know is monitor.available() return the available bytes that can be read and i can also deduce that these two bytes are O and K but the integer value doesn't corresponds to the ascii value of O and K
can anyone explain what is actually getting printed on the serial monitor what is 13 and 10 ? ??

It is just like https://www.arduino.cc/en/Serial/Read :
The monitor.find("OK"); already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive monitor.read()s, then zero more bytes in monitor.available().


text:
is there any real arduino emulators (so I can upload and run machine code on it)
I play with Arduino Micro. I write my programs in directly in machine code, in binary editors (yes, I know that there are more easy ways to program an Arduino, I do it for fun and learning). Often my programs work, but if not, then I would like to run them on an emulator to understand what's exactly going on under the hood. Is there any Arduino emulator that accepts hex files with compiled program and can execute it? I already looked at tools mentioned at Can I program for Arduino without having a real board? , but as far as I see, they are simulators rather than emulators and I can't use compiled binary programs in them.

Are you sure you are not writing Opcode?  As machine code is literally typing in numbers.  For example, there are no "labels" let alone "goto labels".  When writing in machine code, generally all branches need to be calculated to either a relative or absolute memory address.

Yes, I am sure that I am not writing opcodes, I am writing in machine code - this is why I mentioned that I use binary editor (I tried to be clear about it).

Ok, understood.  Going on, I answered your question generically.  But I see you were asking about the ATmega32U4.  If I were Microchip, I wouldn't publish how my processor worked.  That's intellectual property.  So it would be surprising to find a working software emulator available for this specific processor.  As I send in the answer, most developers simply work with the actual processor using its JTAG interface.

Hint: Search github, here is an example of a simulator that you could continue working on: https://github.com/buserror/simavr

Disclaimer: I have no affiliation with Wokwi (based on opensource AVR8js engine) except that I have learnt a lot from it.
I just tried it on the free Wokwi Arduino simulator(my favourite Arduino simulator for learning) and it worked in a blink!
Here is what I did to load the hex file into the Arduino simulator

Go to the Arduino IDE and open the basic blink example
Change the ON time delay to 100ms (to make sure, the hex file is really loaded into the Arduino simulator and to verify it's working.
Once the modified example is compiled go to the %temp% folder
Search for *.hex files and find the one which is just the latest one (this is the only way I found to grab the hex file needed)
Go to Wokwi Arduino Simulator with any Arduino example
Click on the editor tab in the left
Press function key F1
Select the option Load HEX file and START simulation
Done - the simulation should run like expected.

I have created a short GIF and I hope you like it (lazy to show step by step)

What is your affiliation with Wokwi?

Hello @starCat I have been following this Simulator for my Arduino learning but not involved in developing. I have got a lot of help as training and tutorials form Wokwi while I learn and develop other projects.

I have seen this Simulator growing from simple blink to complex projects and is closely knowing all the updates happening. Let me know if I should do something

There are many different processors used in making many different types of Arduino boards.  So there is no one way to write Arduino machine code.
There are emulator for simpler processors available for the asking.  But, while they work, it is not believe they claim to be totally accurate.
At one point in processor development history, ICE machines were widely used.  This is where a real processor is modified to allow access to internal controls and registers.  (This actually sounds like the answer to your question.)  However, as processors grew in speed and complexity, this approach grew out of favor.
Currently, most processors are built with extra internal circuitry and interface to break program execution for debugging purposes.  JTAG is one such industry standard / example.
So, while the question has merit, the common practice is likely not to run code on an emulator, but to run it on the processor using the JTAG interface and an IDE running on a host-computer / work-station.

The in-circuit-emulators were very expensive and never 100% accurate (for example different timing for external signals), while the JTAG is already in the microcontroller for free.

Good points @Jot.  And I can attest to the timing difficulties.


text:
Connecting a sensor to the 5V pin shorts Arduino Nano
I bought an ultrasonic distance sensor seen here: http://arduinobasics.blogspot.co.uk/2012/11/arduinobasics-hc-sr04-ultrasonic-sensor.html?m=1. As per the wiring diagram I connect it to the ground and 5V pins on my Arduino Nano which is powered via USB.
As soon as I connect the 5V to the sensor it shorts and the lights on the Arduino go out and my laptop says 'usb surge too much power being drawn'. Do I need to add a resistor to the circuit? It all works fine and I get a result when the sensor is connected to the 3V3 pin but it does not ping properly.
I have tried using an external power supply via a breakout board as well as usb mains plug but both still short. Any help would be much appreciated!

Perhaps the sensor has an internal short, or you're accidentally shorting wires? I just plugged my unit in exactly the way the referenced link shows, and using their code also on that side, I have no issues (with USB power or external PSU).

I tried both sensors and neither one works. I think i must be shorting wires somehow.

Can you show a pic of how you're doing things?


text:
Arduino Nano not visible in Serial Ports (Mac OS)
I have used by Arduino countless times over the past few years and only after installing an update to Mac OS Sierra did the device stop showing up under the Serial Ports. Now only tty-bluetooth shows up no others. I have looked a countless threads where people suggest installing drivers or uninstalling drivers or rebooting. I have tried everything but still no device shows up.
I switched to my Windows partition using Bootcamp and lo and behold it works perfectly there but not in Mac OS. I would still like to use Mac OS to programme my Arduino. If anyone has any suggestions I would be very grateful!

You've already done exactly the right thing to isolate the problem - trying a different operating system on the same hardware, and the result is that this is a Mac question, not an Arduino one. (My standard advice when people have Mac problems is to remind them that "it just works", but strangely this doesn't often help.)

@MarkSmith Hahaha yes it is unfortunate that in this situation 'it just works' until it doesn't.

Thank you @Adrian Mihalko for the detailed solution. I am running on Sierra latest release, i tried all the options you mentioned in the order. But, the serial port doesn't still show up on my Arduino IDE when I connect my Wemos D1 mini chip (which uses CH340G chipset). Please help!

Im trying to make that machine works and my Macbook pro 2016 with osx high sierra
does see the usb serial but not UGP https://www.amazon.com/MYSWEETY-Control-Engraving-16x10x4-5cm-110V-240V/dp/B01NBVXO0V/ref=sr_1_4?ie=UTF8&qid=1512003731&sr=8-4&keywords=cnc

Is it an original Nano or a clone?
The original Nano uses FTDI's FT232 ship, whereas clones use the CG340 USB-to-TTL chip. The former works fine straight away Mac OS Sierra, whereas the latter needs a driver.
The CG340 driver doesn't work under Mac OS Sierra. Fortunately, someone patched the driver and made it available at GitHub. There you'll also find some troubleshooting instructions that can help (hopefully).
From Adrian Mihalko's repository at GitHub:

ch340g-ch34g-ch34x-mac-os-x-driver
Latest macOS Sierra-compatible driver for devices using the CH340G, CH34G or CH34X chipset. This chipset is used in several Arduino-clones.
Introduction
Version 1.3 (2016-09-27) of the OEM driver for the CH34x chipset currently causes a kernel panic (a.k.a. crash) when installed on macOS Sierra. To resolve this issue, please download and install the driver in this repo.
Installation

Remove the old driver by issuing one of the following commands (depending on your installation):

sudo rm -rf /System/Library/Extensions/usb.kext
sudo rm -rf /Library/Extensions/usbserial.kext

Restart your Mac.
Double-click on the CH34x_Install_V1.3.pkg file.
Restart your Mac.
Plug in your device. It should now be listed under the /dev directory. Examples:

/dev/cu.wchusbserial1410
/dev/cu.wchusbserial1420

Troubleshooting
If, and only if, the device is not recognized after the installation (or you cannot install the driver), please disable System Integrity Protection:

Reboot your Mac into Recovery Mode by restarting your computer and holding down Command+R until the Apple logo appears on screen.
Open the Terminal (Applications > Utilities > Terminal).
In the Terminal window, type in csrutil enable --without kext (or to fully disable: csrutil disable) and press Enter.
Restart your Mac.

Please share this page!
Regards,
Adrian Mihalko

Thank you for your help. It is an original Arduino Nano not a clone as far as I know.

Where did you bought it? Was it packaged inside a box, as original Arduino products are? Did you have to install any driver when you used it for the first time?

I'm also using Mas OS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever. Some people have reported problems using the manufacturer drivers after upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and  relying on the default Apple FTDI drivers instead. It's worth a try.

This works for me. I had Clone Nano. Thanks brah.


text:
CRC usage when ack disabled in nRF24L01
In the documentation of the nRF24L01 library I use (library), the CRC state (on/off) and length can be set or get. It seems to be used for auto ack, but when I switch auto ack off, what is the use of CRC? Can I somehow read the CRC value or use it somehow in a useful way?
The reason is, I get sometimes wrong values and would like the CRC for that, but otherwise I need to implement my own CRC byte(s) in the payload.
(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages).

The chip itself deals with CRC calculation and discards any that fail the check, you don't get to see the CRC. You get faulty packets when connection between Arduino and the nRF is finicky or when power to the module isn't the most table, use better wires (definitely not a ribbon cable) and decoupling capacitors. See the datasheet for more details about special cases of using CRC (Enchanced Shockburst and so on).

@Avamandar ... I use an adapter which afaik already contains the capacitors (also there wouldn't be a possibility to add these manual close to VCC/GND anyway). I use 5V (and the adapter converts it into 3.3V).
I would have to check the special cases regarding enhanced shockburst (I don't want to use the ack-mechanism).

You don't have to use auto-ack to keep CRC enabled, if my memory serves me correctly.

@Avamandar True, it seems different options, but since there is no way to use CRC directly, the only possibility it's used internally in the chip. However, I assume it does not start resending by itself in case of an incorrect CRC and I cannot know the CRC value, so a CRC without an ack does not seem very useful.

@Avamandar ... the default way afaik is to use dupont cables, I assume you don't consider those ribbon cables?

Dupont cables should work fine. Resending, auto-ack and CRC are all separate features that work almost individually. The library has functions for changing that too.

I use dupont and seems to work fine so far indeed, I never used flat cable. I guess I need to do some testing to see how much the CRC influences correct transfers.

(also, when I put my finger against the PCB side on the side where the PCB antenna is placed, but not touching the antenna, I get many more messages). - You may have your gain set too high or your modules too close together and the signal is distorting through too much power (saturating the receiver). Your finger is attenuating the signal. Or the other way around and there's not enough signal and your finger is acting as a crude ground plane for the dipole.

@Majenko that might be the case (too close together, like 5-15 cm and MAX PA level). I will try to decrease it.... however, what if I don't know the distance while in use? In a real situation some slaves might be close, others might be further away... I cannot select it per slave device/port.

If they are just slaves to a single master then it's the distance from the slaves to the master that you need to worry about, not the distance between slaves. Anything further than about 1m you don't really need to worry I think. Experiment. See what PA level gives the best results over the distance range you are expecting. Maybe give a "LOW" and "HIGH" power switch on the unit.

@Majenko ... yes that is what I meant (I mean some slaves will be close to the master, some might be close to the master). So I guess it's best to have at least some distance between all slaves to the master ... or maybe in case two are close together, I might go for a wired solution for one of them.


text:
Problems with installing MIDI library in UECIDE
I installed UECIDE from Majenko but I couldn't register nor email him so I try it here.
When trying in install the MIDI library from 47 effects (https://github.com/FortySevenEffects/arduino_midi_library/releases/tag/4.3.1) I get the following error:
Compiling Failed
Analyzing Arduino_MIDI_Library_v4.3.1.zip ...
Unable to detect any valid libraries in the archive.
You may need to manually install it or re-package it properly.

How to solve this?
I tried install manually by copying files but that didn't result in anything.

The auto-install method only (currently) works with old single-arch style libraries. This one is a new multi-arch style library (though it doesn't use the multi-arch facilities).
You need to install it manually.  Simply that means extracting the zip file into "libraries" within your "UECIDE" folder in your documents (My Documents/UECIDE/libraries on Windows, or ~/Documents/UECIDE/libraries on Linux / OS X).
If UECIDE is open at the time you can use "Help -> Debug -> Rebuild internal structures" to re-scan the available libraries, or just close it and re-open it.

Thanks ... still some errors to be fixed but that's internal in my code. The MIDI library is installed in a breeze.


text:
Unable to set up Intel Edison on Windows
I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.
My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.
I am using an Edison with an Arduino breakout board.
Here is the sequence of steps I followed:

I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
I went to Windows Device Manager and found the connected device on COM6
I installed Putty and connected to COM6 with a baud of 115200.
The console showed a blank screen with a green cursor in the top left.
I waited 30 seconds for it to boot.
I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

I have no idea what to do next.

I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)
I am using Windows 8.1, 64 bit edition.

Download the Edison firmware from https://software.intel.com/en-us/iot/hardware/edison/downloads. For me it was http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip.
Extract the zip file.
Start the Windows Command Prompt as Administrator.
The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.
Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.
Follow the steps in my question until the output on the console (also from my question) appears.
Run "flashall --recovery"
Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.
Wait about 5 minutes for the rest of the process to run automatically.

At this point everything should work again.
You should see this on the command line in Windows:

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download        [=========================] 100%      4194304 bytes
Download done.
Download        [=========================] 100%      4194304 bytes
Download done.
Flashing U-Boot
Download        [=========================] 100%       237568 bytes
Download done.
Flashing U-Boot Environment
Download        [=========================] 100%        65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download        [=========================] 100%        65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download        [=========================] 100%      6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download        [=========================] 100%    566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.

C:\Users\_\Desktop\edison-image-ww25.5-15>


text:
Delayed response from web server
I am trying to implement a web server in ESP8266 that will handle simple HTTP GET requests by initiating an operation (e.g. move a stepper motor to the requested position) and return a response when the operation is finished (i.e. when the motor has reached the target position). This may take a few seconds, but during that time  the main loop should run normally so that both the TCP stack can work and the stepper library can actually move the motor (it works in the background). This means I cannot wait for the operation to complete within the handler. I have to start the operation in the handler, return without sending back a response and when the operation is done (i can poll for that in the main loop) then send the response.
I have been looking at https://github.com/me-no-dev/ESPAsyncWebServer but I'm not sure if such a scenario is supported. Has anynone done anything similar? Is it even possible?
One solution I was thinking was to store the request in a global variable (or queue) before exiting the handler and use it when the operation finishes. But will the request survive outside of the handler? And is it even possible to send the response outside the handler?

Without knowing too much about this, it sounds like a bad idea to delay the actual response to the GET request. A client with a too short timeout might think, that the connection was lost. It may be feasible for you to just poll the ESP from the client for the status of the operation, to get the information if it was finished

Granted, this is not a good design, but since this is what the client expects and I have no control of the client, I am looking at how to implement the requirement

if you are using a webpage to interact with the server, then put a timer into the webpage for auto refresh ... i think that using ajax may also do the job (I'm not sure though)

I'm thinking of going a completely different direction. Dump the client and make my own. Then I have full control and I can do any polling or even use websockets to send events from ESP


text:
Peer to peer communication
Hello guys ,
             I want to perform a mesh network between 3-4 modules using ESP8266 . Any one have idea how to do it?

@Stewart Mayer, your code above (AP & ST) is work! Thanks in advance! Greeting from Indonesia

Stewart, I'm an ESP8266 newbie and have been working on this all day. I stumbled across this client/serve code and it worked first time! Thanks for writing and posting. Peter

Peer to Peer Example
Written by Stewart Meyer (engineer retired from the FAA).
This is first time that I have given an answer, hope you can read this:
Not only can the ESP8266 connect to a WiFi network and interact with the Internet, but it can also set up a network of its own, allowing other devices to connect directly to it. This example demonstrates how to turn the ESP8266 into an access point (AP) also called a server, and serve up data to any connected client also called a station.
Server (Access Point)
First we will look at the server:
/* Server
*  We write the server first because we need its IP address
*/

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char* ssid = "Meyer";       // ssid of server (Access Point (AP))
const char* password = "";        // password of server (Access Point (AP))
WiFiServer server(80);            //Service Port

int ledPin = 2; // GPIO2 of Server ESP8266

void setup()
{
    delay(1000);
    Serial.begin(115200);    // to use tools->serial monitor

    pinMode(ledPin, OUTPUT);   // set GPIO 2 as an output

    WiFi.mode(WIFI_AP_STA);  // Set WiFi to AP and station mode

    // Connect to the WiFi network
    Serial.println();
    Serial.print("Connecting to: "); Serial.println(ssid);
    WiFi.softAP(ssid, password);

    // Display the server address
    Serial.print("Connected, My address: ");
    Serial.print("http://");
    Serial.print(WiFi.softAPIP());
    Serial.println("/");

    // Tell the server to begin listening for incoming connections
    server.begin();
    Serial.println("Server listening for incoming connections");
}

void loop()
{
    // Check if a client has connected
    WiFiClient client = server.available();
    if (!client) // if not available, return
    {
        return;
    }

    // Wait until the client sends some data
    Serial.println();
    Serial.println("Client connected");
    while(!client.available())
    {
        delay(1);
    }

    // Read the request
    String request = client.readStringUntil('\r');
    Serial.print("Request = "); Serial.println(request);

    if (request.indexOf("/ON/") != -1)
    {
        digitalWrite(ledPin, LOW); // turn LED on
    }
    if (request.indexOf("/OFF/") != -1)
    {
        digitalWrite(ledPin, HIGH); // turn LED off
    }

    client.flush();
    Serial.println("Client disconnected");
}

Client (Station)
Next we will look at the client:
/*  Client
*   This client will turn the LED on or off every 5 seconds
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>

const char* ssid = "Meyer";   // ssid of access point (Server)
const char* password = "";    // password of access point (Server)
int port = 80;                // port number

byte ip[]= {192,168,4,1};

int LEDstatus = 0;

WiFiClient client;  // Declare client

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

    WiFi.mode(WIFI_STA);  // set mode to station (client)

    // Connect to wiFi
    Serial.println(); Serial.println();
    Serial.println("CONNECTING TO WiFi");
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");  // print dots until connection
    }
    Serial.println();
    Serial.println("WiFi CONNECTED");
}

void loop()
{
    // Connect client to server
    Serial.println("CONNECTING CLIENT TO SERVER");

    if (client.connect(ip, port))
    {
        Serial.println("CONNECTED");
    }
    else
    {
        Serial.println("CONNECTION FAILED");
    }

    // Send message to control the LED
    if (LEDstatus == 0)
    {
        client.println("/OFF/");
        Serial.println("LED OFF");
        LEDstatus = 1;
    }
    else
    {
        client.println("/ON/");
        Serial.println("LED ON");
        LEDstatus = 0;
    }

    client.println();

    client.flush();

    delay(1);
    Serial.println("CLIENT DISCONNECTED");
    Serial.println();
    delay(5000); // delay 5 seconds
}

You can't, that's not how the esp8266 works.
The esp8266 is WiFi, so you will either need an access point or nominate one esp8266 module to act as an access point running in softap mode.

you can provide  the sample

sorry @girishkolte but... I never used an esp8266, so I'm a newbie. But if Majenko says "you need to run the esp8266 in softap mode" I go on google (if you don't know it, it's a search engine) and search "esp8266 softap". The VERY FIRST result already has an example. And the second one too. And I didn't go through all the others, but I assume that a lot of them already have. So stop waiting for others to do your work and search on your own! It's also faster, because you will get results instantly instead of waiting for other people to search them for you


text:
Interface pressure Sensor
Hello folks,
              I am using G1/4 Pressure Transmitter Sensor 0-1.2 MPa sensor can you guide for programming part.The conversion from bar to pascal  or bar to Mpa or pascal to psi.Though I am new to it. Plz guide me .

I'm assuming you mean that you want to pull a voltage number off of an input pin and convert it to a meaningful number.
To do this find the range of the incoming voltage.
Find the range of the sensor.
After that you need to split the voltage up to show what parts of the range convert to how much psi.
Here is an example of a temperature gauge that has the same principle.
Temp sensor

I done by this way it is right to do this?
 int rawReading = analogRead(A0);   // Range : 0..1023
float millivolt=(rawReading*4.882);

float rawVoltage = (rawReading * (4.5 / 1023.0)) + 0.5;
byte psi = (rawReading-102)/8;
float bar = psi0.07;
float MPa = psi0.006894759086775369;

Looks good to me. Do you think those numbers are accurate after testing done readings?

I dont know i search on it and find this values.It shows the output but dont know it is right or wrong

Logically what you did sounds right. I don't have your sensor in front of me so I can't help you as far as that goes.

One thing that I would add to this is that if you need good accuracy you may want to apply a voltage equal to your full scale output to the AREF pin. The value on AREF does not have to be equal to the full range of the sensor – just to the maximum value you will get – if you will never see readings at the extremes of the sensor's range you can set your AREF below the maximum value and get higher resolution.
Tronixstuff has a good tutorial on the AREF pin that goes into considerable detail about how to configure the pin and use the analogReference() function.


text:
ATTiny85, how to fix overwritten clock pins?
I'm using an ATTiny85 with an external 16MHz clock. I accidentally set pins 3 and 4 to output using pinMode() in a program and uploaded it, and now I'm getting an invalid device signature (the signature is 0) error when I try to upload a sketch.
How can I go about fixing this (if possible)?
I am using an Arduino UNO as ISP, with an external 16MHz clock and capacitors connected to pins 3 and 4, and have rechecked my wire setup multiple times.

Holding the chip in reset while powering it on will ensure that the pins are never reconfigured.


text:
Arduino Delivering less power
I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to  Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then  directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.
I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.
I am using following code
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int p1 = 13;
int p2 = 12;
int p3 = 11;
int p4 = 10;

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    pinMode(p1, OUTPUT);
  pinMode(p2, OUTPUT);
  pinMode(p3, OUTPUT);
  pinMode(p4, OUTPUT);
  digitalWrite(p1, 0);
  analogWrite(p2, 0);
  analogWrite(p3, 0);
  analogWrite(p4, 0);

  Serial.begin(9600);
}
void loop(){
  Wire.beginTransmission(MPU);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  Serial.print("AcX = "); Serial.print(AcX);
  Serial.print(" | AcY = "); Serial.print(AcY);
  Serial.print(" | AcZ = "); Serial.print(AcZ);
  Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
  Serial.print(" | GyX = "); Serial.print(GyX);
  Serial.print(" | GyY = "); Serial.print(GyY);
  Serial.print(" | GyZ = "); Serial.println(GyZ);

   digitalWrite(p1, HIGH);
  analogWrite(p2, 250);
  analogWrite(p3, 255);
  analogWrite(p4, 255);

  delay(333);
}

Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max.  Eg, see table 29.1 in the Atmega328 specs.
Although some sources rate a high-speed 716 coreless dc motor at 40 mA, other sources rate it at 100 mA.  In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.
Edit: Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:

Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries.  Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length.  As a generic designation it has been used for several different motors, some of which produce less power.  For example, in thread #1710948 on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.
Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk.  The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side.  Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)
Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others).  On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group.  If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply.  (Again, I don't know if this will make any difference at all in how well things work.)  Refer to Table 30-1 footnotes for details.
As noted in Gerben's comment, having flyback-diodes for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.
Edit 2: Regarding “which diode, FET to use and where [to] learn about them”, electronics-tutorials.ws is an accurate and helpful presentation about FET digital circuits.  In particular, see the section called “An example of using the MOSFET as a switch”.
Which FETs to consider depends in part on your electronic-circuits fabrication skills.  Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter.  However, some people find SMD parts difficult to work with.  In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size.  (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.)  If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).
Some typical logic-level-input SMD FETs are shown in mouser.com's online catalog.  Note that in that list, RDS_on decreases a bunch as unit price increases slightly.  For example, the FDN359BN would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA.  Voltage drop running a 40 mA motor should be about 4 millivolts.
Some typical SMD Schottky diodes also are shown in mouser.com's online catalog.  I think even the cheapest of these would work ok.  Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.

But most projects i've seen don't use any drivers, Why so ?

Also; don't forget to add flyback-diodes to the motors.

I've added a few more paragraphs of explanation

Cool....Added to knowledge, I have used a paper body so that is only possible light weight and motors
RPM: 20000 +/- 2000
Voltage: 3.7V DC
Shaft: 4mm x 1mm
Continous Current: 40mA
Can you please point to some resource where i can find which diode,FET to use and where can i learn about them ? I am pretty new to electronics

@Anonymous, see edit

In my opinion, the main difficulty is holding parts in their proper places while soldering them - I would second that. However that is merely a mechanical problem, and can be solved in various ways. A couple of years ago I wouldn't have touched a SMD device, but now I am happily soldering SMD LEDs, resistors, etc.

@NickGammon,  I too like SMD parts and use them a lot, since they are small, cheap, versatile, and don't require thru-holes on home-made boards.  However,  “merely a mechanical problem” might not give the positioning problem enough respect.  Simple solutions exist (like using solder stencils and solder paste and an oven, or using a vacuum pickup, or using micropositioners) but without aids like that, holding SMD parts with the necessary accuracy (say .01" or less) for soldering can be hit-or-miss.

I was thinking of 2 or 3 pin parts. The ones with lots of legs are certainly a challenge. :)


text:
SoftwareSerial too slow for MIDI?
I tried to use the SoftwareSerial library for MIDI (by 47 effects), but it seems I get regularly corrupted/unexpected messages.
The circuit I'm using works perfectly when I connect it with the HardwareSerial solution (so the problem must lay in software).
What I see is:

When I press notes and release notes, LED 13 goes on and off correctly.
When I use Serial.print for debugging I get correct messages. However, in the example below I removed the print statements to have a minimal example).
When I use SoftwareSerial, LED 13 goes on and off for every note correctly. However, when I send many messages (for example by aftertouch/pitch bend which send a lot of messages in a short time), I noticed Note On/Off commands with 'random' values are sent.

Some sources say SoftwareSerial should work for MIDI, however, so far it is far from perfect. Do I make some mistake?
(btw, the baudrate of MIDI is 31.250 bps, when I use pitchband several hundreds of bytes per second are sent, so far within the MIDI spec).
The sketch I use is:
#include <MIDI.h>  // Add Midi Library
#include <SoftwareSerial.h>

SoftwareSerial swSerial(2, 11); // RX, TX

MIDI_CREATE_INSTANCE(SoftwareSerial, swSerial, midiSw1);

#define LED 13    // Arduino Board LED is on Pin 13

void setup()
{
  pinMode (LED, OUTPUT); // Set Arduino board pin 13 to output

  midiSw1.begin(MIDI_CHANNEL_OMNI);
  midiSw1.setHandleNoteOn(MyHandleNoteOn);
  midiSw1.setHandleNoteOff(MyHandleNoteOff);
}

void loop()
{
  midiSw1.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, HIGH); //Turn LED on
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, LOW); //Turn LED off
}

I've experienced the exact same problem. In my experience SoftwareSerial isn't fast enough to handle quick, successive MIDI messages. I found I got the best results by using the hardware serial for MIDI and using SoftwareSerial + another Arduino for debugging. Although this was the best setup, it still wasn't perfect. Even the hardware serial dropped/corrupted messages once in a while.

digitalWrite might be too slow. Try replacing it with PORTB |= 0x20; and PORTB &= ~0x20;. But there's nothing much you can do to speed up all the MIDI handling code.

@Mazaryk ... I already use a Mega which has 4 hardware serials, so far I use 3 for MIDI, one for debugging (for now, later can be the 4th MIDI). And when the 4th is used for MIDI I probably will use another Arduino as debugging. I did a lot of testing and so far I never got dropped/corrupted messages ... and CL proposed to use the even better H11L1 opto couplers instead of the 6N138 which I use now.

@CL: Thanks ... everything to speed up might be good ... however, since the hardware serial solution worked well with digitalWrite and the software serial not, I still think it is too unpredictable if I have to use such 'tricks'.... later I want to do also additional processing which might make the software solution unworkable (again).

The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.
As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.
Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the millis() timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives before the ISR is ready to service it there will be a delay - and any delay is bad.
Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).
SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.

Very helpful information (as always) ... I tried to make the buffer 128 bytes but I didn't see any improvement. Of course I can make it 256 of maybe 512, but probably it's just 'delaying' the time before getting into problems if I read your explanation.

If you're sending lots and lots all the time then yes, all you will be doing is delaying the time before you see problems. Also there is always the chance that if the next packet comes too fast the ISR won't be able to respond fast enough and you may lose the start of the next packet, triggering part way through on the next falling edge within it.

Maybe in the future (if my project will grow) I might have to go to another board (giving me 8 hardware serials). Currently I use a SD shield, planning to use a WIFI shield and possibly a USB (host) shield, also need a prototype board for additional components (several opto couplers etc). So maybe 2 Mega's would be good :-)

Maybe even three ;) You can never have too many. It can be good to split a project down into component blocks and have them separately controlled and managed. Maybe have one central master controller than tells all the others what to do.

Yes sounds perfectly clear to me :-) ... I don't know if you are familiar with MIDI, but note on/offs will not give a problem, but CC messages (like pitchbending/aftertouch result in a lot of bytes, well within the baudrate of MIDI which is 31250 bps, but probably too slow for SoftwareSerial).

That also sounds like a very cool idea ... but remember, this is the first Arduino project I do :-) ... on the other hand if the project will slowly grow it's very good to learn a lot about Arduino's/microcontrollers and electronics.

Yeah, I know MIDI quite well. As I mentioned in a comment above it's not just the quantity that can be a problem but the gap between successive packets. Even just two packets sent too close together can be problematic.

And the 'problem' is that I don't mind about losing a CC message, but a note off message being unhandled results in a note that sounds forever (unless changing the sounds on a synth) ... this is totally unacceptable in a live music situation.

Absolutely. It can be useful to program a "kill switch" which stops all sounds in an emergency. Just in case.

A kill switch is not something that is handy too (in my case) ... I want to let the MIDI box (as I call it) to respond to missages coming from synths and processing them and sending messages back ... so the box might be even out of sight for myself while playing.
But I could make a MIDI message that results in such kill (notes) functionality.

Yeah, it doesn't have to be a physical button directly connected - that's why I used quotes ;) Just some signal that can be sent to say "shut the hell up". Maybe get it to respond to a note you never play (C8, or something) so it's right there in front of you all the time at the keyboard. You may even end up incorporating it in your performances ;)

Let us continue this discussion in chat.


text:
Local variable usage in SRAM not counted
I use the following code to print the currently used SRAM space:
// this function will return the number of bytes currently free in RAM
// written by David A. Mellis
// based on code by Rob Faludi http://www.faludi.com

#include "TypeDefs.h"

int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

int printAvailableMemory(uint32 location)
{
  Serial.print(F("Available Memory at "));
  Serial.print(location);
  Serial.print(F(": "));
  Serial.println(availableMemory());
}

My main application (stripped) looks like:
...
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  printAvailableMemory(1);

  printAvailableMemory(2);

  test();
  printAvailableMemory(3);
}

void test()
{
  Preferences _prefs2;
  _prefs2.Set();
  printAvailableMemory(4);
}

While preference (.h) looks like:
#include "TypeDefs.h"

class Preferences
{
   private:
      uint8 _startChannel;
      uint8 _endChannel;
      uint8 _startNote;
      uint8 _endNote;
      uint8 _startCc;
      uint8 _endCc;
   ...
};

The output is:
Available memory at 1: 1065
Available memory at 2: 1065
Available memory at 4: 1065
Available memory at 3: 1065

I would expect the numbers (1065) would change, since a local variable (_prefs2) is made so at location 4 I would expect more space to be used.
Also, if I remove the _prefs2 code like below, the numbers stay the same.
void test()
{
    printAvailableMemory(4);
}

Why is the local variable not counted?

Local variables are allocated on the stack.

Are you actually doing something with _prefs2 other than setting it (which is what I assume .Set() does)? If not, the compiler may well have optimized it out. Check the generated assembly to see what happened.

Why is the local variable not counted?

Let us start with the function availableMemory(), what does it do?
int availableMemory()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

It returns the amount of memory between the top of stack (address of local variable v) and the heap end.
The answer lays in how the compiler works. One strategy that is used is function in-lining. This forces the functions test(), printAvailableMemory(), availableMemory(), etc. to be unfolded into loop() (which actually also gets unfolded into main()).
A common frame with the local variables is created and the variable for the top of the stack becomes one of them. You need a tougher test case to see how the stack top changes, e.g. tell the compiler not to in-line a function.
int availableMemory() __attribute__ ((noinline));

To check this generate the assembly listing for your sketch.
Cheers!

Thank you very much for this detailed answers. I should have known about inline compiling, I just am not used (anymore) to lower level languages (which I don't mean as offensive). Good to have such refresh about how compilers work.

authors: อำนวยศักดิ์ ธรรมวสิน