text:
Arduino Uno and Arduino Yun software. Which version of the IDE works with both best?
I have been working with Unos and just started working with Yun. I have 1.86 currently installed but the Yun starts up saying to use 1.5.6-r2 Beta IDE. Should I uninstall 1.8.6 and install 1.5.6-r2?
Thanks for your help.
Lisa

Get rid of the Yún. Buy a WeMos or NodeMcu or a Raspberry Pi. Every minute you put into the Yún will turn out to be wasted time.

I'm also learning RaspberryPi and Galileo, along with some tiny ones.

The Galileo had a lot of problems and has been "retired". The Arduino boards with ethernet or wifi chips are okay. Stay away from the boards that have a simple microcontroller and a advanced wifi module. The WeMos can do everything those can do and more. The Raspberry Pi is reliable and fun, it will never disappoint you.

thanks for the advice.  What do you think of WickedNode kits?  and 8266?  useful?  I'm mostly wanting to "SMART"-up my home and security.  I have a ton of sensors.  Today I'm playing with an RF send/receive modules.  This probably isn't good conversation on this thread.  Do you mind if I occasionally ask advice through PM?

StackExchange has no PM. The WeMos is EPS8266. The WickedNode seems too specific, I like more freedom. The RFM96 is a good transceiver, it is used by Adafruit. The RadioHead is a good library, but uses a lot of memory. RadioHead is fine for ARM processors (Arduino Zero, Arduino M0, Arduino Due). If you make something that should last at least 10 years, buy from good companies (they use higher quality components) and try to use the most common and most often used standard modules/boards. Wifi at 2.4GHz is common, therefor the WeMos or NodeMcu is a good choice. The Raspberry Pi is always good.

The Yun startup was written when the normal IDE didn't support the yun, so you had to use a release candidate of a future version.
Those days are long gone.
Always use the latest version of the IDE.


text:
Can someone check my code? My Arduino isn't doing a consistent count cycle
I'm wondering if someone could have a look at my code and let me know if there's something wrong with it. I had the code done for me a while back and did a quick test and it seemed to work. I have now built a pneumatic machine for it to work on, and it's doing some strange things.
The first relay turns on and off a pneumatic solenoid, this is connected to a small pneumatic cylinder, it moves in and out. This cylinder causes a pneumatic feeder to activate and move back and forth also.
The feeder has a proximity sensor attached which lights up when the feeder is in its resting position.
The solenoid turns on for approx half a second and then back off again, this pushes the small cylinder out then back in. This sends the feeder forward, it then turns around and comes back toward its resting position.
The Arduino waits for the signal from the proximity sensor to tell it that the feeder is back in its resting position before doing it again.
It then repeats this sub cycle about 20 times.
After 20 sub cycles, the Arduino turns on the second relay for about a second, before turning it back off again.
It then does this whole complete cycle 20 times before stopping.
There's a momentary switch as well, which when pushed, is supposed to restart everything again.
It almost works, the closest i have had is where it was doing the cycles but counting them wrong. i changed the subcycle to 16 instead of 20 and it would count somewhere between 10 and 16. it seems to count different each time.
I just bought a new board and tried again, but now it counts to about five subcycles and then jumps the gun and doesn't wait for the signal from the proximity sensor before doing the next sub cycle. So once again the count ends up wrong.
Any ideas what I could try?
int Relay_1 = 10;           //first Relay
int Relay_2 = 11;           //second Relay
int Prox_Input = 12;        //input signal from proximity sensor
int Switch_Input = 13;      //the switch

int Cycle_Number = 20;      //number of repeating number of "complete" cycle
int Sub_Cycle_Number = 20;  //number of repeating number of "sub" cycle
int Delay_Cycle = 1000;     //delay of the "Complete" Cycle in milleseconds
int Delay_Sub_Cycle = 500;  //delay of the "Sub" Cycle  in milliseconds

bool Button_Pushed = true ; //the state required for the button
int i, j;

void setup() {
  /*configurate the output relays to be begin "low"*/
  pinMode(Relay_1 , OUTPUT);
  digitalWrite(Relay_1, LOW);

  pinMode(Relay_2 , OUTPUT);
  digitalWrite(Relay_2 , LOW);
  /*===========================================================*/
  /*configurate the input switch and sensor*/
  pinMode(Prox_Input , INPUT);
  pinMode(Switch_Input , INPUT_PULLUP);
  /*===========================================================*/
  /*configurate Serial port if you want it*/
  Serial.begin(9600);
  /*===========================================================*/
}

void loop() {
  if (Check_Button() == Button_Pushed) { //check the button
    for (i = 1 ; i <= Cycle_Number ; i++) { //the loop of the "complete" Cycle
      for (j = 1 ; j <= Sub_Cycle_Number ; j++) { //the loop of the "sub" Cycle
        digitalWrite(Relay_1 , HIGH);
        delay(Delay_Sub_Cycle);
        digitalWrite(Relay_1 , LOW);
        while (digitalRead(Prox_Input) == HIGH) {} // waiting the sensor signal
      }
      digitalWrite(Relay_2 , HIGH);
      delay(Delay_Sub_Cycle);
      digitalWrite(Relay_2 , LOW);
      delay(Delay_Cycle);
    }
  }
}

bool Check_Button()  {
  int Reading_1;
  int Reading_2;

  Reading_1 = digitalRead(Switch_Input);
  delay(20);
  Reading_2 = digitalRead(Switch_Input);
  if ((Reading_1 == 1) && (Reading_2 == 1))
    return true;
  else
    return false;
}

please be specific about the problem. try adding some delay in your sub cycle loop.

6V isn’t really enough to put on that barrel jack.  You really need at least 7.5V because of the voltage drop across the regulator.  If you want to use 6V battery then get a switching regulator to make 5V and feed it into the 5V pin instead.

Your fuzzy picture is missing a lot of critical information that would normally be on a schematic. Links to technical information on all the hardware devices would help, azon links are normally sales info and are useless for technical information. I agree with using Vin because of the extra filtering but you need to supply it with at 7.5 or more volts as mentioned by Delta_G If I were to take a SWAG you either have input bounce and/or power supply instability and or failure.

The only reason it might "jump the gun" would be this line:

         while(digitalRead(Prox_Input) == HIGH){}          // waiting the sensor signal

I suggest you check for a transition, that is, make sure the proximity switch has become LOW, and then wait for it to become HIGH again. So for example, if sending HIGH to the relay should make the proximity sensor read LOW, then put a loop in to make sure it does that, before proceeding.

source: Stack Exchange

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

sort: votes


text:
What is corrrect the way to find roll, pitch, yaw?
I have an MPU9250. I have calculated accelerometer, gyroscope, magnetometer. But I want to know how to caclulate roll yaw pitch. I have searched on Google. I found many answer
roll  =  (atan2(-Accel_Y, Accel_Z)*180.0)/M_PI;
pitch =  (atan2(Accel_X sqrt(Accel_Y*Accel_Y + Accel_Y*Accel_Y))*180.0)/M_PI;

source: https://theccontinuum.com/2012/09/24/arduino-imu-pitch-roll-from-accelerometer/
   accelerationX = (signed int)(((signed int)rawData_X) * 3.9);
   accelerationY = (signed int)(((signed int)rawData_Y) * 3.9);
   accelerationZ = (signed int)(((signed int)rawData_Z) * 3.9);
   pitch = 180 * atan (accelerationX/sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/M_PI;
   roll = 180 * atan (accelerationY/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;
   yaw = 180 * atan (accelerationZ/sqrt(accelerationX*accelerationX + accelerationZ*accelerationZ))/M_PI;

source:  https://engineering.stackexchange.com/questions/3348/calculating-pitch-yaw-and-roll-from-mag-acc-and-gyro-data
  Accroll = atan2( accy / (accy^2 + accz^2) )
  Accpitch = atan2( accx / (accx^2 + accz^2) )

source: http://franciscoraulortega.com/pubs/Algo3DFusionsMems.pdf
 Accroll = atan2(accy, accz)
 Accpitch = atan2( -accx, sqrt(accy^2 + accz^2) )

source:https://www.nxp.com/docs/en/application-note/AN3461.pdf
What is the correct way to find roll yaw pitch?

The accelerometer is noisy and the gyro drifts and only the magnetometer knows the direction. The correct way is a filter that uses all sensors combined, sometimes called: sensor fusion. For example the ahrs filter. See the mpu-9250 and ahrs at sparkfun: https://learn.sparkfun.com/tutorials/mpu-9250-hookup-guide

Before everyone makes this problem complicated, the first thing to figure out is if the device is moving and/or changing orientation. If it is not, the problem is a lot simpler and many of the things being suggested are unnecessary.

For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.
Likely this is why accelerometers are used in conjunction with gyroscopes.
Refer to this NXP (aka Motorola, Freescale & Qualcomm) document for an in depth discussion regarding the necessary math.  Note the section regarding "Regions of Instability".
Also, refer to this class and this class from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.
(Added Later)
The rutgers.edu links don't appear to work anymore and this link has been suggested as an alternative.

The links to the rutgers.edu class pdf file doesn't work anymore. Seems that https://aatishb.com/materials/srr/materials.html is the new homepage.

Thanks @MartinMeixger, I've added your new link.

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


text:
Newbie - What is the Difference Between Power Supply's GND and Arduino's GND?
I am new to electronics and Arduino.
What is the difference between power supply ground and Arduino's ground. If I connect my LED cathode to power ground, it doesn't work. But if I connect it to Arduino ground, it works. Aren't all ground the same?
Please see picture below.

Could the power supply / ground bus on your breadboard be split? One difference that I see is that the LED ground to the power supply is more than half way down the breadboard. I've got some that are split in the middle.

dlu, you are right! The breadboard was split in half. Silly me.

I'll bet it never fools you again! You're certainly not the first person to wonder about this…

I had long forgotten about the split in the breadboard power rails. Even when @dlu mentioned it, I thought, that couldn't be it. But then when memory serves, my breadboard have little connectors between the two rails top and bottom. I kinda see the benefit of it, but I would expect the power rail indicator lines to be split (I noticed my boards are). ie, the blue and red lines on the outer edge of the breadboard, are they continuous from one end to the other (as in your diagrams above) or are they themselves broken in the middle? As is mentioned, that won't trip you up again :)

I would expect there to be no difference between the grounds in your circuit, and after looking over the schematic for the board, it appears that all of the grounds are common.
I think the most likely explanation for what you're seeing is a quirk in the breadboard. It may be that the side busses are split at the middle of the board, or perhaps there was just a bad connection somewhere on the ground bus on that side of the board.
One way you could troubleshoot it further would be by jumping the ground side of the LED to the power supply ground. Start with the ground on the regulator and then work out until you find the spot where you loose continuity.

I agree with the other answers.  On rare occasions, TO-xxx packages have bizarre pinouts, but the 78xx series does, in fact, have ground on the middle terminal.  This is surely a split power supply in your breadboard power busses, or else a bad breadboard.  Many breadboards have splits in the power rails halfway down.  I've also seen some with splits more often than that, perhaps as much as disconnects every 5 (or 5 pairs of) contacts.  I have a breadboard, for example, which allows for 6 different voltages, all in a single line, from various connections to a battery pack.  I'd recommend buzzing the breadboard before starting to use it.
I've also had breadboards whose contacts fail after using larger AWG wires in particular holes (or forcing odd connections, such as machined contacts on IC's or sockets, or larger stamped rectangular pins on a TO package such as this) into breadboard holes. The last thing you want to worry about when building a prototype of a new design is whether or not the wiring under the breadboard works.
Many multimeters have a continuity test capability for diagnosing problems such as these, BUT make sure no power is connected (or you could damage the meter on this setting).

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


