text:
How to add hysteresis to threshold values?
This code compares the analog input value against two thresholds, having three voltage regions. Then it will turn on an LED according to what region the read voltage is in.
The problem is that when the voltage read is very close to the threshold, the noise will disturb the output, resulting in an uncontrolled switching between LEDs.
I would need to add some sort of HYSTERESIS around my thresholds to avoid the uncontrolled switching, but I have no idea how to write this into the code language. Would anyone be able to help me writing the threshold bit?
This is the full code:
// these constant won't change:
const int BatteryVoltagePin = 14;   // the pin that battery voltage is attached to
const int GreenLedPin = 3;           // the pin that the green LED (On charge) is attached to
const int OrangeLedPin = 4;          // the pin that the orange LED (no risk) is attached to
const int RedLedPin = 5;             // the pin that the red LED (low battery) is attached to

// Variables will change:
int currentVoltage ;         // current voltage value
int previousVoltage ;     // previous voltage value

void setup() {
  // initialize the battery voltage pin as a input:
  pinMode(BatteryVoltagePin, INPUT);
  // initialize the green LED as an output:
  pinMode(GreenLedPin, OUTPUT);
  // initialize the orange LED as an output:
  pinMode(OrangeLedPin, OUTPUT);
  // initialize the red LED as an output:
  pinMode(RedLedPin, OUTPUT);
}