text:
Arduino to send sms one time only when a button is pressed
The LED_UPDATE() is called in my loop() function, I implemented it (tried anyways),
to send sms as shown in the code such that  only one sms is sent , because as the loop() keeps calling LED_UPDATE(), it's going to keep sending an sms every time (yep you guessed it, very bad for credit :o )
any tips on how I can get around this or what i'm doing wrong in my code would be much appreciated.
p.s. nearly left my mobile phone in the code lol
void LED_UPDATE(int state)
{

int count; // initialized to zero, once program runs it automatically enter state ==1
if (state == 1)
{

    digitalWrite(RED_PIN, LOW);
    digitalWrite(GREEN_PIN, HIGH);
    count=0;
}
else if (state == 2)
{
  count+=1;
  Red_Blink();

  if(count == 1 )
  {
    sms.SendSMS("086XXXXXXX", "PANIC BUTTON PRESSED, Subject needs help!!!");
  }

}

Can you please add the code to sms.SendSMS(string phoneno,string msg)

You are resetting count every time you enter the function.
static int count; // initialized to zero, once.

Adding the static statement should initialise the variable once and preserve its value between calls.

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


text:
Reset Arduino Uno R3 from Serial when it freezes (stops looping)?
I have an Uno that loops processing serial commands and reading from a DHT11 sensor. For whatever reason, the device often stops responding. I put an LED on a pin and gave it a blink to see whether the loop is running, and sure enough the loop() stops running (the LED stays ON or OFF, depending on when it froze). I enabled the watchdog at 2 seconds, but it does not reset the device [it still stays frozen, even though wdt_reset() is called at basically the same time as the blinking LED is toggled].
I then tried various combinations of BaudRate=1200 (or 9600), Open(), Close(), DtrEnable=true [on both the Uno and the Mega], yet none of the combinations would make the device reset. The device will reset, however, if I re-upload the sketch using the Arduino IDE. I would like to emulate this resetting functionality from my own program's code. Reading on the official site, it sounds like the Baud=1200 reset feature is available only on certain models (not the Uno or Mega).
My code is by no means simple as I am no beginner when it comes to programming. This is the first time, however, that I have had a finicky unit that freezes all the time (say between 10 minutes and 2 hours into running). I merely want to reset the unit from the PC using code, like the Arduino IDE does. On the other hand, if the watchdog worked correctly, that would be fine as well. At the same time, I am not that experienced with electronic circuits, so making a circuit that would "press" the "reset" pin when the LED stops blinking is not something I am quite ready to do. Plus, I do not want to add a bunch more components if the job can be done through code.
On a side note, the Serial connection appears to be fully functional the whole time. The LED on the unit that indicates receiving from the PC continues to function whenever I send data to the device. I can connect and reconnect without any apparent issues. Plus, the Arduino IDE has no problem uploading new sketches and resetting the device. Naturally, no data is received from the device after it freezes (until it gets reset, of course).
Update 1: I made a simple sketch (see below) that would run for about 20 seconds and then let the WDT watchdog timeout do its thing. Result:
(a) Running the code on an Arduino-brand Mega 2560, the device simply resets every 20 seconds and keeps blinking;
(b) Running the code on a generic (made in China) Uno R3, at timeout the L light turns on and the device becomes completely unresponsive (not even the reset button or the Arduino IDE can save it); It must be unplugged to reset it.
(c) Running the code on an Arduino-brand Uno R3 works as expected, just like on the Mega 2560.
#include <avr/wdt.h>
void setup() {
  wdt_reset();
  wdt_enable(WDTO_2S);
  wdt_reset();
  pinMode(A5, OUTPUT);
  delay(1);
  Serial.begin(125000);
}
unsigned int LoopCount = 0;
bool TestLED = false;
void loop() {
  if(LoopCount % 300 == 0){
    TestLED = !TestLED;
    digitalWrite(A5, TestLED ? HIGH:LOW);
    if(LoopCount < 20000)
      wdt_reset();
  }
  delayMicroseconds(1000);
  LoopCount++;
}

Nevertheless, I still would like if someone could provide a solution in terms of resetting a frozen generic Uno from Serial in .NET code -- not the WDT frozen, but the normal frozen (of unknown origin). I may be the one coding, but I'm unfortunately not the one deciding which units are put into production.
Update 2: I switched the EasyDriver to its own power source, where the only things in common with the stepper and the Arduino were the ground and the two signal wires. The generic Uno board ended up being even more problematic, going into a new freeze mode (after just a minute or two, pretty reliably) where the L light would blink very quickly. I'm not sure whether it had anything to do with toggling of the DtrEnable property, but I decided to stop messing with the generic board for the time being. The name-brand Uno appeared to freeze occasionally or malfunction as well with the original wiring, but the Watchdog did its thing and reset it straight away every time. Also, I tried toggling the RtsEnable property with the generic board, but it didn't seem to make a difference. The board would become unresponsive and unrevivable, even from the Arduino IDE.
Some more background: The reliability problem only really started to surface when I hooked up the DHT11 temperature sensor, even though the freezing would tend to happen only when the stepper motor was running. I have the DHT11 hooked up exactly as advocated by Adafruit, and it tends to read correctly most of the time.
Update 3: I was thinking maybe the SainSmart Mega2560 would be different from the no-name generic I was using. After getting one and hooking it up, I have found it to have the exact same problem. The SainSmart CPU crashes between 5 and 15 minutes into running. The serial chip (or module) keeps going as you can still see the serial lights change when you send to it. However, the on-board reset button does nothing, and the Arduino IDE cannot upload to the device or reset it. Only a power cycle can save it.

Uno resets whenever a serial connection is established (which is how the IDE is able to reset it to re-upload your sketch). Disconnect/reconnecting your serial terminal should cause the same reset. It's very strange that the WDT doesn't reset it, though.

Agree with @JRobert - I've never seen a case where the WDT didn't reset the chip except when the chip was permanently fryed. Are you sure you are correctly enabling the WDT and not setting it to interrupt only mode? Posting code would help.
The Arduino IDE resets the board by toggling the DTR line on the serial connection. This in turn pulls the RESET pin on the chip low long enough to reset the chip. But if the chip if can reset via the RESET pin, then it almost certainly should also reset on a WDT timeout.

I probably ought to have mentioned that by serial, I meant USB / virtual serial port. Maybe I was mistaking, but I thought the same software commands that work via a conventional serial connection would also work through USB.

@bigjosh -- the chip still works. I've had it freeze several times. It doesn't freeze when it's just sitting there blinking. It's when I run a stepper motor for a while (like 20 minutes). There's a possibility that it's electrical in nature, which may mean that the CPU is crashing, but nevertheless the Arduino IDE can reset the device when it freezes like this. When you say "toggling the DTR", what do you mean from a coding perspective? I'm currently working with the SerialPort class in .NET. I'll see if I can reset the device under a non-crash condition using the WDT.

Try the .NET SerialPort.DtrEnable Property to toggle the DTR.

Stepper motors crash lots of Arduinos! They make lots of inductive noise and pull lots of power. Try connecting the motors and the motor drivers to a completely different power supply that the arduino. Also try filtering any communications lines between the Arduino and the motor drivers. But even though the crashing is caused by motor induced glitches, the WDT should still bring it back to life. Post your WDT enabling code and we will take a look.

Yeah, the SerialPort.DtrEnable property is exactly what I was playing with. I tried setting it before and after opening the port. I tried having a one second delay and having none between turning the property On and then Off (true and then false). I didn't try anything crazy though, like toggling it back and forth a bunch of times. Maybe it's the generic Uno acting up, or maybe there's something tricky about doing it from .NET. As for steppers, I'm using an EasyDriver, but indeed the motor is running on the same power as the Arduino. I've posted an update on my main question.

You really need to understand and fix the root cause, be it software or electrical issues.  It is possible you need to drive RTS rather than DTR to reset this particular board (the IDE may drive both).  It is also possible that an electrical fault or merely noise is causing the USB chip to be re-enumerated and re-opening the serial port is a key part of getting it talking again.

@Chris -- I used to think like that, but then I came to see that it's a very good idea to have systems be fault-tolerant. Trying to prevent every type of problem is often too costly (both in time and equipment) for basic (non-critical) applications. I would actually rather make a system successfully fault-tolerant first and then focus on getting the glitches out. From what I've heard, Google also chose this approach with their search system's network (cheap parts, high fault-tolerance). I agree that finding the problems is well and good, but I think that fault-tolerance should come first.

@Michael - recovery mechanisms are great, as long as you disable them when testing in order to find out if you have a problem.  This system has known flaws likely due to basic design oversights, and those really need to be fixed, not hidden.

You can reset the Uno over the serial link by toggling the DTR line. How you do that depends on what platform and language you are using. There is a capacitor between the line and the reset pin, so the toggle must last a minimum ammount of time. 0.5 seconds works.
This is ok for just a quick fix hack, but probably better in the long run to (1) figure out why the code is crashing, and/or (2) figure out why WDT is not working.

I just tried it, and indeed, simply doing [(1) SerialPort.DtrEnable = true; (2) Sleep(1000); (3) SerialPort.DtrEnable = false;] is enough to make it restart an official Arduino Uno R3 via .NET code. I guess the problem is that this particular generic version doesn't respond the same as the name-brand edition. Presumably this is a feature that sometimes doesn't get tested. At the same time, I haven't had the official one freeze yet in this setup, so I cannot say whether it would reset the same after freezing.

Since we don't know the nature of the freeze-up, and the clone-board behaves differently than an Arduino-brand board but we don't know how or why, there's not much more we can offer beyond suggesting you recommend a higher quality board to your management. You surely have reason enough to do so.
The last remaining thing I can think of, and it's kludgey work-around (shame on me) is:
You know the board will come back after a power-cycle. Kludge up a 555 timer circuit that powers-down the board for a second or two, and trigger it from the DTR line. This is really a broken fix for a broken board!
If my management or a client was intent on shipping a product built with these, I'd have to speak up about potential damage to the company's reputation - and possible liability, if a failure could have real consequences someone - and if necessary, write my objections to the next three levels above me. This board should not be shipped in a product.

Agreed. I did actually pass on the suggestion that the board probably isn't appropriate for this application. Thanks for the extra input.


text:
Will enabling parity bit actually decrease corruption?
I have an Arduino Mega communicating with a Bluetooth adapter through one of the auxiliary hardware serial ports. It works, but there appears to be a corruption rate of approximately 1 in 200 small packets. In other words, about 0.5% of the packets are being corrupted, it seems. I have the option of configuring the serial mode on both ends. While I cannot decrease the baud rate for bandwidth reasons, I do have enough room to enable parity or a larger stop bit if that would help.
Granted the corruption is on the serial line and not on the Bluetooth, if I enable parity, will this actually decrease the corruption rate? Or will the corrupt bytes simply be dropped without being re-sent? In other words, what happens when the hardware detects a bad byte?

"Granted the corruption is on the serial line" in the somewhat unlikely case that is actually true, you have fundamental problems in your system which you should be trying to solve.  With no information about the nature of the "corruption", we can't even rule out a programming mistake (not uncommon when juggling multiple serial devices) at this point.  Understanding exactly how the actual data differs from the expected may be a key guide to what is actually wrong.

You seem to be detecting corruption. How are you detecting corruption?

The Bluetooth protocol for serial communication has several encoding layers to avoid corruption. You might have a race condition in your code that is giving this. What does the ISR load look like? What baudrate and message frequency? And what is the communication "environment"; distance, electronics, wifi, etc.

You could consider adding Hamming code. This will double the message size but you can get 1 bit error correction and 2-bit error detection.

@ChrisStratton, I have only one serial interface enabled on the Arduino.

@slebetman, I am detecting corruption by receiving ping responses with bad nonce values.

@MikaelPatel, I am using Bluetooth BLE. The underlying virtual serial link is completely abstracted from the PC. There is no COM port like there would be with the older Bluetooth devices. There is only a "characteristic" to be consumed. Baud rate is 115200. Frequency is about twice per second. Used baud is currently about 10,000 (while testing). Distance is about 2 meters. There is no WIFI involved or nearby. The CPU load of the Arduino should be low. The PC program takes like 3% CPU. Bandwidth is more important than accuracy.

Parity doesn't, and was never intended to, decrease corruption.
All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.
Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.
When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).
Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.
Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.
An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).
All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.

My packets are actually quite small. The largest one is around 18 bytes. The ones in question are something like 7 bytes. I have not looked into the corruption closely enough to know what type of corruption it is. I do not know, for example, whether there is a missing or extra byte, or whether one or more bytes are corrupted. My protocol was designed around corruption from the start, so it is not a big deal. I just wanted to know whether parity would help. I actually come from the network world, so that side of things I know very well. The electrical stuff is where I have limited experience.

By not looking into the nature of the corruption, you are wasting everyones time as we cannot tell you if parity would help. Voting to close.

@ChrisStratton, Wasting everyone's time? I think not. This discussion about parity is important. You seem to be assuming the problem is not in the serial. Whether or not the problem in my case is in the serial is completely irrelevant to the hypothetical case that it is. I am not asking others to solve my problem. I was simply asking whether parity or a longer stop bit would decrease corruption caused by a low quality serial connection. The answers so far are quite educational for many people. SE is not just about solving the OP's problem.

Your question cannot be answered without knowing if you are getting altered characters or missing ones.  Note that substituted is not the same as altered.  Questions insufficienctly specific to be answerable are off topic here - this is not a discussion forum.

@ChrisStratton, I agree that my particular case would require more information to give a definitive answer, but the hypothetical question about parity can, and seems to have been, answered as-is. If it matters to you, my data so far suggests that specific bytes are being corrupted, hence the bad nonce values on otherwise successfully returning ping responses. Perhaps I will do further testing later, but so far I feel the answers here have been helpful and informative.

Parity by itself does not reduce the error rate, it is used to detect errors. It is up to higher level protocols to determine what to do when the error is detected.
To answer your question about stop bits, going to two might help. The extra stop bit adds a 1-bit-time gap between characters and gives the receiver a little more time to sync up with the transmitter. If the baud rates are a little off between the sender and receiver, it would make it more likely that errors would be limited to one character rather than a whole string of them. That said, the 2 stop bit option is mostly a relic from the days of mechanical Teletype machines. These days it is usually better to make sure both clocks are at the correct frequency.
Have you determined where the errors are occurring - in the serial connection between the Mega and the BT adapter, in the BT link itself, or at the other end? With short wires, correct baud rates (check for the correct clock frequency), a good ground, and correct logic voltages, the raw error rate in the serial connection should be extremely low. I would focus on finding the source of the errors before trying to correct them.

If this is true that parity itself is only for indication, then I can understand why it is often disabled by default these days. I would rather use a hash to check for data integrity than a single bit anyway. I guess parity is just a vestige of the olden days. As for the source of the errors, I have no idea. I am relatively new to serial, and I am very new to programming for Bluetooth (BLE). The wires are indeed short, and the ground is definitely good. The voltage may be a little off, but that may not be worth messing with since the Mega likes 5V and there are other pins using 5V input.

The thing is, I actually started with software serial, which was giving me a packet corruption rate of around 20% (only barely affected by baud rate). Now that the corruption rate is more like 0.5% by using hardware serial, I am pretty happy with it overall. I just wanted to make sure I was not missing any tricks to make it extra clean.

@Michael - that strongly suggests that what you actually have is a mistake in your program.

@Michael if you're doing bitbanging serial ("bitbanging" => just setting & clearing bits at the right time), then you need to have very accurate timing. One common issue is sending a bit, then setting a timer for when to start the next bit - your clock will drift by the amount of time it takes to set the pin high or load plus the time it takes to set the next alarm, plus overhead. Hardware is always better.

I am guessing that the problem is that your clock is not 100% divisable to produce exactly 115200. If so it makes sense that communication sometimes fail.
See this question for more details, in particular
the link to WormFood's AVR Baud Rate Calculator.

That is very interesting actually. According to WormFood (which I had actually referenced in my initial implementation over USB virtual serial), 76800 would be an ideal high baud rate for a 16MHz CPU. Unfortunately, the HM-10 Bluetooth controller does not have any options between 57600 and 115200. When I used USB, I had the baud at 125000 (16MHz divided by 128), which seemed to work very well.

Parity checking will only let your code detect a corrupted byte, and not very well at that. Assuming your primary goal is to get packets transferred reliably, you'd be better off to add a checksum to each packet sent, testing the checksum when the packet is received, and asking the transmitter to re-send a failed packet. Since you only expect 1 packet in 200 to be retransmitted, your bandwidth shouldn't take a big hit.


text:
Can I use 5V 1A Adapter to power Arduino UNO?
I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).
My question is can use any of these to power my Arduino UNO with a barrel connector?
What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.

You can use a clean 5v supply through the USB connector, but not through the barrel jack.  The 12v supply would probably work (if it is DC) through the barrel jack but the regulator may get hot - something around 8v is better there.