void loop() {
  // read the voltage across the battery voltage pin:
  currentVoltage = digitalRead(BatteryVoltagePin);

  // compare the current voltage value to its previous value
 if (currentVoltage != previousVoltage)

 delay(10);

    // value above maximum threshold
    {
     if ((( ( analogRead(BatteryVoltagePin) ) > ( 699 ) ))
        {
        digitalWrite(GreenLedPin, HIGH);
        }
        else
        {
          digitalWrite(GreenLedPin, LOW );
        }
    }

    //value between two thresholds (middle region)
    {
     if (( ( ( analogRead(BatteryVoltagePin) ) <= ( 699 ) ) && ( ( analogRead(BatteryVoltagePin) ) >= ( 628 ) ) ))
        {
        digitalWrite(OrangeLedPin, HIGH );
        }
        else
        {
          digitalWrite(OrangeLedPin, LOW );
        }
    }

    // value below minimum threshold
    {
     if (( ( analogRead(BatteryVoltagePin) ) < ( 628 ) ))
        {
        digitalWrite(RedLedPin, HIGH);
        }
        else
        {
          digitalWrite(RedLedPin, LOW );
        }
     }

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
 }

This kinda sounds like a case where you may need debouncing... Have you already done this?

no I haven't. Could you explain this in more details please?

Adding hysteresis behavior to your code is not difficult. You just need to store the state you're in and make the thresholds for transitioning into another state dependent on that.
You can use an enum to store the state:
enum BatteryStates {
  Red, Orange, Green
};

Then, instead of defining and checking against one threshold value, define two thresholds for each transition, separated by so much that you don't observe the undesired flip-flopping behavior.
For example, when transitioning from Green to Orange you could do something like this:
if ((state == Green) && (battery < 690))
  state = Orange;

And the other direction would use a slightly higher threshold
if ((state == Orange) && (battery > 700))
  state = Green;

so that small fluctuations of the voltage do not cause flip-flopping.
(Note that my code assumes
int battery = analogRead(BatteryVoltagePin);

The variable state should be declared and initialized like so:
enum BatteryStates state = Green;

Instead of an enum you could use a simple int and map each state to a number (e.g. red = 1, orange = 2, green = 3), but using enum makes the code easier to read and write. (In fact enum does use integer numbers.)
I might also use a switch statement instead of an if chain to implement the transitions, but that's a matter of taste.)

Thanks for your answer!!
But I do not know how to use the statmement enum. It looks like arduino IDE does not recognise it.
Could you please explain this in more details?

enum is not highlighted by the syntax highlighting. But it is accepted by the compiler. I have added some details.

Many thanks for your help! However, I am new to programming and I cannot make full sense of all this. I do understand the logic behind it... but when I try to put it together it does not work. If you could post a little working example that does compile, perhaps initialising all the variables etc, it would help a lot!

I am happy to help with concrete questions but I need to ask you to do your part: Try to solve the problem yourself first and if you fail describe where you need help.

This includes hysteresis and uses some loops and arrays to simplify and compact the code, since the logic for each range is essentially the same.  More ranges are easy to include by extending the Cutoffs and LedPins arrays (one more led than cutoff).
const int VoltagePin = 14;
const int Cutoffs[] = { 628 , 699 };
const int NumCutoffs = sizeof(Cutoffs)/sizeof(int);
const int Hysteresis = 5;

const int LedPins[NumCutoffs+1] = {5,4,3};

int Level = 0;
int Voltage = 0;

void setup()
{
  for (int i=0; i<=NumCutoffs; ++i) {
    pinMode(LedPins[i],OUTPUT);
  }
}

void loop()
{
  Voltage = analogRead(VoltagePin);

  while (Level < NumCutoffs && Voltage >= Cutoffs[Level]) {
    ++Level;
  }

  while (Level > 0 && Voltage < Cutoffs[Level-1] - Hysteresis) {
    --Level;
  }

  for (int i=0; i<=NumCutoffs; ++i) {
    digitalWrite(LedPins[i], i == Level);
  }

  delay(20);
}

Your original code had digitalRead() instead of analogRead().  The voltage line should be connected to an analog pin (like A0) and then VoltagePin should be the corresponding pin.   Hysteresis should be tuned for your application.

Here is what I do. I detect whether the voltage is rising or falling and adjust the threshold based on that.
int ledPin = 13;   //pin 13 will be connected to the MOSFET SS relay

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

void loop() {
    int sensorValue = analogRead(A0); // This is the main battery voltage sensor
    int RLA1;   //this will be connected to the MOSFET SS relay
    float threshold; //  To enable some hysteresis and prevent the relay from chattering, we move the threshhold, depending on whether we are going up or down

    float Vmainold;  //  Used to detect whether we are going up or down
    float  Vmain;   // Main battery voltage.
    float Vaux;     // Auxillary battery voltage

    Vmain = sensorValue / 204.6 + 9.8;   // Add back the ~10V that the zener shifts for higher resolution

   if (Vmain > Vmainold) threshold = 13.2;  // If the voltage is rising, set threshhold to 13.2
   else
    if (Vmain < Vmainold) && (Vmainold > 12.8) threshold = 12.8 // If the voltage is falling and previous voltage is above TH, set theshhold to 12.8
    else
        if (Vmain = Vmainold) threshold = 13.2;  // If the voltage is stable, set threshhold to 13.2

   if (Vmain >= threshold) RLA1 = 1; //  Charging

   else
    if (Vmain < threshold) { RLA1 = 0;  Vmainold = Vmain; }  // Not connected

   delay(1000);
   Serial.print(Vmain);
   Serial.print("  Main  ");
   Serial.print(Vmainold);
   Serial.print("  old  ");
   Serial.println();
   Vmainold = Vmain;
   digitalWrite(ledPin, RLA1);
}

`

The state machine is a solid approach.
For this simple case, you can also solve this by implementing small dead bands around the change levels.  When the value is in a range near the transition threshold, do nothing.  Only when the value is certainly above or below the transition, make the change.  Your code would be:
// Variables will change:
int currentVoltage = 0;         // current voltage value
int previousVoltage = 0;     // previous voltage value

void loop() {
  int deadband = 5;
  // on very first loop, start with no dead band
  // this is necessary in case starting voltage is in
  // middle of a transition range
  if (0 == previousVoltage) {
    deadband = 0;
  }

  // read the voltage across the battery voltage pin:
  currentVoltage = analogRead(BatteryVoltagePin);

  // test the voltage against the three ranges
  // value above maximum threshold
  if ((699+deadband) < currentVoltage) {
    digitalWrite(GreenLedPin, HIGH);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, LOW );
  }

  //value between two thresholds (middle region)
  if (((628+deadband) < currentVoltage) && (currentVoltage <= (699-deadband))) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, HIGH);
    digitalWrite(RedLedPin, LOW);
  }

  // value below minimum threshold
  if (currentVoltage < (628-deadband)) {
    digitalWrite(GreenLedPin, LOW);
    digitalWrite(OrangeLedPin, LOW );
    digitalWrite(RedLedPin, HIGH);
  }

  // Note that at this point, none of the if cases above
  // might have been true.  When the voltage is right near the
  // thresholds, do nothing.  Only when the voltage is definitively
  // in the range does the LED state change.

  // save the current state as the last state,
  //for next time through the loop
  previousVoltage = currentVoltage;
  delay(10);

  return;
}

In function, this will achieve the same result as hysteresis.


text:
Deviation of power consumption between datasheet and real world?
According to the Atmega328P-PU Datasheet (side: 589) the current consumption of the microcontroller should be around 9.5mA (at 16MHz and 5V).
But I measured 15mA. (Nick Gammon who did some pretty good power saving research(gammon.com.au/power) got the same)
There is nothing connected to the outputs. The code I ran was this:

void setup () {}
   void loop () {}

Now I'm wondering if this is just a normal deviation (datasheet to real world) or if Atmel measured their current consumption in a state that is different from mine?
EDIT:
I forgot to mention.. I didn't use it with the Arduino Uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.
Now that I think about it..  Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source."
Is it possible that the oscillator needs that extra 5mA?
EDIT2:
Here is a screenshot of my schematic:

And a screenshot of the ATmega328P-PU Datasheet:

Perhaps if you show your schematic. I have got consistent results from my tests.

Thank you!
I added a schematic and screenshot of the datasheet.
By consistent you mean that the results of your measurements were as one yould expect after reading the datasheet?

What kind of meter are you using. Also, try adding a bypass cap to the VCC line (unlikely to help, but still good practice). Do you have any other ATMega328 chips around, or just this one? Did you set the correct fuses?

Set all your IO pins to outputs and set them LOW.  Then disable all timers and interrupts.  What results do you get then?

According to the datasheet:

All current consumption measurements are performed with all I/O pins configured as inputs and with internal pull-ups enabled.

That was the critical point. Trying this sketch:
int main ()
  {
  for (int i = 0; i < 20; i++)
    pinMode (i, INPUT_PULLUP);
  }  // end of setup

Note that timers are not running (your sketch would have timer 0 running):
With that sketch, even using the crystal and capacitors (I actually had a resonator) the consumption at 5 V at around 20 °C was 9.2 mA which is within spec.
Fuses:
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDF
EFuse = 0xFF
Lock byte = 0xFF
Clock calibration = 0x96

If we turn pull-ups off:
int main ()
  {
  }  // end of setup

Now it consumes 14.4 mA, closer to what you measured.

And with your actual test sketch:
void setup () {}
void loop () {}

It consumes 15.5 mA, which is more, because Timer 0 is running (started in the init function). It is also close to what I had on my page about power - 15.15 mA.

So, working as expected. Those pull-ups are important, to stop the input drivers consuming current.
I did mention further down in my page the importance of configuring the pins:

Testing in SLEEP_MODE_PWR_DOWN:

All pins as outputs, and LOW: 0.35 µA (same as before).
All pins as outputs, and HIGH: 1.86 µA.
All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

Notice the difference there of 0.9 µA when asleep. It would appear that there is an ever greater difference if the processor is awake.

Thank you so far! I have to wait until my new chip arrives and I can test this.

Probably Atmel measured the chip consumption without any code. An empty sketch has some code in it (believe it or not).
Another possibility is the remaining components like voltage regulator, usb chip are also consuming some current.
Try to test in a bare minimum configuration.

Thank you for your reply!
I forgot to mention.. I didn't use it with the arduino uno board but as standalone device. There was only a 16Mhz oscillator with two capacitors connected. Power came directly form Power supply.

Now that I think about it.. Datasheet says this regarding the current measurement: "A sine wave generator with rail-to-rail output is used as clock source." Is it possible that the oscillator needs that extra 5mA?

@elperro, now that you've added the info from those two comments to question, feel free to delete the comments.

source: Stack Exchange

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

authors: พี่ โน๊ต. นอนน้อย

sort: votes


text:
How to make PCA9685 work with Arduino Due?
I have Arduino Due and PCA9685.
I use this library:
https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
The board does not do anything with servo connected. I tried to use SDA/SCL pins and SDA1/SCL1 pins, I tried to use or not use pullup resistors. The board does not react in any case.
The PCA9685 is 100% working, because it operates properly when I connect it to my Arduino Mega using the same library, it works without pullups.
Also I noticed the following indicium, when I tried to use  this scanner
http://playground.arduino.cc/Main/I2cScanner I have no detected devices on SCL1/SDA1 but have detected 2 devices at 0x40 and 0x70 when I connect the board SDA/SCL pins.

I made it working by this way: despite PCA9685 datasheet recommendations, we do not need to connect OE pin to VCC. Also we do not need to connect OE to ground as it recommended in some instructions related to other Arduinos.
So we should leave OE pin unconnected.
Also we should use 4,7K pull-up resistors to connect SDA and SCL to VCC.
The board can be used without level converters.
No special program/libraries changes needed. So it was a hardware problem.

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


text:
Serial write skips on Arduino Due
I bought Feetech SCS09 smart servos (also known as SCS009 or SCS0009).
Please note that these servos are not regular PWM servos, they are devices that communicate with board using Serial connection via device named TTLinker that converts UART to half duplex protocol. So the question is about the problem with serial communication only.
The seller provided me Arduino library to work with the servos.
The simplest testing sketch looks as this:
#include <SCServo.h>

SCServo SERVO;

void setup() {
  Serial2.begin(1000000);
  SERVO.pSerial = &Serial2;
  delay(500);
  SERVO.EnableTorque(1, 1);
  SERVO.EnableTorque(2, 1);
}

void loop() {
  SERVO.WritePos(1, 1023, 4000); // Servo ID:1, rotate to the position:0x2FF
  SERVO.WritePos(2, 1023, 1000); // Servo ID:2, rotate to the position:0x2FF
  delay(4000);
  SERVO.WritePos(1, 20, 3000); // Servo ID:1, rotate to the position:0x000
  SERVO.WritePos(2, 20, 1000); // Servo ID:1, rotate to the position:0x000
  delay(3000);
}

The code works perfectly on Arduino Mega and allows to independently control servos.
But with Due I have problems: not all commands can be performed. So if compile the code for Due only servo ID1 works, but ID2 do not work at all.
When I add delays between commands the servos started to work
    SERVO.WritePos(1, 1023, 4000); // Servo ID:1, rotate to the position:0x2FF
    delay(10);
    SERVO.WritePos(2, 1023, 1000); // Servo ID:2, rotate to the position:0x2FF
    delay(4000);
    SERVO.WritePos(1, 20, 3000); // Servo ID:1, rotate to the position:0x000
    delay(10);
    SERVO.WritePos(2, 20, 1000); // Servo ID:1, rotate to the position:0x000
    delay(3000);

When I set delays between 1 and 9 the both servos can work but sometimes skip commands. Servos can skip 1-4 actions and then start to work again. The less delay I set the more random skips I get.
So I think here is some specialities regarding Serial connection on Arduino Due. What It can be? Why delays help to make it working?
By the way I read that Arduino Due can have problems with 1000000 baud rate and I tried different, even significntly less baud rates (for example 38400) with Arduino Due: the result is the same.
I need to explain how WritePos function works in the library
int SCSProtocol::WritePos(u8 ID, u16 Position, u16 Time, u16 Speed)
{
    return writePos(ID, Position, Time, Speed, INST_WRITE);
}

int SCSProtocol::writePos(u8 ID, u16 Position, u16 Time, u16 Speed, u8 Fun)
{
    flushSCS();
    u8 buf[6];
    Host2SCS(buf+0, buf+1, Position);
    Host2SCS(buf+2, buf+3, Time);
    Host2SCS(buf+4, buf+5, Speed);
    writeBuf(ID, P_GOAL_POSITION_L, buf, 6, Fun);
    return Ack(ID);
}

void SCSProtocol::Host2SCS(u8 *DataL, u8* DataH, int Data)
{
    if(End){
        *DataL = (Data>>8);
        *DataH = (Data&0xff);
    }else{
        *DataH = (Data>>8);
        *DataL = (Data&0xff);
    }
}

int SCSProtocol::Ack(u8 ID)
{
    if(ID != 0xfe && Level){
        u8 buf[6];
        u8 Size = readSCS(buf, 6);
        if(Size!=6){
            return 0;
        }
    }
    return 1;
}

void SCSProtocol::writeBuf(u8 ID, u8 MemAddr, u8 *nDat, u8 nLen, u8 Fun)
{
    u8 msgLen = 2;
    u8 bBuf[6];
    u8 CheckSum = 0;
    bBuf[0] = 0xff;
    bBuf[1] = 0xff;
    bBuf[2] = ID;
    bBuf[4] = Fun;
    if(nDat){
        msgLen += nLen + 1;
        bBuf[3] = msgLen;
        bBuf[5] = MemAddr;
        writeSCS(bBuf, 6);

    }else{
        bBuf[3] = msgLen;
        writeSCS(bBuf, 5);
    }
    CheckSum = ID + msgLen + Fun + MemAddr;
    u8 i = 0;
    if(nDat){
        for(i=0; i<nLen; i++){
            CheckSum += nDat[i];
        }
    }
    writeSCS(nDat, nLen);
    writeSCS(~CheckSum);
}

int SCServo::readSCS(unsigned char *nDat, int nLen)
{
    int Size = 0;
    int ComData;
    unsigned long t_begin = millis();
    unsigned long t_user;
    while(1){
        ComData = pSerial->read();
        if(ComData!=-1){
            if(nDat){
                nDat[Size] = ComData;
            }
            Size++;
            t_begin = millis();
        }
        if(Size>=nLen){
            break;
        }
        t_user = millis() - t_begin;
        if(t_user>IOTimeOut){
            break;
        }
    }
    return Size;
}

int SCServo::writeSCS(unsigned char *nDat, int nLen)
{
    if(nDat==NULL){
        return 0;
    }
    return pSerial->write(nDat, nLen);
}

So the problem is somewhere here: Arduino Mega works good, but it seems like Arduino Due have no time for on of the operations.
You can see more info here:
Servo
TTLinker device
Arduino library

Please tell the name of the seller, give a link to your servo motors, give a link to the library that you use and to TTLinked. We would like to look into the hardware and library that you use, but then we have to know what you have.

I added links to my post, you can check, thanx

This is a tough problem. The TTLinker uses 5V signals, and the Due uses 3.3V signals, so you do need indeed a level converter. Can the level converter do 5V to 5V ? to try the Mega board via the level converter ? Do you use a fast logic level converter ? or a weak slow open drain level converter for I2C ? The way you describe the problem is most likely a software problem. The Arduino Due uses 32-bits integers, and the Mega 16-bits. However, I can't find a problem with 32 versus 16 in the library. With a logic analyzer you can get more information and get a little closer to the problem.

I have no experience of the Due, but I have just noticed that Tx0 has a higher max output current (15mA) than Tx1 (3mA), could that be having an affect?

Jot, I use this level converter http://ali.onl/CdL based on TXS0108E, I will try it with Mega to figure out whether it is the converter problem or not

I just connected the TTLinker directly without the level convereter. It work but with the same bug. So the level converter is not needed and it is definitely not a cause of the bug

@SergeyKravchenko I do not agree too much with your last sentence. I checked the Vih of the TTLinker and the Voh of the Due. The TTLinker I found states that the interface is a 74HC126D, powered at 5V. With these data, the Vih seems to be around 3.5V; your 3.3V powered due will never be able to reach this. Moreover the output voltage from the TTLinker is again 5V, and the Due is NOT 5V tolerant. So use the converter every time you attach it to the Due. Then, please show us the schematic you used (TXSs should have one side lower than the other, IIRC)

@fragugi87, I just tried it myself and saw the action in work by my own eyes:) to make it working I supplied TTLinker from Arduino Due 3.3V output, not 5V... moreover 74HC126D can work at 2-6V, it is written in the datasheet, so there is nothing strange... but the bug still exists: I can get proper working only with delays between commands

I figured out that 250000 baud rate is the only choice for the Arduino Due with these servos. Less baud rates cause skips on Arduino Mega also, so this speed is not enough for fast data transfer.
Higher baud rates work good on Mega too but cause garbage on Due.
So let's summarize: these servos with TTLinker (TXS0108E) work good with Arduino Due at 250000 only and with Arduino Mega at 250000 and higher baud rates.


text:
How much current does an Arduino Mega draw from a LiPo battery (5,000 mAh)?
I went through Sparkfun's website on how to power a project because I wanted to calculate how much battery capacity I needed for my project. I saw an ATmega 328 micro-controller that is used as the brains for the circuit: it draws about 20mA under normal conditions.
So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me, I am new to this.

Do you have a reasonably accurate multimeter? You can put it in series with the power circuitry and measure the power draw in your specific situation.

It should be a clamp ammeter otherwise you risk smoking your multimeter with the large currents.

A clam amp meter for measuring milli amps???

I once measured the current draw of my Uno in normal conditions (active mode), and it was around 40 – 50 mA. A bare ATmega328P in POWER_SAVE mode is about 2 µA. Never measured on a Mega.

ya, i dont think you need to worry about a clamp style meter for measuring the current draw of a microcontroller......

The important thing to realize here is that the capacity of the battery does not affect the amount of current drawn. Your Mega will draw the same whether it is connected to a 1000 mAh battery or a 5000 mAh battery. The larger battery will just last longer.
Tests on my Mega2560 Arduino show that (with no peripherals connected) it draws about 70 mA from a 7V supply, and slightly more (72 mA) from a 12V supply (the voltage regulator has to throw away some of the extra voltage as heat). (However, see below)
The exact amount it would draw in practice would be strongly correlated to what things you have connected. For example, LEDs, motors, shields, other devices.
I have a page about power saving that you might find useful if your objective is to minimize power usage.

Edited to add more about power consumption
It appears that my initial claim that the current consumption goes up with an increase in voltage was wrong. With Majenko's help I made up a detailed set of automated tests, increasing the Mega2560 power input by increments of 200 mV, taking a reading from both the power supply and my multimeter, averaging each one over ten readings, and plotting the results. This is what I got:

The two measurements seem to be consistently different by 0.2 mA. What this shows is that at 7V, the current consumption is 65.3 mA, and at 12 it is 64.1 mA, about a milliamp less.
I do, however, stick by my original assertion that the capacity of the battery will not affect consumption, and a larger battery will just last longer.

Sorry, but I just read this now (since it was bumped to the homepage) and I'd like you to further explain the "the voltage regulator has to throw away some of the extra voltage as heat" sentence. The only thing that should increase the current consumption is the RN5C-D couple (20k, which draw 0.35mA at 7V and 0.6mA at 12V, for an increase of 0.25mA); the fact that you are experiencing a 8 times larger increase is puzzling on my side. Even thermal increase in the 1117 has a much lower impact (50°C change about 5% the quiescent current - which is 6mA, so 0.3mA). What am I missing?

I'm seeing about 100mA from my Mega2560. It's static within about 1mA or so all the way from about 6.6V upwards.

@frarugi87 - upon re-measuring I am still finding between 1 and 1.8 mA more consumed at 12V. I can't fully explain that but am working on it. Which revision Mega2560 board do you have? Mine doesn't seem to have a revision number, so it is probably the first one released.

@NickGammon I haven't measured mine; the data I gave came from an analysis of the schematic of rev3; the rev1 mega2560 has another IC, so maybe it's its fault...

@frarugi87 It appears that I was wrong. See amended answer. Much more extensive testing shows that the current consumption decreases slightly with an increase in voltage.

@NickGammon Thank you for your effort in this :) I think this is still strange, since I expected an increase in the current of some hundreds of microamps; maybe the part was heating up slowly, so testing it back and forth (7 -> 12 -> 7) could give more infos, but I fail to understand why a heated up part consumes less... In any case I agree with you; this is very interesting, but is OT in this answer. If you plan to add a page to your website with these measurements and so on please share the link since I will be very interested in your tests and opinions :)

@frarugi87  You are right I am getting off the topic, but just for your info, running the loop backwards (12V down to 7V) gave a very similar plot, so it seems the part is heating up, and that is causing the difference.

@NickGammon Good to know; thank you for these updates and for your patience :)

I saw an ATmega 328 microcontroller that is used as the brains for the circuit: it draws about 20mA under normal conditions.

the datasheet provides the best guidance on that. typically 10ma - 20ma is fairly standard for 8-bit mcus. other components on the board, like opamps, or regulators, leds, may consume a little bit more so I would say 20ma - 30ma total is a good estimate for the board.

So that got me thinking: how much current will an Arduino Mega draw from a LiPo battery of 7.4V with 5,000 mAh 2s 25C under normal condition? Please anyone do help me out and pardon me I am a newbie to this.

the datasheet showed 20ma typical so I would put the board to 30ma total. 5000mah/30ma = ...

Note that one of those “other components on the board” is itself a microcontroller that may draw its own 20 mA.

And looking at the measurements in another answer, the current is 65-70mA

You may be right that AtMega chip will draw relatively small amount of energy. But there are other components in the Arduino that will draw much more. (Voltage regulator as a best example.) In the end, the current drawn can (and will) be 10x larger.
And there is another problem, you have to know how much power will connected sensors draw.
What you can do is build your own 'less greedy' Arduino and use sleep abilities of AtMega chips.
Here are some links to go through:
https://openhomeautomation.net/arduino-battery/
https://circuits.io/circuits/1717500-power-rail-blocking-with-an-arduino/
http://www.gammon.com.au/power

Why do you say tht the voltage regulator is an example of what draws much more current? usually the voltage regulator by itself consumes  moderate current (6mA in the worst conditions), and only when using the Vin power supply. What drains the most are the two microcontrollers. and there are also some LEDs....

How did you get 6mA?

Sorry, I remembered wrongly. It's 6mA typically, 10mA worst case. From the schematic you see that the voltage regulator is an NCP1117; its datasheet has a parameter called "Quiescent Current", which has that value

"Quiescent Current" is the current the regulator disipates when there is no load... POWER dissipation of the voltage regulator will be much bigger. Power, not current. For sure using 9V battery and regulator is much worse (energy-wise) than providing directly 5V. (Just guess, but i think 9V battery (as it is compound of cells) has less capacity than the same size 5V battery...)

BUT I do agree, that voltage regulator was not the best example to start with!

yes, the power dissipated by the voltage regulator is very large. For instance when you have a 11V power supply, the regulator will dissipate about the same power as all the components at 5V combined together. But the current drawn depends mostly on the components at 5V. In any case I noticed you wrote "draw ... energy", but since draw is linked to current I thought that you were referring to it

I should have expressed more clearly... In case of voltage regulator, that is not the case. But in case of unnecessary leds, converters, other components, the DRAW is a case.


text:
SSD1306 / U8glib display fonts and commands
I cannot seem to find any reference for the SSD 1306 or U8glib display font library or any command reference, like all the options for display() etc. For my fonts I been going into the utility folder and scrolling through notepad for the U8glib library but its very croweded with numbers and code. is there any reference for both libraries online that is user friendly?

First, u8glib is superceded by u8g2
Second, the u8glib wiki has a command reference and font reference.
As does the u8g2 wiki.
Neither reference lists a display() command.

OK GREAT iLL CHECK IT OUT

lots of good info on there, thanks. So I added some font and sometimes I get many symbols (I have a scroll set up) How do you grab just one of those symbols, for example, an arrow?

If you have a different question, post it as a new question.

there is not much variety of fonts available

What are you actually looking to do? There are many fonts and even non-English character set fonts.

display is in the SSD1306 library, is there a wiki for that?

Im just toggling through some functions and have a display to show what mode im in but the default font kind of sucks. Looking for something more creative.

https://github.com/olikraus/u8g2/wiki/fntlistall hundreds

u8g2 handles SSD1306 communication, so you should not need a separate library...

ok Ill have to load the U8g2 into my library

what about icons, like battery indicators, meters, etc. is there librarys with ready made images, or bitmap images?

I wonder if you are even reading or looking at the font lists available on the links. https://github.com/olikraus/u8g2/wiki/fntgrpsiji

yeah I read through all of them, look about the same, adobe old standard etc

trying this one now u8g_font_helvB14, seems to be about the best one

so in that github library you have provided with the siji text, how do I grab one of those icons? I dont need them all

You set the font using something like u8g2.setFont(u8g2_font_siji_t);. Looking at the font diagram, some battery icons start at character position 0xe242 through 0xe24b. You may need to enable UTF8 support with u8g2.enableUTF8Print();. Then, you print a string with the 2-byte 'character', like u8g2.print("\0xe2\0x42"); Note, I haven't tested this myself, but I read the documentation.

Ok I see, I will try it out


text:
Using timer2's ISR instead of timer1's in Arduino wiring.c breaks Serial object
I want to change timer0 frequency because I need to use 4 PWM pins at a frequency lower than 500Hz and the SPI on an ATmega328. So I changed timer2 to Fast PWM with 64 divisor, enabled the overflow interrupt for timer2 and disabled the overflow interrupt for timer0:
  TCCR2A = _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS22);
  TIMSK2 |= (1 << TOIE2); // enable overflow interrupt for timer2
  TIMSK0 &= ~(1 << TOIE0); // disable overflow interrupt for timer0

and changed the ISR vector in wiring.c from ISR(TIMER0_OVF_vect) to ISR(TIMER2_OVF_vect).
But delay doesn't work. What can be the problem?

I would guess Serial and delay rely on timer 2 and you have just changed it.

HardwareSerial does not use timers. delay uses Timer 0.

Please post a Minimal, Complete, and Verifiable example.

I don't know if millis() and micros() work - why not? Write a "blink" sketch and find out.

Now everything works except for delay()

delay() uses micros() and micros() reads the hardware registers, like this:
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t = TCNT0;
#elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t < 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

You would need to change all those references (TCNT0, TIFR0, TOV0 etc.) to use the Timer 2 equivalents.

This fixed it. Strange that micros() works fine without the fix?

Appeared to work. I'm sure over a longer interval you would have seen anomalies.


text:
Set Arduino digitalRead reference voltage
I wanted to know if the reference voltage for the digitalRead() function could be set to a particular voltage, either with an external reference or internally.
In the Arduino reference under the constants heading they have mentioned that they use 3V as reference for the boards I'm using (an Arduino Uno R3). But I want to change it to be a little lower.
Is it possible and if so how?

You could try not digitalRead, but analogReadVoltage. Analog Read Voltage
From Arduino examples:
/*
  ReadAnalogVoltage
  Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

 This example code is in the public domain.
 */

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  // print out the value you read:
  Serial.println(voltage);
}

@SumanRoy: How does this help (changing the digital reference)? Or are you instead going to measure the voltage and make your own HIGH/LOW decision (in code)?

@JRobert yes, you will have to make few tests, get your reference point ant everything above that point will count as "HIGH". Its up to your imagination :)

@JRobert yeah that's it. Measure the voltage and return a HIGH  LOW

for a 5 volt Arduino anything over 2.7V will be considered as a digital HIGH whereas anything below 0.4V will be a digital LOW.

To stick to ATmega 328 datasheet (http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf p313), I'd say that anythng below 1.5V (0.3 x Vcc) is cnsidered LOW, and anythng above 3.0V (0.6 x Vcc) is considered HIGH.

... and of course, anything in-between is undetermined, i.e. sometimes HIGH sometimes LOW.


text:
Why is timer0 the fastest timer in the arduino?
In the documentation, it shows that the higher  frequency that can be reached with an Arduino UNO for and 8bits PWM is using timer0  with the pre-scaler  set at 1. That  gives a Fs of 62500 Hz, but why is that so?
I understand the Prescaler is dividing the frequency, but why it does start at 62500 Hz and  timer1 and timer2 have as maximum 31372 Hz.

Timers 1 and 2 are configured by the Arduino core library to run the so
called “phase correct PWM” mode. In this mode, the timers count
forward from 0 to 255, and then they count backwards to zero. Timer 0 is
configured by the same library in “fast PWM” mode, where it counts
from 0 to 255 and then overflows back to zero in a single timer cycle.
You can, if you want, configure timers 1 and 2 in fast PWM mode. For
doing this, you will have to access their I/O registers directly. C.f.
the datasheet of the relevant microcontroller for details.
A couple of links:

the datasheet of the
ATmega328P
microcontroller describes all the possible configurations of the
timers (sections 15, 16 and 18 for timer 0, 1 and 2, respectively)
the source code of the Arduino init()
function
to see how Arduino core configures them.

Where is that function called? is it in the bootloader?

@LuisRamonRamirezRodriguez: No, init() is called by main().


text:
Connecting a LSM9DS0 9DoF module to Arduino Uno
I got a bit confused by Sparkfun's hookup guide for this 9DoF breakout module.
It says the VDD-in on the breakout "should [get voltage] regulated between 2.4V and 3.6V", yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.
Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?

I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.
In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.

In the second example it states "... if you have a 3.3V-operating Arduino – like the 3.3V/8MHz Pro – you can connect SDA and SCL directly from microcontroller to sensor." - is this equivalent to using the Arduino Uno's 3.3V pin?

Ah, there's two voltages to consider, to voltage to power a device and the voltage its logic runs at. It's the latter that's referred to here. Essentially at what voltage in digital communications logical HIGH is considered to be. This IMU can only tolerate digital communications (SDA & SCL) at 3.3V logic level. Your UNO can supply power at 3.3V but has a 5V logic level for its pins, the logic level converter takes 5V signals from the Arduino and converts them to 3.3V for the IMU and takes the 3.3V replys and converts them back up to the 5V level the Arduino expects.

Hm, interesting. So did I understand correctly that I should not connect it straight to the 3.3V pin of my Uno?

You can safely power it from the 3.3V pin, but cannot safely communicate over SDA and SCL (or any other UNO pins) as they are at the wrong voltage. You'll need a logic level shifter to safely connect those pins.
Take a look at sparkfun's logic level guide if you want to learn more about why this is.

Thanks, I've since read up on it and realised I confused logic voltage and powering voltage here, as I've had never heard of logic voltage levels. :)


text:
Accelerometer sensor gy-61 convert to m/s2
I have a problem calibrating my GY-61 accelerometer on an Arduino Uno to get values in m/s2.
Analog-reading code:
const int xPin = A5;
const int yPin = A4;
const int zPin = A3;
// ...
void loop() {
   int xRead = analogRead(xPin);
   int yRead = analogRead(yPin);
   int zRead = analogRead(zPin);

   float xData = (((float)xRead - 337.92) / 61.44 * 9.81);

   accData= sqrt((xData*xData)+(yData*yData)+(zData*zData));

xData should show values in m/s2.
What do those values  337.92  and  61.44 mean and how can I calibrate them to get right values?
Values I get (in one position without moving):
xData   yData   zData    accData
-11.16   1.61   -0.79    11.31
-0.79  -11.48    0.01    11.51
-0.47   -0.63  -10.68    10.71

accData should be near 9.81 m/s2, also x or y or z, depending on rotation.

I get some answers on other forums, this and this . Second solution is better, but i still get strange readings. So i ordered some new acc sensors for testing, one of them is ADXL 335, which have many libraries and instructions. But still want to figure it out about GY-61.


text:
How to make 2 LEDs flash in a 5/4 Polyrhythm?
Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.
//Making a 5/4 Polyrhythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {

  for(i=0; i<5; i++)
  {
     digitalWrite (LED13, HIGH);
     delay(500);
     digitalWrite (LED13, LOW);
     delay(800);
  }

  for(i=0; i<4; i++)
  {
     digitalWrite (LED7, HIGH);
     delay(500);
     digitalWrite (LED7, LOW);
     delay(1000);
  }

}

Where it is feasible to do so, a problem with a simple ratio like this may be most readily addressed by running something at the least common multiple and acting, or not, on each output as appropriate.  Likely this means you will need an event happening at 20 times the desired repeition rate, which (if you intend the flashes to be visible as such to a human), is not even remotely difficult for an Arduino to handle.  One LED would flash on events 0, 4, 8, 12, and 16, and the other one events 0, 5, 10, and 15...

It is up to you to decide if you want each LED to be one for one 1/20th or something else, for example you could double the rate to 40x and generate distinct events for on and off.

I generally calculate whether the led must be on or off, based on the current time.
//Making a 5/4 Polyrythm with 2 LEDs
const int LED13 = 13;
const int LED7 = 7;
int i = 5;

void setup() {
   pinMode(LED13, OUTPUT);
   pinMode(LED7, OUTPUT);
}

void loop() {
    // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
    // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
    bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
    bool led7on  = (millis()/750)%2!=0;
    digitalWrite (LED13, led13on);
    digitalWrite (LED7, led7on);
    delay(10);
}

Thank you very much. Could you explain what the (millis() / 600) %2 means? Is the millis just the millisecond time (from 0 to 600) is modded (%) with 2 and if it comes out odd or even determines if the LED is on?

@JonStapchuck millis() is the number of milliseconds since the board powered on.  This is then divided by 600, and if the result is odd, the LED turns on, otherwise it turns off.

See the comments inside the code.

See https://arduino.stackexchange.com/a/17929/6628 with code like:
const int onTime = 500;
const int measureTime = (int) (60*1000/10);  // 10 BPM, or 1500*4ms/measure
const int off4 = measureTime/4 - onTime;  // take care these don't go negative
const int off5 = measureTime/5 - onTime;  //
unsigned long next5;
unsigned long next4;

...
loop(){
  unsigned long now;
  now=millis();
  ...
  if(next5 < now) {
     if digitalRead(LED13) { next5 = now+off5;   digitalWrite(LED13,LOW );}
     else                  { next5 = now+onTime; digitalWrite(LED13,HIGH);}
  }
  if(next4 < now) {
     if digitalRead(LED7)  { next4 = now+off4;    digitalWrite(LED7,LOW );}
     else                  { next4 = now+onTime ; digitalWrite(LED7,HIGH);}
  }

}


text:
Unable to flash bootloader on ATmega32U4 with AVR dragon
I am flashing a naked ATmega32U4, but the process fails in the end where it is verifying.
avrdude -c dragon_isp -p m32u4 -P usb -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m -v -B 100

avrdude: Version 6.1, compiled on Mar 23 2014 at 04:42:55
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/usr/local/Cellar/avrdude/6.1/etc/avrdude.conf"
         User configuration file is "/Users/SomeUser/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : dragon_isp
         Setting bit clk period        : 100.0
avrdude: usbdev_open(): Found AVRDRAGON, serno: 00A200050468
JTAG ICE mkII sign-on message:
Communications protocol version: 1
M_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              1
S_MCU:
  boot-loader FW version:        255
  firmware version:              7.38
  hardware version:              7
Serial number:                   00:a2:00:05:04:68
Device ID:                       AVRDRAGON
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : DRAGON_ISP
         Description     : Atmel AVR Dragon in ISP mode
         Vtarget         : 5.0 V
         SCK period      : 100.37 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as CB
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 62.28s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 152.35s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x66 != 0x6e
avrdude: verification error; content mismatch

avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: lfuse reads as FF
avrdude: safemode: Verify error - unable to read hfuse properly. Programmer may not be reliable.
avrdude: safemode: Sorry, reading back fuses was unreliable. I have given up and exited programming mode

avrdude done.  Thank you.

I get another verification error when i program without fuses:
avrdude -c dragon_isp -p atmega32u4 -P usb -U flash:w:Caterina-Micro.hex -u

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.16s

avrdude: Device signature = 0x1e9587
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "Caterina-Micro.hex"
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: writing flash (32730 bytes):

Writing | ################################################## | 100% 69.60s

avrdude: 32730 bytes of flash written
avrdude: verifying flash memory against Caterina-Micro.hex:
avrdude: load data flash data from input file Caterina-Micro.hex:
avrdude: input file Caterina-Micro.hex auto detected as Intel Hex
avrdude: input file Caterina-Micro.hex contains 32730 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 178.10s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x04 != 0x0c
avrdude: verification error; content mismatch

avrdude done.  Thank you.

can you try without setting the fuses?

Have you retried the same command several times? It can happen sometimes that the command fails due to a bad serial connection.

@Treesrule14, i tried without the fuses and the result is the same. Verification error. Although it seems like something goes right as the boards LED starts blinking. But i am absolutely not confident with the flashing.

@jfpoilpret, i have tried so many times that i stopped counting :-/

Does your board have any additional curcuitry connected to the SPI pins?

Try setting only the fuses first. By default the 32u4 runs at 1Mhz I belief. Try lowering the programming speed using -B 10 (not sure if this works for the dragon; I have to use this parameter when programming blank AVRs using my usbASP programmer).

@ChrisStratton, yes i have and there are 100Ohm resistors between the peripheral connected.

@Gerben, i have tried setting the -B flag but the results are extremely inconsistent. I am afraid that the AVR dragon is not playing nicely in OSX. Tommorow i will get my hands on a Atmel-ICE and see if it will play with me.

100 ohms may well not be enough to prevent interference with programming.

@ChrisStratton, how much is recommended?

@ChrisStratton, how much is recommended? I have MPU-9250 IMU connected to the SPI line, where there is 100Ohm resistors in series with that device.

If there is any way it could be driving signals (or clamping them? Is it powered? At what voltage?) I would want at least 1K.  Maybe best as a temporary test to remove the resistors to entirely break the connection and experiment with programming that way for an hour or two.

I literally gave up and got myself a Atmel-ICE which solved all my problems.

I think you need to pass the option -u to disable safe mode, see the avrdude documentation. Under the -u option the manual states:

If you want to change fuses you will need to specify this option

I tried to pass avrdude -c dragon_isp -p m32u4 -P usb -u -U flash:w:Caterina-Micro.hex -U lfuse:w:0xff:m -U hfuse:w:0xd8:m -U efuse:w:0xcb:m -U lock:w:0x2f:m with the -u option, but instead i am getting a bunch of avrdude: stk500v2_jtagmkII_recv(): failed. On the SPI line i also have another SPI device connected, which is seperated by 100Ohm resistors, so i am not expecting that its causing any problems?

I remember getting that same error programming with the dragon via avrdude. From memory, it was due to some kind of wiring problem. Not sure about the other SPI device, but working with the simplest possible circuit will always make it easier to debug.

ISP wiring problem perhaps? The thing is that the bootloader has been uploaded to the MCU once in a while, which is quite odd if theres a wiring error.

I meant a bad connection, which may still work intermittently

I will try to change the ISP cable and see if it does anything. I have changed USB cables just to verify that its not an issue.

I have updated my post. Its as if i flash the bootloader, it is extremely hard to reflash it afterwards. Im powering it with USB.


text:
Cannot program Arduino Micro in OSX without hard resetting the board every time
I am experiencing a problem when programming Arduino Micro in OSX Mavericks. I have tried to reproduce this problem in XCode and Arduino IDE and it is persistent. I need to make a hard-reset at the same time as a click the "program" button.
I have tried to use the new Leonardo bootloader to see if it solves my issue, but its still persistent.
I am running avrdude 6.1, what is the problem?
Stacktrace:
---- Size ----

Binary sketch size:   24162 bytes (of a 28672 byte maximum)
Estimated SRAM used:  733 bytes (of a 2560 byte maximum)
Elapsed time: 5.2 s

---- Reset ----

screen -X kill

No screen session found.

make: [reset] Error 1 (ignored)

sleep 1

9.2-RESET:  <   micro   ./ ./

stty -f /dev/tty.usbmodem1411 1200

---- Upload ----

10.6-UPLOAD:  <     micro   ./

/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -patmega32u4 -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -D -cavr109 -b57600 -P/dev/tty.usbmodem1411 -Uflash:w:Builds/embeddedcomputing.hex:i

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

Try updating the bootloader. Also, is the problem also present on none-OSX systems?

@Gerben, i have tried updating it, still the same result. I am considering trying Leonardo bootloader instead to see if it does any good.

This Arduino.cc article describes the differences between Leonard & Micro vs. other Arduinos, including the fact that Micro does not have a separate USB processor on board but creates a virtual USB with the main processor. There is no (or a very different) auto-reset mechanism. There is apparently a way for the IDE to open the Mac's USB at 1200 baud to cause the Micro to reset; then the IDE can wait for the virtual USB to re-appear. But it also says you may need to use the reset button suggesting the 1200 baud dance doesn't work all that reliably.

Thats how far i have reached so far, but unfortunately it does not solve my problem as resetting manually every time i am uploading a sketch is a pain in the @$$.

I believe the reliability of the reset depends on the sketch (i.e. that it's possible to write code that inadvertently disables the auto reset code). Have you tried reproducing this with e.g. a blink sketch?


text:
Unable to alter SPI speed on Arduino Micro
I am using SPI to communicate with a IMU device which is working perfectly, except the SPISpeed which is not being altered as it should:
unsigned int m_SPISpeed = 400000;
SPI.begin();
pinMode(m_SPISelect, OUTPUT);
m_SPISettings = SPISettings(m_SPISpeed, MSBFIRST, SPI_MODE0);
...
SPI.beginTransaction(m_SPISettings);
digitalWrite(m_SPISelect, LOW);
SPI.transfer(regAddr | 0x80);

Where m_SPISpeed is 400000. No matter what i set this value to it is always operating at 125000Hz.

What data type is the variable m_SPISpeed?

@RogerRowland, unsigned int

If that's a Uno, then unsigned int is only 2 bytes, so max 65536. Which Arduino?

Try unsigned long m_SPISpeed = 400000L;

Its a Arduino Micro, i have to try again tommorow. But i am afraid that you may be right!

Strange. I tried to change it to unsigned long, but now it is maxing at 250kHz. I tried to type 400000L directly in the settings and this is still the maximum i can reach. Is there another parameter i need to change?

Put another zero in that literal, 4000000L, looking at the source code for the new SPI library, it applies a simple algorithm to get a clock divider, so unless you're spot on with a multiple, you get the next lowest.

As was pointed out in the question comments, your use of unsigned int is the problem. The prototype for SPISettings is:
SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) {

The comments in spi.h say:
// We find the fastest clock that is less than or equal to the
// given clock rate. The clock divider that results in clock_setting
// is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the
// slowest (128 == 2 ^^ 7, so clock_div = 6).

So your SPI speed will be the processor speed divided by 128, which is 16 MHz divided by 128, being 125000 Hz, which is your observed result (since unsigned int cannot possibly hold more than 65535 on this platform).


text:
What is micro C in a circuit diagram?
This is probably a simple question but I am a beginner with these things. What does the micro C part of the circuit diagram mean? The diagram is from the datasheet of the tssp77038 IR receiver. Does it want there to be a capacitor on the output?
(http://www.farnell.com/datasheets/1915248.pdf?_ga=1.234529246.1943069395.1480959857)

If you Google "µC" you reach the page Microcontroller

It means "Micro Controller" - you know it as "Arduino".


text:
Controlling 3 stepper motors simultaneously
I have three stepper motors connected to the drv8825 drivers to an arduino uno.
I am using the example code below (from here), which works fine for moving multiple stepper motors at the same time BUT they all move for the same number of steps and in the same direction. I would like to tweak the code so that all of them move at the same time but each one for a different number of steps and in different directions. The motor with the least steps would probably have to wait for the motor with the most steps to finish its movement before going again.
int dirPin = 8;
int stepperPin = 7;
int bdirPin = 6;
int bstepperPin = 5;

void setup() {
 pinMode(dirPin, OUTPUT);
 pinMode(stepperPin, OUTPUT);
 pinMode(bdirPin, OUTPUT);
 pinMode(bstepperPin, OUTPUT);
}
 void step(boolean dir,int steps){
 digitalWrite(dirPin,dir);
 digitalWrite(bdirPin,dir);
 delay(50);
 for(int i=0;i<steps;i++){
 digitalWrite(stepperPin, HIGH);
 digitalWrite(bstepperPin, HIGH);
 delayMicroseconds(800);
 digitalWrite(stepperPin, LOW);
 digitalWrite(bstepperPin, LOW);
 delayMicroseconds(800);
 }
}
void loop(){
 step(true,1600);
 delay(500);
 step(false,1600*5);
 delay(500);
}

Thank you in advance for your help!

You would first have to provide all the necessary information to your
step() function: direction and number of steps for each motor. Then
you just have to stop the loop at different points for each motor. You
do this by running the loop up to the number of steps of whichever motor
needs to run for longer, and making the steps of each motor conditional
on the loop index, as follows:
void step(boolean dir0, int steps0,
          boolean dir1, int steps1,
          boolean dir2, int steps2) {
    digitalWrite(dir0Pin, dir0);
    digitalWrite(dir1Pin, dir1);
    digitalWrite(dir2Pin, dir2);
    delay(50);
    int max_steps = max(max(steps0, steps1), steps2);
    for (int i = 0; i < max_steps; i++) {
        if (i < steps0) digitalWrite(stepper0Pin, HIGH);
        if (i < steps1) digitalWrite(stepper1Pin, HIGH);
        if (i < steps2) digitalWrite(stepper2Pin, HIGH);
        delayMicroseconds(800);
        if (i < steps0) digitalWrite(stepper0Pin, LOW);
        if (i < steps1) digitalWrite(stepper1Pin, LOW);
        if (i < steps2) digitalWrite(stepper2Pin, LOW);
        delayMicroseconds(800);
    }
}

It would be more elegant to put the data for all the motors in an array,
and you would probably want to do so if you have more than three motors.

I have two ideas:

I don't have personal experience working with the AccelStepper Library, but I believe it implements a class that allows you to work with multiple steppers.
I plan on controlling two steppers for a project of my own (a self-balancing robot implemented with an STM32 processor), and I plan on using hardware timer interrupts to control the speed of my motors. A quick google search shows that a similar approach is possible with Arduino. You can probably use Timer0, as 1ms is fairly fast for a single step. This has several benefits...

The refresh function will run on set intervals, (allowing you to control the speed very precisely.
It will run with the correct timing, even if there is a function in loop() that is taking a long time.

Note: do NOT put any delay statements in your interrupt handlers. If you do this, it will probably prevent other interrupts from occurring and cause some API functions (such as millis or micros) to misbehave. In addition, the execution of anything in loop is halted while the interrupt is being handled, meaning that you would effectively stop everything until the interrupt is done. See the caveat in Arduino reference page for delay.

This is my first ever StackExchange answer, please let me know if there are any ways in which I can improve it.

Hi, welcome to arduino.stackexchange, and thanks for this first, constructive answer! You could improve it by giving an algorithm or prototype code for your second idea: judging from the level of the question, it seems the OP would have a hard time building this on his own. Also, it's worth noting that Timer0 is already used by Arduino core to provide timing functions. Buts since only the TIMER0_OVF_vect ISR is used for that purpose, you can still use TIMER0_COMPA_vect and TIMER0_COMPB_vect for the motors.

I can write some code if I have time. However, it will be untested due to the fact that my Arduino board is broken (although it is probably just the ATMega chip).

You need a struct for each stepper with a timestamp, a position and rate of change and a loop that updates the postion based on rate which is the change in position over some time:
struct stepper {
  unsigned long timestamp;
  int position;
  int rate;
};

// init steppers array

while (keepGoing()) {
  unsigned long now = millis();
  int si;

  delay(10);

  for (si = 0; si < 3; si++) {
    struct stepper *stepper = &steppers[si];

    if (steppers[si].timestamp > now) {
       steppers[si].position += steppers[si].rate;
       steppers[si].timestamp = now + 100;
    }
  }

This is a back-of-a-napkin sketch of course. It is only supposed to illustrate how you can update any number of things concurrently.
The important thing is that you only call delay once. And presumably it would be only a very short delay compared to the unit of time for the rate. In the above example it would adjust the stepper position every 100ms. You would need to experiment with the timing to find a good behavior given the speed of the stepper, speed of the code and maximum permitted rate.
Beware that there is a lot to think about beyond this. For example, you should initialize the timstamps with different timestamps so that the motors are not all running at the same instant and thus try to minimize the total power consumed by the motors at any particular time.
Note that I have never played around with stepper motors but this type of loop is a common programming idiom for handling things concurrently.

Your stepper pointer is a good idea: using it would make the code shorter and easier to read. But you forgot to use it... 2. You should not compare timestamps: this is bound to fail when millis() rolls over. You should compare durations instead.


text:
Arduino processing serial comunication - losing data?
I'm trying to send an array back and forth between Processing and an Arduino UNO. But I think data is being lost along the way. I simply iterate over the array in Processing and send the Values separately. A new set of data is indicated by the character <. On the Arduino the data gets added to a string and sent back for testing.  When I print out the string in processing, some data changed to -1.
The array contains {1,2,3,4,5,6,7,8}
The Output looks like this:
12345678
12345678
1234-1-1-1-1
12345678
12345-1-1-1

Is there something I'm missing in terms of implementation, or is this simply a hardware related problem (like slightly different clock speeds)? Is there any way to improve this?
Arduino Sketch:
int srr[8];

int content; // Data received from the serial port
void setup() {
  Serial.begin(9600); // Start serial communication at 9600 bps
}

 void loop() {
   String str = "val:";
   int test;
   if (Serial.available()){ // If data is available to read,
     content = Serial.read();
   }

   if (content == 60){
     for(int i=0; i<=7; i++)
   {
       str+=Serial.read();
   }
   Serial.println(str);
   }
}

Processing
Serial myPort;  // Create object from Serial class
int arr[]={1,2,3,4,5,6,7,8};  //The array to send

String str;
void setup()
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw() {
  //write
  myPort.write("<");
  for (int i =0; i<=7;i++){
    myPort.write(arr[i]);

  }
  //read
  if ( myPort.available() > 0){  // If data is available,
    str = myPort.readStringUntil('\n');         // read it and store it in val
    println(str); //print it out in the console
  }

}

Ok, let's look at your Arduino program a bit at a time (for that is where the problem lies).
if (Serial.available()) { // If data is available to read,
    content = Serial.read();
}

If there is at least one character available in the buffer then read one character into the variable content.
if (content == 60) {

If the variable content is 60 (better to use '>' so you can see what it is), then ...
 for(int i=0; i<=7; i++) {
     str+=Serial.read();
 }

... read 8 characters from the serial buffer whether there are any characters in there or not.
That last bit is the crunch point.  You have an unknown number of characters in the buffer.  You had at least one, and that one you read into content.  You don't then check to see if there are the required 8 more characters available (or wait in each iteration of the loop for each character to actually arrive) before trying to read that character in.
If you take a moment to read the documentation on Serial Read you will see this:

Returns
the first byte of incoming serial data available (or -1 if no data is available) - int

The simplest fix is just to make your loop blocking so it waits for a character to arrive before reading it:
for(int i=0; i<=7; i++) {
     while (!Serial.available());  // Wait for a character to arrive
     str+=Serial.read();  // Read it
}


text:
Regulator magic smoke
I have accidentally released the magic smoke from the regulator on a digispark board. I did this when I accidentally plugged a circuit into the 5V and the VIn instead of the 5V and Gnd, and then plugged the board into the USB port.
The attiny chip still works - I know because I plugged it in to the USB ,with no circuitry attached, and the uploaded program still runs happily.
My question is, is there any possibility that when the magic smoke was released from the regulator, the attiny was also damaged?
Secondly, is there any harm in leaving the dead regulator on the board? Or am I better off cutting it off?

Better replace the regulator on the board. Cutting or leaving is not the best idea.

Linear voltage regulators have an internal parasitic diode that shorts the output to the input. You have burned out this diode which has destroyed the regulator, but it is highly unlikely that any other components have been damaged. You can get away with cutting away the legs of the regulator, but complete removal will be difficult due to the large size of the tab connection and will likely result in damage to the other components.


text:
Sending a text message through a arduino wifi shield
I am using an Arduino uno and need to send text messages and email messages from the device based on certain events occurring.  I have the logic figured out of when to send the text message or email but don't know what shield I need to send these messages.

Do you know how to send them?

No I don't.  This is all new to me

Figure that part out first.

In today's world, you will realistically need an external service provider for both wifi-to-SMS gatewaying and also simple email as most most recipients' email services will conclude messages arriving directly from stand-alone devices are spam.  You can do small-volume SMS directly with a GSM modem if your plan allows.  But in general you should probably pick the service before you pick the hardware.  Do try to select something that is both secure but does not require extremely heavyweight authenticiation libraries on your embedded device.

So, with a valid connection, could I send an SMS using Twilio? It's an online software that uses python to send SMS. So technically if I had an ethernet connection using a shield, I could send a text using that program correct? *I am using an Arduino Uno by the way.

Sending an email you need a network connection of some form.  Options include:

Ethernet Shield
WiFi Shield
GSM Shield (can be expensive, but will work almost anywhere)

To send a text message you need access to a text message service. That can either be directly through a mobile phone operator or through an on-line SMS gateway service. For an on-line service the options are as above, since it's almost the same as sending an email (in fact, some gateways offer an email-to-SMS gateway option). For direct mobile provider access you can only use a GSM shield.
So really it boils down to how mobile you need it to be, and how much you are willing to spend (both on the initial hardware outlay and service provider fees and charges).

In one of project I had seen recently, they used esp8266 for home automation and used TEMBOO.com to send SMS. I am sorry I can't help u further than this, but i am sure, Google will..
You can also refer this tutorial from adafruit on sending an sms with Temboo
https://learn.adafruit.com/sending-an-sms-with-temboo/

If you are trying to send test messages and emails over INTERNET using ETHERNET or WIFi you might need some REST API. There are two ways to get that part done.

You might create your own REST API that contains some AUTHENTICATION KEYS, USER ID, RECEIVER ID etc for emails and same for test messages.
You can use third part REST API that provides these functionality.

I am attaching some link you for help that will tell you how to send emails and text messages over internet.for emails For Text Messages
NOTE :- Email api might get expired, don't get stuck over it found some other ways or third party API for that.

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


text:
Can't enable face detection on esp32 cam : CORRUPT HEAP: Bad head at 0x3ffe2eb4. Expected 0xabba1234 got 0x00000008 abort()
I was trying to make esp32 face recognition using the esp32 camera web server example in arduino ,
and everything works fine untill i press on face detection the frame is frozen , module restarted and put this error to serial monitor :

CORRUPT HEAP: Bad head at 0x3ffe2eb4. Expected 0xabba1234 got 0x00000008
abort() was called at PC 0x4008a64d on core 1

ELF file SHA256: 0000000000000000

Backtrace: 0x4008df7c:0x3ffe1c30 0x4008e1f5:0x3ffe1c50 0x4008a64d:0x3ffe1c70
0x4008a779:0x3ffe1ca0 0x400f97cb:0x3ffe1cc0 0x400f5a61:0x3ffe1f80 0x400f59f0:0x3ffe1fd0
0x40093545:0x3ffe2000 0x40082976:0x3ffe2020 0x4008a545:0x3ffe2040 0x4000bec7:0x3ffe2060
0x400d1bc9:0x3ffe2080 0x401194f5:0x3ffe2230 0x40119bfd:0x3ffe2260 0x40119cb5:0x3ffe22f0
0x4011a088:0x3ffe2310 0x40118774:0x3ffe2330 0x401187cb:0x3ffe2370 0x4008fe86:0x3ffe2390

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

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1216
ho 0 tail 12 room 4
load:0x40078000,len:10944
load:0x40080400,len:6388
entry 0x400806b4

I tried erasing flash bt it made the same error again
I am using Arduino IDE 1.8.12 , esp32-cam
operating at 5 volts from the programmer (also tried other external power supplies)
and these are the pictures of settings : (also used wrover kit in programming settings with huge app >3mb)
Chip name

ESP32 Cam

FTDI Programmer

AI THINKER

Settings

I want to make a face recognition door lock , if this doesn't work could anyone refer me to how can I get facial recognition on esp32 cam with any other way?

I don't have enough reputation to be able to add a comment, but using the answer from Andrew Hart I was able to resolve this.  For completeness of this thread in case the linked solution ever disappears:
Locate these sections from the app_httpd.cpp:
if (net_boxes){
    detected = true;
    if(recognition_enabled){
        face_id = run_face_recognition(image_matrix, net_boxes);
    }
    draw_face_boxes(image_matrix, net_boxes, face_id);
    free(net_boxes->score);
    free(net_boxes->box);
    free(net_boxes->landmark);
    free(net_boxes);

and
fr_recognize = esp_timer_get_time();
draw_face_boxes(image_matrix, net_boxes, face_id);
free(net_boxes->score);
free(net_boxes->box);
free(net_boxes->landmark);
free(net_boxes);

replace the 4 free's in each block with dl_lib_free.

The above free(...) -> dl_lib_free(...) replacements fixed the issue for me. This was done on the 2.0.0 board version in the Arduino IDE. I was able to revert to 1.0.4 and find myself in a working state, but performance was definitely worse (where 1.5 frames/s being good performance). Don't forget to re-enroll if you shave your beard... Not that I couldn't unlock a cabinet because of this or anything.

Rollback your ESP32 board driver to 1.04. works for me ;-)

Thanks!! this worked for me!!!

I ran into this issue with the same setup. This Github issue seems identical to ours, and applying the fix in this comment quickly resolved it for me: https://github.com/espressif/arduino-esp32/issues/5128#issuecomment-851785970. Good luck!

Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.

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


text:
Passing class member function as argument
I need to pass a class member function to server.on, unfortunately i get an error.

error: no matching function for call to 'ESP8266WebServer::on

I have done some searching but could not understand anything I found. No simple explanation.
This works:
void handleRoot(){}
server.on("/", handleRoot);

This doesn't:
void myClass::handleRoot(){}
void myClass::setup(){
    server.on("/", handleRoot);
}

The second argument to server.on is
typedef std::function<void(void)> THandlerFunction;

Unfortunately I have no idea what it means.

Seems like more of a C++ question than an Arduino question.

@TheDoctor you are probably right but I thought since it is related to arduino IDE someone could have same problem.

It actually has nothing to do with the IDE per se.

@Ignacio Vazquez-Abrams since I use arduino ide to write the code and to upload it to my esp8266 like many others do, it has a lot to do with it. Other people use same library and so they could have run into the same problem. Apart from that I really appreciate your useful comment.

It would happen with any editor, upload tool, or library. It is a language issue.

It's quite common question related to C++ programming.
The extensive explanation can be found here.
The short answer is: it's very different from taking the address of a regular function.
Workarounds (that might or might not work for you, depending on what else you need that function to do) are:

make it static
declare it as friend function, rather than member function

Either way, the point is that it should not be something associated to an instance of the class, but rather to the class as a whole.

Static works. Hope i won't run into another issue by making it static though :) Thanks a lot.

This will get the job done - using anonymous function syntax:
server->on("/", [&]() {
   handleRoot();
});

I've ben hitting this same problem.
Some further research on c++ syntax helped me find this clean solution, based on the
std::bind syntax:
server.on("/", std::bind(&myClass::handleRoot, this));

If you have the Standard Template Library installed, yes.


text:
1x4 Button membrane help
Im trying out this membrane from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?
UPDATE
Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on HIGH. i used Serial.println(digitalRead(one)); to verify that and the output was 1.
int two =  8;
int one = 9;
int four = 10;
int three = 11;

void setup() {
  pinMode(one, INPUT);
  pinMode(two, INPUT);
  pinMode(three, INPUT);
  pinMode(four, INPUT);
  Serial.begin(9600);
}

void loop() {
  if(digitalRead(one) == LOW){
    Serial.println("One");
  }else if(digitalRead(two) == LOW){
    Serial.println("Two");
  }else if(digitalRead(three) == LOW){
    Serial.println("Three");
  }else if(digitalRead(four) == LOW){
    Serial.println("Four");
  }
}

You have the pullups enabled on the 4 pins, right?

Please show your code and wiring.

This is my setup and my code will updated

pinMode(one, INPUT);

You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You must enable the pullup on the pins (and connect the common to ground) if you want correct operation.
 pinMode(one, INPUT_PULLUP);

i was not aware of such a thing, thanks! Im quite new to arduino

authors: Θεοδωρος Πετριδησογλου


text:
Mount arduino metro mini
I'm using an Arduino Metro Mini (for example https://www.adafruit.com/product/2590) in a project, and want to mount it so the micro USB socket is available through a hole in the case.
Is there an easy way to do this? The main difficulty is that the board has to be mounted end-on to the case, which means you need brackets, which also need standoffs since of course neither side of the board is entirely flat; and the screw holes are at the very end, so no space to spare between them and the case. Etc. If that's not clear, glance at the analogous HDMI mount linked below.
Adafruit sells a complete enclosure (https://www.adafruit.com/product/2709), and there's a similar printable one at https://www.thingiverse.com/thing:936519. I could glue that to the case and then put the mini in there. But that seems like overkill.
For some breakout boards Adafruit has a special panel mount (like the HDMI one at https://www.adafruit.com/product/3121) -- but nothing I see there or elsewhere for the metro mini.
Any better solutions out there? Closest i've seen here is Mounting Arduino in an enclosure

are you asking how to mount a device that has 4 holes for screws? ... your question is not really related to the arduino

The USB micro specification includes clearance for mounting through a case. You notice when you plug a cable in there is always a small gap between the socket and the moulded body of the plug. That gap is for the housing of your project. Get a box with a thin enough wall, Cut a hole in it the right shape. Stick / glue / tape / velcro / screw / whatever your board so the socket is behind (and maybe partially inside) the hole you cut. It's not rocket surgery.

What do you mean "neither side of the board is entirely flat"?  Looking at the linked picture of the Arduino Metro Mini it looks to be a perfectly flag rectangular piece of PC board with mounting holes in all 4 corners. Attach a stand-off to every one of those holes, and position the Arduino near the edge of the case so that it's USB connector is barely inside. Measure and cut a hole in the case large enough to insert a USB plug.

i would copy the thingiverse stl object into tinkercad, where i can make a case around it, cutting out parts as needed. you can mount it  "upside-down" on a corner of the case, which lets you press the button with a paper clip. i did just that for nodeMCUs, though eventually i gave up on the imported bracket and make my own with a few cylinders and holes...

What I've done for my projects is to get PC board standoffs of the right height, and use those to mount the board to the bottom of the case.
I measured the height of the USB connector and it's distance from the mounting holes, and calculated where to cut a hole in the side of the case for the USB connector.
I did not look up the USB specification for the depth/clearance of the connector - I just "guesstimated" and it worked fine.


text:
Burned Arduino?
I have an arduino that I programmed a PWM signal on pin 5. When I power the arduino with 12v or USB5v, pin 5 has the PWM signal. Iam checking it with a oscilloscope. Oddly enough the arduino is not recognisable to a windows PC or MAC, the device never shows up on the usb. The LED on the device seem to give all the right signals. The Green ON LED is on. And the L LED is also on. The program is not using serial so the RX and TX are not on.
When I try another Arduino it works fine.
What could I have broke? I am guessing the ATmega328 is fine?

Try reflashing the ATMega16u2 that does the usb-to-serial. Try it using the DFU option. If that fails use another arduino to reflash using ISP (using the ISP header right near the chip in question. If that also fails most the atmega16u2 is probably broken the board is beyond economical repair

Tried that, with no luck. Yeah I am not trying to fix for $$ reason, just trying to understand what went wrong.

with no luck. Could you expand on that. Were you unable to update the firmware, or did it not have any effect.

I was not able to use DFU option because the UNO is not detected by the pc or mac. I tried the ISP option and burned the bootloader, but it still is not detected by the computers.

Did the ISP programmer successfully verify the flashed rom?

Just a guess, if anything else work fine, my (first) guess would be the serial to usb adapter. I damaged one a while ago on a breadboard but also dont know how. But it could also be almost everything else. The pwm sketch, in which language is it written and burned? Does the Atmega have a bootloader on it?

The sketch was really simple, just doing a analogWrite(5, 100);

And how have you load it onto the arduino?

Using the arduino IDE

have you seen any error message inside the status window? would be nice if you tell a bit more..

The only error I see is the it can't find the usbmodem because the computer is not seeing the uno

which port uses the command? have you verified it? you said you have more arduinos right? try to communivate to another one using RX/TX pins.

Not sure what you mean? My other UNO use usb. And yes it is pin 5 sending the signal

that wasnt my question, ive meant the port you connect the arduino to your computer. it should be like COM1 on windows or like /dev/ttyACM0 on linux

Yeah it never shows up on windows or mac.

It also doesn't show up under device manager? Would it be possible for you to boot a linux distro and try it there? Most distros allow outputting detected USB devices and USB related logs so those might help up.


text:
What is the best serial protocol for bidirectional communication with NodeMCU?
Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.
Details:
I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.
I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending <=122 character strings to Arduino and possibly getting a short response.
I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).
My research shows that:

ESP8266 has obvious timing issues, having been designed for a different purpose.
Controlling the ESP8266 from Arduino via hardware serial works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.
The same via SoftwareSerial is unreliable
Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)

I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.
The Arduino already works as an I2C master.
I'm assuming I2C is the way to go, but wanted to ask for opinions first.
[EDIT]
Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 can't do very precise timing, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?

I need it the other way around, too - can you clarify what that means? I'd rather keep the hardware serial ports for programming - maybe, but unplugging two wires every time you need to program isn't that bad, if it makes the whole setup work reliably.

I would suggest my ICSC library - I use it for communication between a NodeMCU and a PIC32 board.  https://github.com/MajenkoLibraries/ICSC

@nick-gammon Controlling the Arduino by sending serial commands from ESP8266. Would be fine if the latter didn't talk so much - errors and boot message... And programming: 2 jumpers are tolerable but won't help when I'm monitoring/debugging the whole setup.

@majenko Useful, so thanks, but I'm not seeing much relevance to the question itself. First arg in constructor is a serial interface, which means the choice I'm asking about had already been made.

I have a page about debugging with I2C and SPI which shows how you can debug if the serial ports are in use for other purposes. I also have pages about I2C and SPI if that helps. I'm not seeing much relevance to the question itself - I don't see a question, frankly.

@nick-gammon Neat, thanks. he question stands, though - speaking ow which, are you playing Jeopardy, or is this really "unclear what is being asked" territory? Sorry. If my next edit does not explain to your satisfaction, please try to put me on the right track.

Most of the posts I have seen about it use serial, so I personally cannot answer your updated question. With luck someone else can.

Majenko's library appears relevant because support for non-UART software serial was recently added ( https://github.com/MajenkoLibraries/ICSC/pull/2/files ), and it was designed for high reliability.

Could you please edit your question to clarify: Do you want to reserve the UART on the Arduino for something else, so you want to communicate using some other pins of the Arduino? Do you want to reserve the UART on the ESP8266 for something else, so you want to communicate using some other pins of the ESP8266? Do you want to reserve both the Arduino UART and the ESP8266 UART, and communicate using other pins?

@david-cary My main reasons not to use hardware UART: 1. ease of debugging, requiring no other hardware of software. 2. NodeMCU sends unsolicited data and I don't know how to ignore or turn it off. 3. I may at some point wish to connect more than 1 duino to the esp.

So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.
In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.
One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.
Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial.  For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin).  When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high.  When the APM detects & processes incoming data as I2C slave, it sets OK2SEND low.  NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low.  APM detects HAVESENT low which completes the handshake.  When APM is ready for another byte, it sets OK2SEND high again.  etc.  Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.
If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above.  The APM could be like a dedicated I2C peripheral, albeit a slow one.

APM uses Wire.onReceive() and onRequest() - works well. Thank you, for reminding me that other kinds of communication can take place aside from i2c - it was a D'OH! moment for me.

Just to clarify, though: I wrote the Arduino was already the i2c MASTER. I only switched it to slave later because afaik NodeMCU can't work as a slave. But I'd really like to keep the Arduino as master so I'd have direct access to the RTC module.

While possibly not "the best", I have found I2C to be sufficient for my needs.
Simple to use, if a bit different conceptually (master-slave).
My tests have shown it to be reliable thus far, zero errors over 20 minutes (sending & receiving 20 bytes each time), as long as there were sufficient pauses between calls.
I am going to make the Arduino switch its i2c master/slave role based on the state of other pins. Master most of the time (to use a DS1307 RTC, etc), switching to slave whenever NodeMCU (which can only work as master) has something to say. Thanks to Zeph for the idea.

Side note: You now that on i2c you can have multiple masters talking to each other?

@offler Yes, I do recall that. Haven't gotten the hang of it, though, especially with NodeMCU. I don't trust examples that make it look easy, got burned too many times.


text:
Stuck on upload
I just bought the SmartEverything FOX Board which is Arduino compatible http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf and simply tried to get started with it.
My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014
I cannot upload sketches on it, when I try, it gets stuck on uploading, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens.
The board does not do anything, tx/rx leds do not flash.
I can access to it with a Windows 7 laptop  (UPDATE: and another UBUNTU laptop) from a friend, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.
When I try to upload, I only get the compiling logs:
Quote
Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes.

I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.
I am connecting directly from my board to my laptop through USB 3.0, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.
I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time.
The IDE sees that my board is connected on /dev/ttyACM0
I tried to run in command line but it gets stuck as well
Quote
/home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0
I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?

Have you added yourself to the dialout group? $ sudo usermod -a -G dialout jcharlet then log out and log in again or reboot.

thank you Majenko for your answer, but I already tried it, and it did not work.

Enable verbose upload log from the IDE's settings.

Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):

This is a known bug of the bootloader.
to fix this U need to download the one i attach in this email with the
  ATMEL-ICE tool. http://www.atmel.com/tools/atatmel-ice.aspx
Copy the attched file under: \Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
  (Linux) C:\Users\\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme
  (Windows)
last follow these three simple step Connect the ATMEL-ICE on the SWD
  J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red
  one)

select on Arduino IDE to connect to ASME via atmel-ice (board menu)
  tool->burn bootloader

Please clarify if your answer indicates a solution to the problem. If so, please accept it by clicking on the "tick" icon next to the answer. This indicates to other users that the answer is useful, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

marked as solved


text:
Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot
I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!
I can't figure out how to parse strings in Arduino like c++/java/python!
I tried this, If the first letter is L, set the next value to left motor, same for R
but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.
Any ideas on what I should do?
EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option
Update: This is how it works now:
L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)

Either collect characters until you have a full string (probably terminated with a newline) or else create a state machine which interprets characters one at a time as they are received, for example first deciding on a mode based on a letter, then doing a multiply-and-add on digits to create a value, and executing on the newline.

:O Good idea! I'll try that tomorrow :) thanks! But I just realized, I also don't need my speed to be so accurate, It can be from 0-9! but anyway that's also good for future stuff and way better than inaccurate speed :)

I'm starting to think my lpc1678 is better for this :) but its too hard to work with :S my board is so huge!

Further to Chris Stratton's comment, you can read about using state machines for processing serial data.

A state machine is the right way to go if you are sending multibyte commands.
However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees?  If not I would consider encoding the dAta into a single byte.  You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.
Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.

For my RC Car its enough! (0-9 speed) but I would love to know about it just for other projects :) But chris and Nick told me how to do so! Thanks :)