An Arduino will not consume 1A of current, far from it, it will use less than 0.1 A of current even with a couple of LEDs lighting up. So don't worry about the current rating of the adapters, it is OK. The Arduino will only take as much current as it needs.

I'm guessing your other adapter is 500mA, not 500A.

As I mentioned 5V adapter is actually a LG mobile charger - Do I assume that it can supply clean 5V? How do I know it is clean 5V or not? I measured it gives 5.0V  @ChrisStratton


text:
Arduino UNO inconsistent I2C register reading from ArduCam
I have an Arducam hooked up to an Arduino UNO.  The code I am running looks like this:
#include <Wire.h>
#include <ArduCAM.h>
#include <SPI.h>
#include "memorysaver.h"

const int CS = 10;

ArduCAM myCAM(OV5642, CS);

void setup() {
  uint8_t vid, pid;

  Wire.begin();
  Serial.begin(115200);
  pinMode(CS, OUTPUT);

  SPI.begin();

  //Check if the camera module type is OV5642
  myCAM.rdSensorReg16_8(OV5642_CHIPID_HIGH, &vid);
  myCAM.rdSensorReg16_8(OV5642_CHIPID_LOW, &pid);

  if ((vid != 0x56) || (pid != 0x42))
    Serial.println("Can't find OV5642 module!");
  else
    Serial.println("OV5642 detected.");

...

and the rdSensorReg16_8 function from the library:
//I2C Write 8bit address, 16bit data
byte ArduCAM::wrSensorReg8_16(int regID, int regDat)
{
    Wire.beginTransmission(sensor_addr >> 1);
    Wire.write(regID & 0x00FF);

    Wire.write(regDat >> 8);            // sends data byte, MSB first
    Wire.write(regDat & 0x00FF);

    if(Wire.endTransmission())
    {
        return 0;
    }

    delay(1);
    return(1);
}

The problem I am experiencing is that sometimes I will receive the "Can't find OV5642 module!" message, and other times everything is fine and I receive "OV5642 detected" (I have the OV5642 module hooked up, so it should always be returning detected).
I have tried using different cables to connect the camera to my UNO.  I have tried swapping out my USB cable.  I have tried using a 12v wall adapter to power the UNO. None of these options permanently solved my problem - I still receive both messages interchangeably.
One thing that seems like it is adding consistency is when I change which USB port on my computer the cable is plugged into.  Every time I switch the USB port I am using, it seems like for the first run I'll receive the successful "OV5642 detected" message, but after reseting the Arduino or re-uploading my sketch, I go back to the "Can't find OV5642 module!" message.
Can anyone help me troubleshoot why I am getting inconsistent readings?  Thank you.

Same problem here. It seems like if you reset the camera (plug it out and in again) it works again. I don't know why, I also tried it with a Raspberry Pi, and I didn't have this problem (however I had other problems!).

I would start by adding a short delay before SPI.begin() and verifying that the power drawn does not exceed 500 mA.
The product description describes the power on sequence. OV5642

Thanks for the suggestion Mikael.  I added a delay and verified the power, but I am still experiencing the same issues.

Ok. Let us assume a hardware issue. Pull-up resistors on I2C wires? Might be integrated on the board. How are you connecting the device? Did you measure the power drawn? How much was it? Did the voltage drop?

Have you tried decoupling the power pins on the module? Just attach a 100uF or larger capacitor to the GND and power pins on the module.


text:
How to prevent Wire.requestFrom from hanging?
I'm trying to read data from an Arduino Uno I2C slave via Wire.requestFrom() on an Arduino Uno master. The slave's onRequest handler is simply:

void I2C_Send()
{

  byte myArray[4];

  myArray[0] = lowByte(acount);
  myArray[1] = highByte(acount);
  myArray[2] = lowByte(bcount);
  myArray[3] = highByte(bcount);

  Wire.write(myArray, 4);

}

It seems to work fine for a few iterations, but eventually something happens and the master's requestFrom() call hangs indefinitely. What's causing this and how do I prevent it?
I've tried setting various levels of timeout with Wire.setTimeout(x); but that has no effect.

You are using pull-up resistors and connected ground correctly? How long wires? Might have too large capacitive load and need to reduce the I2C clock frequency. Check the signals with a logic analyzer.

Can you post the master's code?

Did you find an answer...?


text:
Why can't this C++ program read my arduino's Serial.write()?
I made a super simple arduino uno sketch to send a serial byte once every second:
void setup(){
  Serial.begin(9600);
}

void loop(){
   Serial.write(12); // send a byte with the value 12
   delay(1000);
}

My arduino is hooked up to com 3.
On the other end of the line, I have a C++ program with the following read function:
int Serial::ReadData(char *buffer, unsigned int nbChar)
{
    //Number of bytes we'll have read
    DWORD bytesRead;
    //Number of bytes we'll really ask to read
    unsigned int toRead;

    //Use the ClearCommError function to get status info on the Serial port
    ClearCommError(this->hSerial, &this->errors, &this->status);

    //Check if there is something to read
    if(this->status.cbInQue>0)
    {
        //If there is we check if there is enough data to read the required number
        //of characters, if not we'll read only the available characters to prevent
        //locking of the application.
        if(this->status.cbInQue>nbChar)
        {
            toRead = nbChar;
        }
        else
        {
            toRead = this->status.cbInQue;
        }

        //Try to read the require number of chars, and return the number of read bytes on success
        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
        {
            return bytesRead;
        }

    }

    //If nothing has been read, or that an error was detected return -1
    return -1;

}

This seems to check only one time if data is available, so obviously I have to loop through it until data comes in.  I did that in my main program:
#include "Serial.h"
#include <iostream>

using namespace std;

int main(void)
{
    Serial serial("COM3");

    char* c = "";
    int len = strlen(c);
    while(c == "")
    {
        serial.ReadData(c, len);
    }

    cout << "\n\n";
    system("PAUSE");
}

When I do this, my C++ program gets stuck in an infinite loop waiting for data from the arduino, and I cannot figure out why this is happening.  My program never sees the data the arduino is sending.
This Serial class works and is configured properly because I can SEND all the data I want to the arduino without any problems.  My issues are only with reading back from the arduino.
Can someone please help me figure out why this is not working?

Welcome to Arduino SE! Have you verified the Arduino code outputs the right data with the serial monitor? If so, I think this question should be migrated to another site to address the C++ code. Thanks!

Can you also confirm that the receiver program works if you send some "correct" data with a terminal program? The answers to those two questions will tell you whether to look at the Arduino, the receiving CPU, or the serial line.

I want to send keypad data from Arduino to Code Composer Studio or CCS and i'm using Texas instruments (TMS320F8069). When I send the data, I hope that CCS will show the Arduino data that i already send. And the CCS will send it back. It's like a TR > RX program. But, it's not work. I mean the CCS console (serial monitor) doesn't show the data. So, can you guys help me solve this problem? Here my CCS code... const int LEN = 1; char msgg[LEN + 1]; int numBytes = 0; for(;;) { msgg [numBytes] = 0; scia_msg(msg); // Wait for inc character while(SciaRegs.SCIFFRX.bit.RXFFST !=1) { } // wait for XRDY

The problem is in your C++ program at the other end of the line (not the Arduino side):
char* c = "";
int len = strlen(c);
while(c == "")
{
    serial.ReadData(c, len);
}

Here, len is zero because that is the length of "" , the empty string! Thus, in your loop, you ask ReadData to read 0 bytes. Hence, the condition of your while loop is always true as, c never changes.
Also, the while condition seems incorrect as it is not recommended in C++ to compare 2 strings (defines as char * or char [...]) with ==. In your situation, what is important is the number of characters read by ReadData:
char c[LEN + 1];
int numBytes = 0;
while(true)
{
    numBytes = serial.ReadData(c, LEN);
    if (numBytes != -1)
    {
        // Terminate the string if we want to use c variable as a string
        c[numBytes] = 0;
        break;
    }
}

in the code above, LEN is the number of characters you want to read at one time, in you example it should be set to 1, either as a #define or as a const variable:
// either:
#define LEN 1
// or:
const int LEN = 1;

The code above also ensures that c can be used as a normal string, by adding a 0 at the end. This is mandatory only if you want to use string functions on c such as strlen, strcpy, strchr... otherwise numBytes is enough to manage the number of characters read into c.

char* c = "";
while(c == "")

The variable named c is a misnomer, because it is a pointer to a string, not a character.
For example c = 0x123456.
You should use a more explicit name for your variable.
This first line assigns a pointer to an empty string to the c pointer.
So, the value stored at address 0x123456 == whatever pointer to a static memory address containing '\0'
Note that no memory has been allocated to hold characters. Only a pointer to char has been allocated. Thus you cannot store anything in your string!!
You could write something like:
char data[2] = "";
That would allocate a pointer, and a string to hold 2 characters

The second line, while(c == "") compares a real memory pointer (e.g. 0x123456) with a compiler pointer.
"" is not a real application pointer, you should not manipulate it.
So that second line relies on a compiler behavior.

If I were you I would wrap the multi-char routine into a single-char routine. For example:
int ReadChar(char *c)
{
  return ReadData(c, 1);
}

Then:
main()
{
  char c;
  ReadChar(&c);
}

On a different note, I think the compiler should catch such error.
The line c == "" would never do anything useful and should be caught.


text:
How to loop over objects or pass object to function?
I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.
I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.
However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.
I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.
I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:
SomeClass classA();
SomeClass classB();

// error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
SomeClass things[2] = {classA, classB};

int init(class SomeClass thing) {
    std::cout << "Setting up thing ";
    thing.setFoo(100);
}

int main() {

    for (int i=0; i < 2; i++) {
        things[i].setFoo(100);
    }

    // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
    init(classA);

    return 0;
}

And just for completeness my class files which are simplified versions of the AccelStepper class:
SomeClass.h:
#include <stdlib.h>

class SomeClass
{
public:
    SomeClass();

    void    setFoo(float foo);
};

SomeClass.cpp:
#include <stdlib.h>
#include <string>
#include <iostream>
#include "SomeClass.h"

SomeClass::SomeClass()
{
}

void SomeClass::setFoo(float foo)
{
    std::cout << "foo ";
}

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

There's a couple of fundamental errors in your sketch.  Mainly your construction of your class instances:
SomeClass classA();
SomeClass classB();

Those are taken as functions that return a SomeClass object, not SomeClass constructors.  Instead they should just read:
SomeClass classA;
SomeClass classB;

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier.  For instance, your array would look like this:
SomeClass *things[2] = {&classA, &classB};

That is an array of pointers to the objects.  It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.
Your loop would then run like this:
for (int i=0; i < 2; i++) {
    things[i]->setFoo(100);
}

Note the use of -> instead of . because you are using a pointer to the object.
Similarly your init() function would be like this:
int init(SomeClass *thing) {
    Serial.println("Setting up thing");
    thing->setFoo(100);
}

init(&classA);

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:
int init(SomeClass &thing) {
    Serial.println("Setting up thing");
    thing.setFoo(100);
}

init(classA);

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using .

Thanks for your answer! I should have included a more complicated constructor, the actual objects are created as eg:
AccelStepper stepperA(AccelStepper::HALF4WIRE, motorPinA1, motorPinA3, motorPinA2, motorPinA4);
Does this still hold with the above?

From my C experience, this looks like a pointer to an array of pointers: SomeClass *things[2] = {&classA, &classB}; Is it different in C++?

No, it's just an array [] of pointers *.  If it was a pointer to an array of pointers it would be SomeClass **things[2] - exactly the same as in C.

If your constructor takes parameters then you add parameters. If it doesn't you don't. It is a little confusing and I have no idea why they did it that way.

@Majenko thanks for your answer. It has been a great deal of help. I was wondering, however, instead of having an array of pointers with references to class objects, couldn't we just have an array of these objects and reference them like myObj &obj = arr[idx];?


text:
Re-enable Arduino after short
I happened to short-circuit my Arduino by mistake. It was powered by USB on my Windows 7. The OS was so smart to pop-up warning about USB power surge and shut it down immediately. Arduino survived.
I fixed the circuit and connected it back. Arduino was powered again, but it was not recognized as COM port anymore. There was no unknown device in Device manager. I tried different USB connector on the same computer and it was found and it worked. But the other USB was out.
I restarted the computer and connected the Arduino back to the broken connector. The drivers were automatically reinstalled (I don't know why) and it worked again.
Is it possible to re-enable Arduino on the same USB connector without restart? I'd like to understand what happened on the computer side.

Windows wouldn't have reacted fast enough to shut it down itself.  The hardware driving the USB port will have overcurrent protection built in and would have shut down the port and notified the OS of this occurrence.  It might be possible to avoid having to restart the PC by disabling and re-enabling the USB system from the Windows Device Manager but since your keyboard and mouse probably are USB devices this might be tricky.

But that said, shorting out the USB host controller can cause damage to your motherboard.  If you are worried this might happen again, I'd suggest you run your arduino from a powered USB hub instead of directly from the PC, that way it won't risk maging the motherboard.

Most likely, your motherboard detected a over-current situation, and disabled power to that port. Since it has to way to know if the cause of the over-current has been fixed, it will continue to disable the port (since the only way to know would be to turn the power back on, and doing that to many times might cause permanent damage).
I wouldn't expect there to be a way to force your MoBo to reset the port, as this is an unlikely event. You should be glad the MoBo prevented any damage.
Using a different port sounds like an okay solution.

I happened to do it again (shame on me), I noticed Win7 produced a background popup asking if that buggy device is disconnected with option to turn it on again. After that, another device such as mouse can be connected to it, but not Arduino until reset. So I guess it is a Windows feature.


text:
HD44780 DDRAM addressing on the second line
I write bytes to HD44780 display DDRAM to display characters and it works weird on the second line. I use 16x2 model and I write "0123456789" string from address X on.
According to the datasheet:

In a 2-line display, the cursor moves to the second line when it passes the 40th digit of the first line.

So when I set X to 40, the string appears from the beginning of the second line. So far so good. But when I change X to different values, this appears on the second line:
X=39 ... 123456789
X=40 ... 0123456789
X=41 ... 0123456789
...
X=47 ... 0123456789
X=48 ... 89
X=49 ... 789
...
X=56 ... 0123456789
X=57 ... 0123456789
...
X=64 ... 0123456789
X=65 ...  0123456789
X=66 ...   0123456789

Since address X=64 it works as expected, so increasing X by one shifts the string to the right by 1 character. The datasheet also says

However, when N is 0 (1-line display), AAAAAAA can be 00H to 4FH (79). When N is 1 (2-line display),
  AAAAAAA can be 00H to 27H (39) for the first line, and 40H (64) to 67H (103) for the second line.

So the second line starts at 40H (64), not 40, it seems. Is it a confusion? What is the idea between address 40-64? It would make sense if the second line was address 28H-40H. I don't see the explanation in the datasheet. Also, how the DDRAM works for 20 characters per line and 4 lines displays?

Your confusion here is mixing "digit" and "byte". The two are not the same.
HD44780's can never have more than two rows. If you look at the block diagram you can see there are 16 "COM" connections. Those are the rows of the characters - 8 per line. That gives at most 2 lines of text.
20x4 displays are actually 40x2 displays but sliced in half and stacked. The 21st character of the first line is actually the first character of the 3rd line.
These two lines are split into two separate blocks of memory. One starts at 0x00 and the other at 0x40. The two blocks are pretty much completely separate.  There is nothing of any interest to you between 0x28 and 0x3F. In fact that memory may not even exist - however those addresses may map to other addresses within memory. This will purely be an artifact of how the memory is addressed internally.
For simplicity of decoding the addresses the two blocks of memory are distinguished purely by the most significant bits of the address. The lower bits, then, will always be the same for the same location in both lines of text. That is, for the same horizontal character position on the display the first row (COL0-COL7) will have the same address in memory as the second row (COL8-COL15) except the most significant bits.
Since the HD44780 operates in blocks of 40 bits (8 characters, 5 bits per character) for its displays and uses "extension modules" to give each extra block of 8 bits (which is why you get 8, 16, 20, etc widths) having the two lines of text with truly consecutive memory addresses would make decoding the addresses needlessly difficult. So they don't.
If you take an example of the 3rd character horizontally on the display the pixel address in memory will be (note: this is the pixel address, which is 5x what the character address would be after the data has been generated from the internal character set):
Line 1: 0x02 = 0b00000010
Line 2: 0x42 = 0b01000010

Since the memory itself is 80 bytes and designed to be no more than 40 characters wide with 1 or two rows, there necessarily has to be a dead zone between the blocks of addresses. If the addresses were completely contiguous, so that the first character of the second row (character 40) was the 40th address in memory, the memory addresses would look like this:
Line 1: 0x02 = 0b00000010
Line 2: 0x2a = 0b00101010

Mapping those two addresses to the signals COM0-COM7 and COM8-COM15 would be considerably harder and take far more complexity in the design of the chip - which the manufacturer certainly doesn't want.
It is far simpler to add a little bit of logic into the cursor control which says "If the cursor moves from position 39 to 40 then set the memory address to be 0x40".
So when writing successive characters to the display the cursor logic hides the segmented memory from you. But if you are directly manipulating that segmented memory then you have to take that segmentation into account.

I see, I skipped the talks about SEG and COM pins as blackbox and jumped to the instructions part. Now it is clear.


text:
Serial communication between a single Android device and multiple Arduino boards
I am thinking about a project, but I will need let's say two Arduino Uno. I can see that we can just use different USB ports on a PC, but what about an Android device?
I want to "run commands" from it on both Uno boards. Is it possible to connect it as it is single board, just both in parallel? I do not need communication between the boards, just with the smartphone.
For example, let's say that one of the boards will control a green LED and the other a red LED. I want to send from my phone on the serial "toggle green" or "toggle red" and both the boards will change the state of the LED connected to it accordingly to the "command" received. Will both boards be able to receive the "command"?
Thank you!
EDIT:
I see that I forgot to add that I may need to receive on the phone from any of the boards. Something like feedback.

USB hub  . . .  ?

Yeah that could be possibility, but I want to run them as it is single. Isn't it possible?

let one arduino handle both leds. can't be far one from other if you have a usb connection

How do you connect a single Arduino to your phone now?

Juraj, I just give an example. I am going to use all the analog pins, so I will need more (and second chip will it be), I do not want PWM because they flicker on camera.
Dmitry Grigoryev, at this moment I have not used anything. I see that I can use data cable, and the arduino IDE from the appstore.
Thank you for the comments!

Use a third Arduino, which serves as a hub. It is connected to your Android and to all Arduino Uno devices you want to interface. It passes the commands to all Arduino devices, and the feedbacks to the Android device. You could use for instance an Arduino Mega, with the Android on Serial0, and the Arduino Uno devices on Serial1 and Serial2.

That should do the trick. I was thinking the same but I did not know why should I waste the 40 digital pins on the Mega, But since that's the only case I will do it. Since it will be on my car, managing my headlights (going to add projectors) maybe I will manage to use them from something else..
Thanks again! : ]

You could use a smaller device like an Arduino Uno, with SoftSerial instead of S1/2.

authors: Кристиян Илиев


text:
Arduino JSON foreach loop
I'm trying to extract values using ArduinoJson. The values aren't fixed, therefore I need to use the foreach loop.
I'm trying this, but I can't seem to use the values like I could with.
root["0"]["value"].as<const char*>();

Here is my code.
void loop(){
  int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
      payload = http.getString();
    }
    if(payload.length() > 0) {
      Serial.println(payload);
      JsonObject& root = jsonBuffer.parseObject(payload);
      if (!root.success()) {
        Serial.println("parseObject() failed");
        jsonBuffer.clear();
      } else {
        Serial.println("Data Fetched");
        for(JsonPair& node : root) {
          Serial.print("0 State: ");
          Serial.println(*node);
        }
        http.end();
      }
    } else {
      Serial.println("Payload Empty");
    }
  }
}

Please avoid any missing brackets. Thanks in advance.
[{"state": true, "value": 10}, {"state": false, "value": 8}, {"state": false, "value": 5}, {"state": false, "value": 13}]

How can we possible answer this question if we don't know what JSON will be fed in and what error occurs?

wouldn't it be root[0]["value"]?

what does this mean? avoid any missing brackets .... how do you avoid something that does not exist?

@jsotola I meant to say please avoid if I missed some bracket in the code above. Nevermind...

You should press ctrl-T and indent your code properly, as a start...

I found another way around the solution.
Idk if this is helpful to anyone but the problem was that I had an unknown number of nodes I wanted to loop through, Example of the json format above.
void loop(){
int httpCode = http.GET();
  if(httpCode > 0) {
    // if Get request has processed
    if(httpCode == HTTP_CODE_OK) {
          payload = http.getString();
      }
      if(payload.length() > 0){
          JsonArray& nodes = jsonBuffer.parseArray(payload);
          if (!nodes.success()) {
            Serial.println("parseObject() failed");
            jsonBuffer.clear();
          }else{
            int node_length = nodes.size();
            for(int i=0; i<node_length;i++){
              Serial.printf("node-%i\nValue : ",i );
              String value = nodes[i]["value"].as<const char*>();
              String state = nodes[i]["state"].as<const char*>();
              Serial.println(value);
              Serial.print("State : ");
              Serial.println(state);
            }
            http.end();
        }
    }else{
      Serial.println("Payload Empty");
    }
  }

  jsonBuffer.clear();
  delay(8000);
}

so you found out that the json array has a size property?

Yes both jsonArray and jsonObject has size property


text:
How to use use 2 or more HC-SR04 sensors as one single sensor?
I'm new to Arduino and this is my problem. I need to track an object in a room. For now I have placed 3 sensors on the edges of each axis (x, y, z), where the x axis will the line between the east and the west walls of the room, the y axis will be the north and south walls of the room, and the z axis will be the ceiling of the room.
I have written code to get the output as x, y, z coordinates. But since the HC-SR04 has no horizontal range it can only track objects in its line of sight. Due to this I'm not able to fulfil my requirements. So I thought if I could couple up an array of HC-SR04s together to work as one sensor I can get more horizontal range.
Is this possible using an Arduino Uno R3? If it's possible, please guide me through it.

You can try to use them sequentially. Or try triggering all sensors for one axis at once an wait for an echo signal at any of the echo pins (each one at it's own Arduino pin). For the first approach you may run into performance issues depending on the number of sensors. For the second you may see interference effects with the multiple sound waves interacting. Try and test. If this is successfull, please come back and answer your own question, so that everyone can profit from it.

You can try attaching your HC-SR04 sensor to a servo, then you will have a range of detecting an object in 180 degree span.

Of course you will have to make modifications to fit your purpose. Using three ultrasonic sensors with each of them having their own servo of 180 degree range will surely increase accuracy. To get started visit here.
Hope this was what you were looking for.
(Image credits: Dejan Nedelkovski)


text:
20x4 lcd display problems
I was recently experimenting with 20x4 lcd display with my Arduino Mega board. The connections which I followed are shown in the picture attached. I am very much sure about the connections and code written in the Arduino IDE. Everything is compiled and uploaded properly on my board. However the problem I found is the 20x4 lcd display only shows two alternate block lines and nothing else! To resolve this I tried following things:

I made sure multiple times the hard wire connections between Arduino and display and found all are as per requirement.
I made sure the proper coding with initialization.
I tried changing the value of 10KOhm pot in order to control the contrast setting of lcd.
I made sure about connecting the R/W pin of lcd to ground.
I tried replacing the lcd display with another same unit.

With above troubleshooting the problem still persists. Can anybody will suggest what could be the issue?
Suggestions are highly appreciated!
Thanks and regards,
VK

Two rows of blocks on a 20x4 is the same as 1 row of blocks on a 16x2. It's not initializing the screen. Either your code is wrong or the wiring between the Arduino and the screen is wrong (i.e., it has nothing to do with contrast).

I am very much sure about the connections and code written in the Arduino IDE. -- that cannot be the case. One of those two is wrong. Your wiring looks fine (from what you showed us), so it must be your code that is wrong.

Try wiggling the wires in the breadboard. Breadboard sometimes don't make a good connection with the wire. Could you post an image of your setup, and the code you uploaded? As you've already done everything I would normally suggest.


text:
Cannot upload to Robotdyn Mega 2560 PRO MINI?
I get this error trying to upload avrdude: stk500v2_ReceiveMessage(): timeout
It is Robotdyn Mega 2560 PRO MINI and a Robotdyn CH340 which I have connected like this:
I installed the CH340 drivers from here https://sparks.gogo.co.nz/ch340.html and I can see it in the device manager.
Connecting the Mega 2560 Pro Mini lights up the L and On LED but when pressing upload (testing with simple examples as Blink) I get the error and neither RX or TX lights up.
I have tried everything I can think of. What am I doing wrong?
I have confirmed that it is connected to the correct COM-port and I use these settings:
Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

I have also tried many different USB-cables, short and long, and USB 2.0 and USB 3.0 ports. I use Windows 10 64-bit.

why is the pin header not soldered to board?

It is now, took the picture before

@Juraj this is not the same error message?

but the same troubleshooting

I now have the adapter and it has swapped RX TX labels, so must be wired RX to RX, TX to TX

Try placing a 100nf capacitor on RST. That is usually required on an FTDI programmer.
See Edgar's post - https://arduino.stackexchange.com/users/47431/edgar


text:
Is it possible to send data from device (e.g. MPU6050) to Arduino through cut/hacked USB cable?
So I understand the USB cable consists of VCC, GND and Data+, Data-.

Is it possible to connect an MPU-6050 gyro to these 4 pins, especially data+/-, and still receive them normally through the SCL/SDA pins on the Arduino?
The goal is to make an input piece modular by having an USB out at it while having an USB in at the Arduino.
Here is a basic visualization:

No, the i2c bus is not meant to go through a cable.

Just make sure you keep the VCC and GND wires the same as USB, so that in the event someone plugs it into a PC, thinks don't get damaged.

Execellent non-Arduino question about I2C cable so the answer is also non-Arduino. I recommend the following Hackaday blog. https://hackaday.com/2017/02/08/taking-the-leap-off-board-an-introduction-to-i2c-over-long-wires/. You can find a more theoretical model in https://www.analog.com/media/en/technical-documentation/technical-articles/I2C-Cabling.pdf
Basically yes you can use cables. Different cables have different level of capacitance per meter. This will reduce the maximum frequency and may also require adjustment of the pull-up resistors.
Cheers!
BW: "nihil novi sub sole": This question has been asked before, https://forum.arduino.cc/index.php?topic=143337.0

Thanks for the info. I just did it with simply connecting the wires and was suprised that it worked, but it's actually just a long wire in the end, right? So of course it should work. But now I'm wondering what if I needed one more pin (e.g. the AD0 of the MPU)? Can I somehow manually put one more wire inside the USB?

Why all the trouble? There are a lot of different cables out there. USB has four wires so that is a limit. How about using an Ethernet cable? Or even Telephone cable. In any case do not forget to accept the answer if it was just that.

You're right, gonna do something similar!


text:
uno timer0 prescale
I have a project where I need to get a low frequency to get a pwm suited from my project. The problem is that after I modify the frequency of timer0 the millis() becomes slower or faster depending on prescalar. So a fix as stated here is to change prescalar in wiring.c. But I don't know for what reason when I set it to 256 or 1024 the millis return 0. For 1-64 works fine.
Timer 0 uses a prescale factor which is set to 64 by default
To set the prescale factor use this line in the setup function

Setting                          Prescale_factor
TCCR0B = _BV(CS00);              1
TCCR0B = _BV(CS01);              8
TCCR0B = _BV(CS00) | _BV(CS01);  64
TCCR0B = _BV(CS02);              256
TCCR0B = _BV(CS00) | _BV(CS02);  1024

To use Fast PWM on Timer 0
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
And to calculate the PWM frequency, use
Fast_PWM_frequency = (16 000 000)/(Prescale_factor*256);

To use Phase-correct PWM on Timer 0 (half the frequency of Fast PWM)
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
And to calculate the PWM frequency, use
Phase_correct_PWM_frequency = (16 000 000)/(Prescale_factor*510);

Changing the prescale factor on Timer0 will affect functions
millis(), micros(), delay(),...

To adjust millis(), micros(), delay(),... accordingly,
You can modify a line in the wiring.c function in the Arduino program files
hardware\arduino\cores\arduino\wiring.c

In the beginning of wiring.c you can find:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

You need to modify the prescale factor in this function to the corresponding line

For fast PWM (default):
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR* 256))
For phase-correct PWM :
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR * 510))

try setting it to 257 or 1025

Integer math in C is done in an int or unsigned int by default. int is 16-bit on AVR. 256 * 256 overflows to 0, as does 1024 * 256. You will need to tell the compiler to perform the math in a longer type.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(256 * 256L))

The value is stored in an unsigned long not an int, which is 32 bits.

Amended, assuming you are correct.


text:
Passing the result of the variable to another variable
Hello everyone i'm figuring if this variable can be passed to another variable. I'm using RFID RC522
Here is the code:
 #include <SPI.h>
    #include <MFRC522.h>
    #define RST_PIN         5           // Configurable, see typical pin layout
    above
    #define SS_PIN          53          // Configurable, see typical pin layout
    above
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    int result = 0;
    // Number of known default keys (hard-coded)
    // NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
    #define NR_KNOWN_KEYS   8
    // Known keys, see:
    https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
    byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
    };
    /*
    * Initialize.
    */
    void setup() {
    Serial.begin(9600);         // Initialize serial communications with the PC
    while (!Serial);            // Do nothing if no serial port is opened (added
    for Arduinos based on ATMEGA32U4)
    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();         // Init MFRC522 card
    // Serial.println(F("Try the most used default keys to print block 0 of a
    MIFARE PICC."));
    }
    /*
    * Helper routine to dump a byte array as hex values to Serial.
    */
    void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */
boolean try_key(MFRC522::MIFARE_Key *key)
{
    boolean result = false;
    byte buffer[18];
    byte block = 0;
    byte status;

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("PCD_Authenticate() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("MIFARE_Read() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        //Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        //Serial.println();
        // Dump block data
       // Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array(buffer, 16);
        //Serial.println();
    }
  //  Serial.println();

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;
}

/*
 * Main loop.
 */
void loop() {
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;
// Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
    return;
    // Show some details of the PICC (that is: the tag/card)
   // Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
delay(3000);
// Serial.print(F("PICC type: "));
  //  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    //Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys

      }

I list all of my card's value and i want to create a conditional statement if the result of dump_byte_array is the same with my card's value i list.
Sample:
if ( dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) && "D4 39 F8 BE" ==
  true ){
        Serial.print("Card 1 Detected");

That's what i want to happen but i know that is wrong.
Please help me with this.
Thank you in advance.

Ok sir , i will edit my post.

looks similar to this question - anyway, since the function (which you wrote) i.e. void dump_byte_array doesn't return anything, then, no, you can't possibly compare the result of calling that function with anything ... perhaps create a new function, to which you pass mfrc522.uid.uidByte, mfrc522.uid.size, [0xD4, 0x39, 0xf8, oxbe] which can return true/false

I tried to add this code and it works fine but no result if its, Card 1 is correct.

Simply rewrite your dump_byte_array function as follows
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    for (byte i = 0; i < bufferSize; i++)
        if (buffer[i] != match[i])
            return false;
    return true;
}

and call this new function like
if ( matchID(mfrc522.uid.uidByte, mfrc522.uid.size, [0xD4, 0x39, 0xF8, 0xBE], 4)) {
    Serial.print("Card 1 Detected");
}

As suggested in the comments, what's wrong with memcmp ...
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    return memcmp(buffer, match, bufferSize) == 0;
}

I tried to rewrite this:
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);

to this:
[code]
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
if (bufferSize <> matchSize) return false;
for (byte i = 0; i < bufferSize; i++)
if (buffer[i] <> match[i])
return falsbool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
if (bufferSize <> matchSize) return false;
for (byte i = 0; i < bufferSize; i++)
if (buffer[i] <> match[i])
return false;
return true;
};
return true;
}
[/code]

And it gives me:
exit status 1
expected primary-expression before '>' token

That's not valid code. Sorry was in vb mode

But it can convert it to C++ ?

answer edited, check now - my code had one flaw ... <> instead of != - so, yes, it can be converted!

It gives me another error:expected primary-expression before '>' token

see ... there were two places I used <> instead of != - that's the problem with blindly copying code from an answer without understanding it - try now - I'm beginning to suspect the code in the question is not written by you, rather it is an exact copy of someone elses efforts

I didn't copy paste the code, i'm typing it and trying to understand what's the code mean.

What's wrong with using memcmp?

absolutely nothing - just made the simplest change possible with the view that it'd be easier to learn :p added it to the answer


text:
Read serial data from XV11 sensor
I am trying to read data from an XV-11 sensor using the description of the format found here https://xv11hacking.wikispaces.com/LIDAR+Sensor.  This is the code I am currently using to communicate with the computer by USB and the sensor with software serial on an arduino uno.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  mySerial.begin(115200);
}

int count = 0;

void loop()
{
    if(mySerial.available())
    {
      byte in = mySerial.read();
      Serial.println(in, HEX);
    }
}

However, the data I am receiving on the computer is inconsistent with what I expect.  For example, I am expecting a 0xFA byte every 22 bytes, however this only sometimes happens.  Many times extra or fewer bytes appear in the middle of the data.  I am using the 5 volt arduino serial communication, however I have heard that it is still compatible with 3.3 V sensor communication, so I doubt it is the problem.  I don't thinkthe sensor is broken, as it is new from a working unit.

3.3v is "on the edge" of communication with 5v. Also the Ardunoo's TX must go through a level shifter of some form (resistor divider would do) to drop it to the 3.3v of the sensor or you could damage the sensor. Also, you do have the grounds connected together don't you...?

I am only receiving data from the sensor so the arduino tx isn't even connected to the sensor.  The sensor is connected to the arduino 5V and ground pins

Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection.  I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.

The 'Serial' baud rate is too low compared to the baud rate of 'mySerial'. It could be causing you to lose bytes as the Serial buffer overflows, especially if the sensor transmits a lot of values in a relatively short interval. Increase the Serial baud rate to 115200 and see how it goes.


text:
Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE
I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.
When I try to transfer a sketch to the device it fails with error message
avrdude: stk500_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11  and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.

Are you using the same cable in both cases? Could be a cable issue if you're not.

Solved:
The issue was due to an USB Hub which I have at my desktop.
After I connecting the arduino directly to an USB port at my desktop everything was fine.
Unfortunately there is no hint about this in the arduino troubleshooting guide. A hub is only mentioned in conjunction with a MAC.


text:
None of the programs in Arduino example is compiling
I am new  to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\ drive
exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist
    Error compiling.

I don't know what to do. Please help me

A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it here.
What's odd looking too me is:

The double backslashes, they could be causing the file to appear not to exist, and
The arduino-nightly component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).

One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.

The link which you gave is for downloading arduino 1.6.6 which is arduino- nightly

Hmm, did you try the Windows Installer (in the box on the right hand side) rather than the Hourly build? You might also try an older version. I'm on a Mac and my install (of 1.6.6) does not mention being "nightly."

Also, double check that the missing file, and the path to it, actually exist.

Yeah it worked perfectly well for older version i.e 1.6.5. Thanks @dlu


text:
Can I convert 3.7V to 5V's using 3.3v to 5v converter

THe product: (https://www.sparkfun.com/products/12009)
So guys, here' s a pretty simple but important question for me:
Can I convert 3.7V (li-po battery's voltage level) to 5V's (I do have arduino pro mini running on 5 volts) using 3.3v to 5v converter (picture shown above...) ??
Thanks already...

That looks like the SparkFun BOB-12009 Level Converter https://www.sparkfun.com/products/12009 . If so, it would help if you identified it as such

Thanks, glad I' ve heard that. I' m editing my Q right now...

No. That is a level shifter. It uses a low voltage (3.3V) to switch a separate high voltage (5V) supply to create different logic levels.
It does not convert voltage, it merely switches.
To create 5V from 3.7V you need either a boost converter (inductor based circuit) or a charge pump converter (capacitor based circuit).


text:
ERROR: Timed out waiting for Arduino 101 - anything I can do?
I just received an Arduino 101 so I did the following in a wave of excitement...

Connected the USB cable between it and my Macbook Pro
Started the Arduino IDE version 1.6.7
Wrote a little bit of code
Selected Tools | Boards | Boards Manager... and installed the Intel Curie Boards as per Getting Started
Selected Tools | Board: "Arduino 101"
Selected Tools | port: "/dev/cu.usbmodemFA141 (Arduino 101)"
Selected Sketch | Upload

I was expecting something amazing, but I got the error:
Starting upload script
Payload: /var/folders/jr/5rmqcrqj58103d4p1f6_3sjr0000gn/T/build7c6ce067b9e8a57f9917c651ec494989.tmp/orientation.ino.bin
Waiting for device...
ERROR: Timed out waiting for Arduino 101.

Is there anything I can do to debug this or did I miss a step perhaps?
(I tried the good ol' turn it off and on again, including shutting the IDE down).

Press the reset button next to the USB port. (either one, the master reset is between the DC jack and USB ).
This will cause the Arduino 101 to reboot and enter DFU mode for 5 seconds if it is connected on USB. The download will proceed when the Curie enters DFU.
The IDE uses a baud-rate signal over USB. It is a virtual serial port, so baud rate doesn't matter. But when the host side (Arduino IDE) switches the baud rate to 1200, the board will reboot and enter DFU mode for download. If it gets stuck for some reason and misses the message to reboot, you can just hit the reset button and accomplish the same thing.

If the path to your source file contains a space, it might be causing this error. For more information, and a workaround, see this topic in the Arduino forum.

I am running Ubuntu 18.04 and I had a similar problem but solved it in the end.
What worked for me was:

Update Arduino Curie driver in Boards manager to the latest version which is v 2.02 at the time of this post

Run the following command in terminal in order to grant execution rights:
 chmod +x ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

Run the executable
 sudo ~/.arduino15/packages/Intel/hardware/arc32/2.0.2/scripts/create_dfu_udev_rule

Restart Arduino and try to reupload

Edit for Debian testing
At the time of this edit, all the previous steps work for the Bookworm distribution, with the latest Arduino IDE version (1.8.19) and the latest Arduino Curie driver version (2.0.5). Just remind to adapt the previous path according to the driver version.

I was having the same problem: unable to upload a program to a brand new 101.  Now it works.
I can successfully load both BLE LED example programs and also the ReadTime program read via Serial Monitor.  (BTW, using the iOS MCP app, you need to send either 00 or 01 to turn the LED on/off.)
I am running a modern 64 bit laptop with USB 3.0 ports.  All ports work fine with either of two USB cables that I have.  So I don't believe the problem is related to USB cables or USB 2.0/3.0.
How did I fix it?  Well, I tried several things and I'm not sure which one fixed it, so perhaps someone can try these methodically and confirm the best fix.

Uninstall the Arduino IDE and manually deleted the Arduino15 folder in user..\AppsData.
Restart laptop.
Download and install IDE 1.6.8.  (Earlier failed attempt was with current 1.6.9.)
Restart laptop.
Open IDE.  In Boards Manager, searched Intel, selected Curie boards, and install v1.0.4.  (Earlier failed attempt was with current 1.0.5.)
Restart laptop.
Open IDE.  Plug in 101 for the first time.  Device showed up normally in Device Manager.
Select proper port (COM5 for me) and proper board (101).  Select example file LED under CurieBle.  Click verify.  Looks good.  Click upload.  SUCCESS!  Can now see the 101 in nRF MCP, can turn LED on/off.  BLE functions now work with 5V USB charger. (but not 9V battery, guess that's not an option) When connected to laptop USB 3.0 port, the 101 now stays in COM5 the entire time, no longer cycling on/off when I try to upload.  No need to press either reset button during upload.

So the fix is either one of the software downgrades, or careful installation procedure.
Previously, I tried the dfu-utils updates but that didn't fix this problem.

I was really persistent to look for ways on how to fix the Arduino/Genuino 101 Timeout Error, I searched different forums and read a lot of suggestions on how to fix the error, but still all failed, I know some of the 101 users already bricked their 101 or other just left it behind.
We are all aware that the Arduino 101 is already discontinued and even support is already stopped, Hence this little but powerful microcontroller is still out there and probably used by the some. Anyhow, to be straight to the point I finally I discovered the fix for the error.
Notice that when you insert your 101 to the USB plug it will read and install the device, checking it in the device manager will show the Arduino/Genuino 101 in "Other Devices" and a new COMPort (COMX) is added, then you install the Arduino IDE (regardless of the version), then install the Arduino 101 Board thru "Board Manager", the manager will install the Arduino 101 but it will not notify you that the driver for Arduino 101 is not installed due to error. So in short we are assuming that the driver for Arduino 101 is successfully installed. This is where the error lies. The software driver "dpinst-amd64" is not digitally signed and Windows is blocking to install unsigned drivers.
So what's the fix?
The fix here is still to install the "dpinst-amd64" since it is the driver needed to recognize your 101, the trick here is you need to install it in other way, not in your regular PC operation. You need to access the "disable signature enforcement" under the startup options (not safe mode). This startup mode will enable you to install unsigned drivers (I trust this Intel Curie driver since it was downloaded with the board). After installation restart your PC to its regular startup and plug-in again your Arduino/Genuino 101, this time the PC will now recognize the microcontroller and you can now upload sketches without the time out error.
For a step by step procedure:

Access Update and Security>Recovery>Advanced Startup
Your computer will eventually restart and will bring you to the Advanced Startup, access Troubleshoot>Startup Settings. Your PC will restart again and options for the startup will display, choose number 7 "disable signature enforcement"
Your PC will start. Locate "dpinst-amd64.exe" in C:>Users>YOUR USERNAME>AppData>Local>Arduino15>packages>Intel>hardware>arc32>2.0.4(latest version)>drivers>dpinst-amd64
During installation a message will prompt if you want to install the unsigned driver, just click install.
After installation restart your PC and your Arduino/Genuino 101 is good to go.
To confirm that your Arduino/Genuino 101 is installed go to Device Manager and you will see that the Arduino/Genuino 101 is not anymore in the Other Devices.

I hope this will help. :D I will try to make a video about this fix. :D
Thanks!
Regards,
Raf

I posted a fix here:
https://forum.arduino.cc/index.php?action=profile;area=showposts;u=1472279
I was really looking forward that this will be the fix for all Arduino 101 Error

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

Oh yes sure I will just copy and paste the steps here

It's already documented in the arduino.cc, but I will just add here as reference:

Linux only: some distributions need to be configured to perform the
  upload. After installing the core, execute
sudo ~/.arduino15/packages/Intel/tools/arduino101load/1.6.4+1.18/scripts/create_dfu_udev_rule

inside a shell to gain upload permissions.

Reference: Upload Procedure


text:
How can I maintain switch state when in sleep mode?
I'm using a esp8266 to build a remote control to power a gas fireplace. I'm using this guide to try and maximize battery life.
The concept is the controller uses its built in WiFi to access a RESTful API on a remote server; If the API discovers"1", it should close a switch and the fireplace turns on. If the arduino reads a "0" via the API it opens the switch and the fireplace turns off. After discovery and performing the required action the unit calls Deepsleep and shuts off for ten seconds, whereupon it powers up and the cycle repeats itself again.
I just realized that if the controller powers off, I don't know what happens to the switch. If the fireplace was turned on,  what happens when deep sleep starts. Is there a way (special switch?) that maintains its state in deepsleep mode?

Please edit question to clarify meaning of  “I'd it sees”

Save the last state in EEPROM. Or, since you are using a remote server, store the state on the server.

@Gerben I think he means the physical state of the IO pin - when in deep sleep the general consensus (though I haven't found a definitive answer) is that the GPIO pins will lose their drive state when the chip goes to sleep.

@Majenko that indeed makes more sense.

Yes, there is such 'switch'. You could use JK Flip-Flop to hold the last output. JK Flip-Flop has J, K and clock inputs and If J and K are different then the output takes the value of J at the next clock edge.

Wouldn't the flip-flop require power all the time, reducing the benefits of the deep sleep mode?

ESP8266 draws from 50 up to 200 mA while J-K flip-flop draws 5-6 mA + less than 100 µA per input. Everything reduces the benefits of the deep-sleep mode, even the ESP8266's counter which is still running during deep sleep.

So that's a "Yes, but the difference is marginal"? I was asking for enlightenment, so thanks for the info.

Well, the difference between the deep sleep mode and 'deep sleep + J-K flip flop' is indeed considerable because the current draw in deep sleep mode is only about 10 µA but 5-6 mA might still be acceptable when using batteries because a few seconds of ESP8266 drawing full power everytime it wakes up will probably drain the battery more than J-K flip-flop drawing a few mA continuously. Depends on waking up intervals and for the remote control to be acceptably responsive ESP has to wake up quite frequently.

During my Deep Sleep experiments I noticed that a couple of pins held their state through a Deep Sleep reset, but I didn't write it down anywhere.  Simple observation suggests that any of the pins that wiggle during boot will NOT be retained, which leaves just GPIO4 and GPIO5 for likely candidates.  Try it and see!
During Deep Sleep the pins hold their state, although they're using weak FETs equivalent to 2uA source/sink current.  The boot cycle following Sleep clobbers most of the GPIOs.  Sigh.

You can get a latching relay. These come in two flavours - Unipolar, where you energise one pin to turn it on, and energise the other to turn it off, and Bipolar, where the direction of the current through the coil turns on or turns off.
Unipolar is easier to drive since you just need two transistors, diodes and resistors. Bipolar is harder, since you need a H-bridge (motor driver), but requires less wires to connect it up (2 as opposed to 3).
In both cases it is just a short pulse that is needed to switch the relay into a different state - there is no need to maintain the output, so is ideal for deep-sleep mode where everything is turned off except the RTC.

authors: Сергей Корягин


text:
Arduino command line vs. Arduino builder
I'm working on adding my Arduino to continuous integration and I came across two different possible ways of doing this, Arduino command line, and arduino-builder.  Can someone explain why the arduino-builder tool exists separately from calling Arduino from the command line?  And what are the advantages of using one over the other?

...and http://platformio.org/#!/frameworks

I've discovered one downside of calling arduino_debug (on windows) from the command line.  It generates graphical pop-ups for errors instead of command line messages.

The Arduino IDE command line predates arduino-builder and was made available when the source pre-processing and compiling was implemented by a Java class (deeply) embedded in the IDE.
The current IDE uses arduino-builder behind the scenes to process and compile the code so if you use arduino-builder you avoid having to load the whole Java IDE. Try it out it does some pretty cool stuff

I've written a new option for Arduino CI/unit testing and put together a decent size writeup about it as an answer to this related question.
I ended up using the Arduino command line instead of arduino-builder, because it worked better cross-platform for me.  It assumes a graphical display though, even if you just use the CLI features.  In the case of Travis CI, I needed to spin up a fake X display to handle the initial splash screen and other graphical error messages.  (Fortunately, you can tell based on how long a command takes to complete whether it's waiting for you to acknowledge a graphical error message.)
Some examples of how to enable CI on your own project:

The DoSomething example library shown above, used to test arduino_ci itself
A practical example, testing a Queue implementation
A complex example, simulating a library that controls an interactive device over a SoftwareSerial connection as part of the Adafruit FONA library