text:
Molex power with USB serial Communication from the same PSU
Before I begin I just want to apologize for my mediocre understanding of things electrical and arduino. I know there are a lot of topics similar to this but I'm confused by the term external PSU
Question
Do I need to worry about any sort of issues (loops/grounding) if I use the molex connector to supply power to my arduino uno and continue to use the USB for serial communication at the same time? The source of both would be from the same PSU in my PC.
From what I understand the Uno when powered by DC should not exceed 7.5V for maximum efficiency. So it looks like the 5V from the molex would be more suitable than the 12V and sufficient for my needs of roughly 3.6A (60mA per LED * 60). Since USB can only supply a maximum of 2.0A and Molex appears to supply up to 5.0A from what I've read.
And I would connect it like so 5V molex powered Uno?
Background
Currently I'm using the arduino uno to power a single 5V strip of 30 rgb WS2812B leds, which works great when powered through the USB port, but since I need an additional strip of 30 leds and USB alone cannot supply enough amperage to power both I need a better source of current. I also needed the cleanest solution possible as it's for a PC tower and I don't want to use an external power source.
Edit - Alternative solution
If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino

I think the Molex and the USB should have a common ground (The PC, The mains, etc), but why not just add one just to make sure?

USB is rated to supply only 500 mA. Some charging adapters, and occasionally computer USB ports, will supply more, but that should not be counted on unless you're doing the proper detection (which is manufacturer-dependent) to confirm that you can do that.

Oh, and I'd forgotten, there's also a 500 mA polyfuse on the USB input of the Uno, so even if your USB port can supply more than 500 mA, it makes no difference.

Post your own solution as an answer, not as an edit to the question.

Two important things first:

The Uno 5 V pin and power bus must never be supplied more than 5.5 V or the MCU may die. The DC power input jack (the barrel jack) and the Vin pin, which are connected together, are not directly connected this bus, which is why you can supply higher voltages to that (see below).
You can not simultaneously supply power via both the USB cable and a power supply to the 5V pin/5 V bus because that would directly connect the two power supplies. That's a very bad thing, and probably not just for the Uno. (But there is a trick you can use here to still connect USB data when you are supplying power to 5V; see below.)

Now on to the details.
You can safely connect Vin (the pin or the barrel jack; they are directly connected) and USB at the same time because there's a switch (T1 on the schematic) on the board that will disconnect the USB power line from the Arduino 5V bus if more than 3.3 V is being supplied to Vin.
However, Vin goes through a regulator which, while it has the advantage of safely handling voltages much higher than 5 V, also causes some voltage drop, so you need to supply it with a minimum of 7 V. (6 V might work if there's very little power draw; 5 V almost certainly will not.) The maximum voltage you should supply is 20 V, but it's recommended that you stick to 12 V or less, since higher voltages mean that the regulator can get rather hot.
Unfortunately for you, this doesn't really help with your problem. While you could take the 12 V power off the molex connector, supply it to Vin and run the Arduino itself quite happily with the USB cable also connected, the regulator on Vin is rated for only 1 A, which is considerably less than you need for the entire system.
There are ways to have some parts of the system powered by one power supply and other parts powered by a separate power supply, but they're not trivial (and also beyond my expertise at the moment :-)).
Probably the easiest solution is to connect the 5 V output from the molex connector to your system power bus, which would be supplying both the 5V pin on the Arduino and your external components, and then build a custom USB cable with only the D+ and D- pins connected, dropping the power and ground pins. (You don't need the ground pin because the USB data signal is actually a differential signal: the difference or similarity in the voltage between D+ and D- pins is what determines whether the signal is a 1 or a 0.)
By the way, just to make sure, you do have some separate switching for all those LEDs, right? You're not trying to provide all their power via the Arduino digital outputs? Because, as per section 32.1 of the ATmega328P datasheet, while you are allowed to sink up to 40 mA from any individual data pin, you cannot sink more than 200 mA in total from the chip.

Wow thank you for such a detailed and well thought out explanation. Really appreciate that since, I know very little. To answer you question about the LEDs I'm not entirely sure how to answer it best. This is the project I'm using as an example for mine. https://github.com/CalcProgrammer1/KeyboardVisualizer right now there is no switching on my led strips connected to the digital output, ground and the 5V pin that I am aware of. Seems to run fine with just the 1 strip of 30 LEDS so I'm assuming that the strip itself is handling this?

I'm marking you answer as the correct answer. But I have discovered an easier way which wouldn't require a custom USB cable, I could simply power the Arduino from my PC's motherboard USB header via a standard cable and the LED strip from the Molex seperately. The only connection between these two would need to be GND and led strip data line I believe. So I would never need to try share a 5Vs connection between the 2 components.

If you have an Arduino board with USB, simply power the Arduino from your PC's USB via a standard cable and the LED strips from the Molex. The only connection between these two would need to be GND and led strip data line. No need to share a 5V between the LEDs and the Arduino


text:
Pushing sketches to pro mini with Uno 101
So I just bought a Pro Mini the other day, however, I didn't get an FTDI cable or a USB/Serial converter board.
From what I understand from this article I can use my Arduino Uno 101 to push sketches onto the Pro Mini.
The wires are all hooked up (grounded reset on the Uno) and I have uploaded the sketch to disable the serial communication port on the Uno, however, when I try to push a sketch to the Mini it errors out with the following message
Arduino: 1.8.3 (Windows Store 1.8.6.0) (Windows 10), Board: "Arduino Pro or Pro Mini,
ATmega328 (5V, 16 MHz)"

Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for
local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\\.\COM3": The system cannot find the
file specified.

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

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

The only part of the suggested troubleshooting guide that maybe applicable is the drivers section.

Drivers
The Arduino Uno and Mega 2560 use standard drivers (USB CDC) provided by the operating system to communicate with the ATmega8U2 on the board. Other Arduino boards use FTDI drivers to communicate with the FTDI chip on the board (or in the USB-serial convertor).

I could be wrong but to me it doesn't seem like the second sentence applies to this situation since the the Uno sits between the pc and the mini. However, when I check the windows device manager I can see that the Uno is connected on a COM port, but nothing about the Mini. Though I am not sure that it should show up.
I am using the IDE(1.8.3) to program and "Arduino Pro or Pro Mini" as the board. Though Tools>Port is greyed out when I have this board selected.

There is no "Arduino Uno 101" there are only "Arduino Uno" and "Arduino 101".
101 uses completely different hardware, and tricks to use an Uno as an USB to UART adapter won't work on an 101.
101 has also separate serial interfaces for USB serial (Serial) and hardware serial (Serial1).
If you have have an Arduino 101 you can solve this by software means.
The board needs to be able to change the baud rate and use DTR for reset.
There is a sketch from PaulStoffregen on GitHub that does that.
/* USB to Serial - Teensy becomes a USB to Serial converter
   http://dorkbotpdx.org/blog/paul/teensy_as_benito_at_57600_baud

   You must select Serial from the "Tools > USB Type" menu

   This example code is in the public domain.
*/

// set this to the hardware serial port you wish to use
#define HWSERIAL Serial1

unsigned long baud = 19200;
const int reset_pin = 4;
const int led_pin = 13;  // 13 = Teensy 3.X & LC
                         // 11 = Teensy 2.0
                         //  6 = Teensy++ 2.0
void setup()
{
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
  digitalWrite(reset_pin, HIGH);
  pinMode(reset_pin, OUTPUT);
  Serial.begin(baud);       // USB, communication to PC or Mac
  HWSERIAL.begin(baud);     // communication to hardware serial
}

long led_on_time=0;
byte buffer[80];
unsigned char prev_dtr = 0;

void loop()
{
  unsigned char dtr;
  int rd, wr, n;

  // check if any data has arrived on the USB virtual serial port
  rd = Serial.available();
  if (rd > 0) {
    // check if the hardware serial port is ready to transmit
    wr = HWSERIAL.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the USB port
      n = Serial.readBytes((char *)buffer, rd);
      // write it to the hardware serial port
      HWSERIAL.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if any data has arrived on the hardware serial port
  rd = HWSERIAL.available();
  if (rd > 0) {
    // check if the USB virtual serial port is ready to transmit
    wr = Serial.availableForWrite();
    if (wr > 0) {
      // compute how much data to move, the smallest
      // of rd, wr and the buffer size
      if (rd > wr) rd = wr;
      if (rd > 80) rd = 80;
      // read data from the hardware serial port
      n = HWSERIAL.readBytes((char *)buffer, rd);
      // write it to the USB port
      Serial.write(buffer, n);
      // turn on the LED to indicate activity
      digitalWrite(led_pin, HIGH);
      led_on_time = millis();
    }
  }

  // check if the USB virtual serial port has raised DTR
  dtr = Serial.dtr();
  if (dtr && !prev_dtr) {
    digitalWrite(reset_pin, LOW);
    delayMicroseconds(250);
    digitalWrite(reset_pin, HIGH);
  }
  prev_dtr = dtr;

  // if the LED has been left on without more activity, turn it off
  if (millis() - led_on_time > 3) {
    digitalWrite(led_pin, LOW);
  }

  // check if the USB virtual serial wants a new baud rate
  if (Serial.baud() != baud) {
    baud = Serial.baud();
    if (baud == 57600) {
      // This ugly hack is necessary for talking
      // to the arduino bootloader, which actually
      // communicates at 58824 baud (+2.1% error).
      // Teensyduino will configure the UART for
      // the closest baud rate, which is 57143
      // baud (-0.8% error).  Serial communication
      // can tolerate about 2.5% error, so the
      // combined error is too large.  Simply
      // setting the baud rate to the same as
      // arduino's actual baud rate works.
      HWSERIAL.begin(58824);
    } else {
      HWSERIAL.begin(baud);
    }
  }
}

Then you need to connect:
Arduino 101  |  Arduino Pro Mini
-------------+------------------
VCC          |  VCC
GND          |  GND
TX           |  RX
RX           |  TX
PIN 4        |  DTR

After that you can use the port as a Arduino Pro Mini programmer.

I tested that code on a Pro Micro and was able to program a Pro Mini.

source: Stack Exchange

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

sort: votes


text:
Custom ATMega 2560 board won't execute Arduino code
I have a custom PCB with an ATMega 2560 microcontroller on it. To test if the ATMega was working properly, I uploaded the following code:
void setup() {
  Serial.begin(9600);
  Serial.println("Test setup");
  pinMode(6, OUTPUT);
  pinMode(30, OUTPUT);
  pinMode(31, OUTPUT);
  pinMode(32, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  digitalWrite(30, HIGH);
  digitalWrite(31, LOW);
  digitalWrite(32, HIGH);
}

The mentioned ports are connected to LEDs, 6 to an external LED and 30, 31 and 32 to LEDs on the PCB. Each connected in series with a 220 Ohm resistor.
The board is setup like this:

When uploading I am using a Arduino UNO as ISP and after uploading the Arduino IDE says 'Done uploading' without any errors, but the board is not showing any sign of executing the code. I have checked that VCC is 5V and RESET is HIGH after uploading. The text "Test setup" is also not shown on the serial monitor.
Does anybody have a clue why the board is not working?
Thanks on forehand.

There could be many reasons - the most common of which is that your crystal isn't running right. You'll have to show us your schematic and images of your PCB for us to help you.

Edited, good point on the crystal, I will check if it is functioning well.

Also make sure that your fuses are burned correct for your crystal source.

The crystal itself is working. I have added a picture of the board as well. A problem I found myself is that maybe the loop of the crystal and its capacitors is rather large, which may cause the problem.

As was pointed out the first time you posted this, your description doesn't really make sense.  If you are using ISP, then what does the bootloader have to do with it?  If you loaded the bootloader via ISP, you don't have a test program on there, and if you loaded the test program via ISP, you no longer have a bootloader...

Edited, I understand the confusion. I did not understand that the bootloader was not needed if I was using the Uno as ISP anyway. It is still strange that the code lighting up the LEDs is not working. Right?

When using an empty ATMega2560 you need to change the fuse settings, otherwise it will just upload your code but it won't execute.
This tutorial explains it very clearly:
Programming ATMega 2560 with Arduino UNO

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


text:
how to implement PWM LED fading into a random case switch?
Ive recently bought my self a arduino Mega 2560 and managed to get a sort of RANDOM function to work with different cases which go of by the number selected.
My question is is there a way to also make a PWM sequence in such a case? so that the LED is fully light to dark and then the the next case starts?  IS there a more random sequence wich i could then also expand if neccesary?
Mark.
int ledcolor = 0;
 int a = 500; //this sets how long the stays one color for
int b = 2000;
int brightness = 255;    // how bright the LED is
int fadeAmount = 25;    // how many points to fade the LED by

 void setup() { //this sets the output pins

 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
 }

 void loop() {
 int ledcolor = random(1,16); //this randomly selects a number between 1 and 15

 switch (ledcolor) {

 case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
 analogWrite(11, brightness);
 brightness = brightness - fadeAmount;     break;
 case 2:
 digitalWrite(10, HIGH);
 delay(a);
 digitalWrite(10, LOW);
 break;
 case 3:
 digitalWrite(9, HIGH);
 delay(a);
 digitalWrite(9, LOW);
 break;

Research this, but I believe the Arduino library random function returns the same set of (pseudo) random numbers after each power up.  If this is a problem you can research if you can seed the Arduino random number generator.  However, finding a (always changing) starting seed (with out something like a RTC or Temperature sensor) is difficult in an embedded environment.

What are you actually trying to do? Are you trying to set random brightness on 4 LEDs? Or is the aim more complex?

@gbulmer my Goal is to have many different cases wich are going to be set of random with different LED effects for Simulation a firework on my Model Traintrack. and some of those fireworks should also be able to fade from 255 to 0.

In order to fade in and fade out LEDs you need to use PWM feature. And, specifically you need to use the analogWrite() function call. Also, you need to make sure all your LEDs are connected to PWM port pins.  Port pins which support the PWM feature for various Arduinos are listed in the above link.
In your code you might try replacing your 500ms delay with a count up followed by a count down loop.  Each loop should contain the appropriate delay and count up or down to the appropriate value.
For instance, you might try a 1ms delay and a count from 0 to 255 followed by a count from 255 to 0.  In both loops just before or just after calling the delay() function, place the call to the analogWrite() function and pass the counter value as the PWM duty cycle (LED brightness setting).
added later...
For example, you might try to see if this code works for the 1st case statement:
int brightness_level;

case 1: //if ledcolor equals 1 then the led on pin 11 will turn on etc.
  for(brightness_level = 0 ; brightness_level < 255 ; brightness_level++)
  {
    analogWrite(11, brightness_level);
    delay(1);
  }
  for(brightness_level = 255 ; brightness_level >= 0 ; brightness_level--)
  {
    analogWrite(11, brightness_level);
    delay(1);
  }
break;

thank you for the quick help i now have changed the Code but the led does not fade bevor the next case which is randomised beginns even tho i made the delay time longer. (see my changed Code pls) Mark

Not exactly what I had in mind.  In each case segment of code use two for loops. The first should count from 0 to 255.  The second should count from 255 to 0.  In each loop there should be a 1ms delay and a call to analogWrite passing the pin number and the current loop value.  Make sure the pin used for your Arduino supports the PWM feature!

would there be a possibility fopr you to do an example for me im not quite shore what u mean. and it should be only counting down from 255 to 0 and then the next random case Shell start.

I added an exmple to the answer. I haven't tried it so errors might have snuck in.  Try it.  Make sure pin 11 on your Arduino supports PWM.

thank you. Great now I know what u meant with the for loop.

ive just uploaded it onto my arduino but somehow the LED is not Fading ist flashing. what could i doo that it fades from 255 to 0n and then the next case starts? @st2000

Double check the code (I seldom write perfect code on the first go).  Also, you need to do this for all case statements, for all the LEDs.  I just gave you the fist as an example.

To make a completely "non blocking" system you need to change your thinking somewhat. Instead of thinking "A need to fade from X to Y" you instead need to start thinking "I am at brightness X at the moment. I want to get to brightness Y. What do I need to do to get there?".
For instance, you might have a loop() than contains a structure like:

My target brightness is Y
My current brightness is X
Is X equal to Y?

Yes:

Select a different target brightness to get to

No:

If my current brightness is below my target brightness then make it brighter.
Otherwise make it dimmer.

You can introduce a small delay to slow the fading down, or use millis() to only run that structure at pre-defined intervals (like BlinkWithoutDelay does) to get your desired fade speed.


text:
initial power output in the digital io pins of an Arduino controller
I am a newbie..  I am integrating Arduino controller with Matlab
I have connected my arduino DUE board in COM7. And I have also connected a DC Motor in one of the digital output pins (D3)
So when I just execute the matlab built in arduino function to initialise or establish a connection my motor runs for a second and then stops. I dont want my motor to run initially. Is there a solution or an alternative to do this.
a = arduino('COM7', 'Due');

Thanks in advance.

How have you connected your motor?

@Majenko I have just connected the motor to the output lines of the Arduino Motor Shield directly (using an external power source).

It sounds like there is a problem with the Matlab function, but I guess you can't fix that.  So here is my sledge hammer approach, put a PNP transistor in the supply line to the motor shield and control it from a digital port on the Arduino.  The digital pin will start up high and this will block the power to the motor, when Matlab sends the digital lines to low, power will flow, but you will have control.  You will need to ask someone about what transistor (and other bits) to use to achieve this, but there my theory.  Hope it works.


text:
Can I use ESP8266 and OV7670 to video stream on a web?
OV7670 image sensor, small volume, low operating voltage, providing all functions of a single chip of VGA camera and image processor. so I am using and ESP8266 to connect to internet and stream the video from the OV7670 on a web, can I do so?

a quick search on the internet show that the camera can be used with an arduino, so the answer to your question is yes

@jsotola, but with esp8266 too? and can it be streamed on web, because most of the people are using the ESP32, but i want to do it with ESP8266, ESP32 can host a websocket, can ESP8266 do so too?

@jsotola and i am working with a NodeMCU

if it can be done on an arduino, its 99.9% sure it can be done on an ESP8266 when using arduino framework - also, the fact that you know you can do it on an ESP32 increases the probability of success to 99.99% - the only thing left is for you to do it - networking on ESP8266 is more mature than on ESP32, so in the case of networking, if it works in 32 it WILL work on an 8266

@JaromandaX and can i use the esp8266 to stream the ov7670 on web?

@JaromandaX , can you please give me any schematic on how to connect the Ov7670 to the nodemcu, because in an arduino we usually use 6 analog pins, where nodemcu only have one, so any idea? , thanks!

oh, sorry for leading you astray - I didn't think to look up the connections for you, thought you would've researched that yourself - it seems you can not connect that to an ESP, as there are far more pins to connect than the ESP actually has - I thought the question you had was about the functionality of the ESP, not the camera

@JaromandaX, no problem, so i cant use the esp8266 with the camera right?, ESP32 is only the way right?, can you please tell me , i need to know this, thanks!

google search esp32 ov7670 and there are literally hundreds of working results - so, my guess is "yes"

@JaromandaX , yeah i know that it is working with esp32, but just wanted to know if i can use it with a cheaper microcontroller which is the nodemcu, but it seems you cant, thank you!

@JaromandaX I literally google search what you suggest, and funny to see I should google it recursively.

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


text:
Wire doesn't work between Uno & ESP32S & ESP8266
I think i've reached my limit. I can't get Wire to work between an Uno or ESP8266 or ESP32S. On the Uno I had them connected like SDA via Uno SDA -> ESP32 GPIO21 SCL via Uno SCL -> ESP32 GPIO22.
I also tried flipping them like this:

SDA via Uno SDA -> ESP32 GPIO22
SCL via Uno SCL -> ESP32 GPIO21

Connections are as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO4
SCL via ESP32 GPIO22 -> ESP8266 GPIO5

I also tried flipping them, as follows:

SDA via ESP32 GPIO21 -> ESP8266 GPIO5
SCL via ESP32 GPIO22 -> ESP8266 GPIO4

I have present a 4.7 kOhm pull-up resistor from SDA and SCL to +3.3 V.
All these combinations led to nil result on I2C bus scanners. I tried 5 scanners and 3 Wire libs. I tried having the ESP32 as slave because I heard the ESP8266 won't work as slave. I know I'm doing something wrong but can't figure it out, I've been at it all day.

the esp8266 and the esp32 Wire library supports only master. so you can't make them communicate

That is unforturnate. I believe stickman is working on a lib that supports slave.

sorry, the esp Wire libraries support slave mode, but it is experimental and doesn't work in most cases

In https://github.com/espressif/arduino-esp32/tree/master/libraries/Wire/examples they provide examples of master, slave, and scan.

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


text:
LB1847 stepper controller :how to connect to grbl atmega based board with step ,direction,enable , limit?
I like to use an LB1847 chip with stepper motor "both salvaged from old copier". I made a GRBL AtMega board, this board gives step, direction, enable and limit leads.
So I tried to find the corresponding pins on the LB1847, but the data sheet only shows enable1 and enable2 pins and phase1 and phase2 pins?
So how can I connect the step and direction and enable pins of AtMega to these pins of LB1847?
There are other logic pins on LB1847 chip to control current and decay.
If the data sheet is required i can upload it.
Thanks in advance

Please provide a link to the datasheet

Link to datasheet: https://www.onsemi.com/pub/Collateral/LB1847-D.PDF

It seems that most people use an Arduino CNC Shield to connect their Arduino Uno (running GRBL software) to the drivers of the stepper-motors. Via Google you find plenty of them, for example: here and here. The schematics of the latter example are published here. You could use the information from this schematic to make your own 'interface' between the Arduino and the LB1847 driver chips.


text:
Light Sensor - how to wait for specific setting then continue on Leonardo?
I have an analog light sensor working on my Micro Pro Leonardo board. I want to reach a part of my code which include keyboard presses where it monitors to see when an LED flashes and then continues the code from there.
Could someone give me a code example of how I can do that?
Currently I'd have something like....
  Keyboard.write(KEY_RETURN);
  delay(800);
  Keyboard.write(KEY_TAB);
  delay(150);
  Keyboard.write(KEY_TAB);
  delay(150);
  Keyboard.write(' ');
    }

//Code here to wait until LED flashes, registers as 30 or less on the light sensor. Then carry on with code below once this happens

  BootKeyboard.press(KEY_LEFT_GUI);
  BootKeyboard.press('r');
  delay(40000);
  BootKeyboard.releaseAll();

etc
I know the light sensor is AnalogValue = analogRead(A0); and I assume it's some kind of "If" statement which loops until the value because less than what is defined but have no idea how this would be written.

Generally you want to avoid delay, and avoid waiting until some external event happens. Both of those things completely lock up the controller until the condition is satisfied. Instead you usually want to check state flags in your loop function, and/or use millis() to see if enough time has transpired.

I know but for a beginner with a script which has about 150 button presses that all have specific and different wait times between each key press, it seems the easiest way to do it. At some point I will revisit the code so I can add a pause button if required, but at the moment it's not the question in hand.

One method:
while (analogRead(A0) < setting){
// sit in this loop taking readings until get one that is >= to setting
}

Thanks @CrossRoads i'll give this I shot, I read it should be a while setting and that < would be used with my number but didn't know how to actually structure this into a line.


text:
Double precision floating point operations using Arduino
Today we were programming something in university which dealt with really large numbers (even larger than unsigned long) and we had to create a code that broke the  numbers into an array and performed operations on them.
I know that an Arduino is an 8 bit MCU, but I was wondering if similar approaches could be used to do 32 bit double precision floating point operations (or even better,  i.e quad precision, etc) using the Arduino (e.g. create a quad precision calculator or similar applications).
I know it sounds silly or similar to a brute force method, but I'm really curious if it's possible to do such things.

Anything is possible if you have the programming skills. Natively the highest precision Arduino supports is float. Anything more precise you will have to code your own support for from scratch. Or there's Nick Gammon's Big Number library for massive integer use.

Note also that double precision is actually 64 bits (with 52+1 bits in the mantissa). For integers, avr-gcc natively supports int64_t and uint64_t.

The source code for float handling in AVR could be a starting point. The compiler back-end for AVR might need changing so that true double literal numbers could be used in sketches. https://github.com/vancegroup-mirrors/avr-libc/tree/master/avr-libc/libm/fplib

Thanks everyone. I'm a bit busy but I'll try to come up with some sort of code myself. I'll ask more details if I couldn't figure something on my own, thanks.


text:
Forbidden characters in TCP/IP
I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...)  I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.
By the way,
I'm using this to write to the server, and I work with the standard WiFi Client library
char arr[255]
for(int i = 0; i < 255; i++){
   arr[i] = (char)i;
}
client.print(arr);

Nodejs File:
// Load the TCP Library
net = require('net');

var mysql = require('mysql');

// Keep track of the chat clients
var clients = [];
var uploadCounter = 0;

initMySQLConnection();

// Start a TCP Server
net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " connected\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(">> " + data, socket);

        uploadData(data);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " disconnected.\n\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // Don't want to send it to sender
            if (client === sender) return;
            //client.write(message);
        });
        // Log it to the server output too
        process.stdout.write(message)
    }

}).listen(10101);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 10101\n");

var connection;
function initMySQLConnection() {
    connection = mysql.createConnection({
        host: "host",
        user: "user",
        password: "pass",
        database: "database"
    });

    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
        }
    });

    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                    // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

    setInterval(function () {
        connection.query('SELECT 1');
    }, 60000);
}

function uploadData(data) {
    data = String(data);

    console.log("Package Length: " + data.length);
    console.log("GOT ASCII CODE: ");
    for (var i = 0; i < 255; i++) {
        console.log(data.charCodeAt(i));
    }

    //upload Code
}

what does this mean? ... I don't get any usefull data out of it  ................ what are you expecting for ASCII-Code (0,1,2,3...)?

The print function takes an array of characters as zero terminated c-string. It prints until a byte with value 0. You have zero at arr[0] so it is an empty string.
To send bytes, write function is used. The print functions convert parameters to text or expect text as zero terminated char array.
In your case it should be client.write(arr, length); where length is the number of bytes you want to send from the buffer arr.

now I get values from 0-127 but all above is 65533. so the error seems to be in my nodejs file, i will add it above

ASCII code are only until 127. why do you read it as String and chars?

Doesnt the extended ascii code go until 255?

tell it to data.charCodeAt(i) :-)

So you mean without the data = String(data)?

try ArrayBuffer


text:
Power Arduino with 12V while using Serial Communication over USB
I'm going to build a 8x8x8 Led RGB Cube, therefore I will need a lot of Power which the arduino can't handle, so I'm using a 12V 20A (I know 20A isn't necessary but I had one laying around).
So the question is, is it possible to power the arduino over the Vin Pin with the 12V and program / communicate over serial connection in the same time? Like a real time programmed RGB LED Cube.

simulate this circuit – Schematic created using CircuitLab

What kind of LED's require 12V?

I'm now starting to doubt what I though about Arduinos.
If you are using a 12V PSU to power the Arduino, you are only going to get 5V out of the vOut pin.  The 20Amps you are supplying isn't going to come out either, all you'll get is ~300mA from the vOut or ~20mA from the digital pins. This is because of all the regulators.
If you want to get the Arduino to switch LEDs on and off from another source you are going to need transistors.  This will let you switch different voltages and higher currents.


text:
I2C device responding, but data is nacked
I'm working on a project where I have to communicate to several devices over I2C using a Genuino 101. Now I'm trying to get data off the bus but wire.available() stays at 0, even though my trace clearly shows there's data being sent.

with the following timings

Because the wire is never available my readbuf will always be empty.
Rdbuf[0] is: 0 Hex is: 0
Rdbuf[1] is: 0 Hex is: 0

I'm using the following code to read from the I2C bus.
void i2cRead(unsigned char device, unsigned char memory, int len, unsigned char * rdBuf) {
  ushort memstart = memory;
  bool available = true;;
  while (len > 0 && available) {
    available = false;
    ushort blockSize;
    /*If the number of bytes is smaller than the block size, read that size*/
    (len < RD_BLCK_SIZE) ? blockSize = len : blockSize = RD_BLCK_SIZE;
    Wire.beginTransmission(static_cast<int>(device));
    //send i2c START command
    Wire.write(memory);
    //Write memory address
    Wire.endTransmission();
    //send i2c STOP command
    Wire.requestFrom(static_cast<int>(device), blockSize,true);
    //Request blockSize bytes from the device
    /* for every byte in the response add that byte to the read buffer */
    while (Wire.available() && (len != 0)) {
      available = true;
      rdBuf[memory - memstart] = Wire.read();
      memory++;
      len--;
    }
  }
}

I'm not quite sure what I'm doing wrong, any help would be much appreciated.
Edit:
Below is an image of the current (minimal) setup. On the left there's the board with the ADC and multiplexer visible.

The third set of wires goes to my protocol analyzer.

Since this has been reopened i figured i'd post what the problem was, in the end and what i did to fix it.
it turns out, that even though the documentation of the Curie tells us to apply a level shifter for i2c communications, this level shifter is already in-place on the genuino 101.
skimming over the documentation of the 101, i had overlooked this.
The fix, in the end was removing the level shifter.

You want to get the resulting code working, but you should do small minimal tests.
Start with the i2c scanner.
Connect only one sensor, and if it is detected, add more sensors.
How long are the wires, and what is the value of the pullup resistors ?
Perhaps you have too many modules with sensors, and the total pullup value it too low. The I2C bus is specified for maximum 3mA pull down current.
Do you have a more common 3.3V Arduino board ? For example the Arduino Due or the Arduino Zero ?

hey jot, i have the code working on a different sensor, i2c scanner gives me all the sensors, and i can sucessfully read these sensors. the only difference here is that i have this sensor connected via a logic-level converter, converting the 3.3v signals into 5v signals.
i have an arduino uno i could test with, but this is part of a bigger project, in which we're using the bluetooth component of the 101.
the wires are all 30cm DuPont wires,  they're pulled up to 5v with 10kOhm resistors

The I2C bus is 3.3V, with a level shifter is for a 5V sensor ? Did you connect the high side (sometimes called HV) to the sensor side, and did you apply the 3.3V and the 5V to the level shifter ? Use seperate wires, not a flat ribbon cable. When SDA and SCL are next to each other in a flat ribbon cable, then they cause crosstalk. The i2c scanner detect a sensor by a ACK to its I2C address. Then you should be able to get that same ACK in a small test sketch. Perhaps the sensor has to be woken to be able to return data ? Is that a normal sensor, or a microcontroller with clock puls stretching ?

The sensor i'm currently trying to reach is a 10-bit adc, so far it's always just worked when we try to get data from it, in the packet log you can see that it responds with valid data.
i'm currently using a adafruit level shifter on a breadboard. 3.3v peripherals and the 101 on one side, and my 5v peripherals(Io expander/adc)  on the other.
currently the sda and scl are next to eachother on the breadboard, ill try with a few pins in between to see if crosstalk is the issue, a raspberry pi connected on the 5v side can talk to all the periperals, so i believe the circuit ought to be fine

A Raspberry Pi is 3.3V and it must be connected to the 3.3V side of the I2C bus. And you did apply 3.3V and 5V to the level shifter ? You really should test the problem with the absolute minimum. Remove everything that is not needed from the I2C bus and make a very small test sketch. Perhaps the timing of the Arduino 101 Wire library is in conflict the with sensor. You could, for example, add a delay of 1ms after Wire.endTransmission.

thats what i find odd, the raspberry pi works on both sides, but the genuino works on neither.
i'll do a test with the bare minimum attached tomorrow and i'll see what's going wrong. thanks for your ideas so far


text:
Keep RTC time in a loop
I recently started a project with HC-SR04 sensors and RTC DS1302 clock. The idea is when a sensor detects an object, call and keep a timestamp (hh:mm:ss) all over the loop until Else If{} appears,  but I don't know how to.
#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
String inTime;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

   if (distance <= 4) {
    inTime= rtc.getTimeStr();
    Serial.println(inTime);

    }

    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");

    }

  delay(500);
}

Appreciate any help, thanks.

Check '{' and '}' pairs in your code.
void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance <= 4) {
        inTime= rtc.getTimeStr();
        Serial.println(inTime);

   }
} //<--- what is this little fella doing here?
    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");
    }

delay(500);
}

thanks, that's because my original code is too long and is normal miss or add some {}

Well, the machine will not accept your excuses. You must be precise here. Maybe you can try to split code into few files?
Also, look at your 'distance' variable. Its type is 'long'. After line
'distance = (duration/2) / 29.1; '  you are loosing what is after comma.


text:
Controlling DC motor speed?
I'm trying to control a DC motor through L293D motor controller

const int controlPin2 = 4; // connected to pin 2 on the H-bridge
    const int enablePin = 3;   // connected to pin 1 on the H-bridge

void setup(){

  pinMode(controlPin2, OUTPUT);
  pinMode(enablePin, OUTPUT);

  digitalWrite(enablePin, LOW);
  digitalWrite(controlPin2, LOW);

Serial.begin(9600);
Serial.println("Ready");
}

void loop(){
if (Serial.available() > 0) {
    int inByte = Serial.read();

    switch (inByte) {
    case '0':
  digitalWrite(enablePin, LOW);
   digitalWrite(controlPin2, LOW);
 Serial.println("OFF");
      break;
    case '1':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 50);
    Serial.println("CW slow");
      break;
          case '2':

  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 100);
    Serial.println("CW slow +");
      break;
          case '3':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 150);
    Serial.println("CW medium");
      break;
          case '4':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 200);
    Serial.println("CW fast");
      break;
          case '5':
  digitalWrite(controlPin2, HIGH);
    analogWrite(enablePin, 250);
    Serial.println("CW fast +");
      break;
    case '6':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 50);
    Serial.println("CCW slow");
      break;
      case '7':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 100);
        Serial.println("CCW slow +");
      break;
      case '8':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 150);
        Serial.println("CCW medium");
      break;
       case '9':
  digitalWrite(controlPin2, LOW);
    analogWrite(enablePin, 250);
        Serial.println("CCW fast");
      break;
}
}
}

It is working well except 1 to 5 are reversed:

1 should be the minimum speed
5 should be the maximum.

But it is back to front:

5 is the minimum speed
1 is the maximum speed

Any ideas?

Other than changing your case expressions?

So first thing, you should try to be more disciplined with your code formatting and the question...
FYI: it's best to use #define as it doesn't use memory for storing pin numbers... It's like Find and Replace in a text editor, this:
const int controlPin2 = 4; // connected to pin 2 on the H-bridge
const int enablePin = 3;   // connected to pin 1 on the H-bridge

Becomes this:
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

So this is the tidied up code, you can see the problem is a lot more approachable when the code is indented consistently, and good use of spaces and new lines is used...
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '5':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}

So your actual problem is that you need to reverse cases 1, 2, 3, 4, 5 to be 5, 4, 3, 2, 1...
There are two solutions:

Inelegant: would be to simply change the case numbers, they don't have to be in-order.
Elegant: copy and paste the code in each of the 5 cases about.

The result of option 2 is as follows, please feel free to confirm this is working?
#define controlPin2 4  // connected to pin 2 on the H-bridge
#define enablePin   3  // connected to pin 1 on the H-bridge

void setup () {
    pinMode( controlPin2, OUTPUT );
    pinMode( enablePin, OUTPUT );

    digitalWrite( enablePin, LOW );
    digitalWrite( controlPin2, LOW );

    Serial.begin( 9600 );
    Serial.println( "Ready" );
}

void loop() {
    if ( Serial.available() > 0) {
        int inByte = Serial.read();

        switch ( inByte ) {

            case '0':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 250 );
                Serial.println( "CW fast +" );
            break;

            case '1':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 200 );
                Serial.println( "CW fast" );
            break;

            case '2':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 150 );
                Serial.println( "CW medium" );
            break;

            case '3':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 100 );
                Serial.println( "CW slow +" );
            break;

            case '4':
                digitalWrite( controlPin2, HIGH );
                analogWrite( enablePin, 50 );
                Serial.println( "CW slow" );
            break;

            case '5':
                digitalWrite( enablePin, LOW );
                digitalWrite( controlPin2, LOW );
                Serial.println( "OFF" );
            break;

            case '6':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 50 );
                Serial.println( "CCW slow" );
            break;

            case '7':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 100 );
                Serial.println( "CCW slow +" );
            break;

            case '8':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 150 );
                Serial.println( "CCW medium" );
            break;

            case '9':
                digitalWrite( controlPin2, LOW );
                analogWrite( enablePin, 250 );
                Serial.println( "CCW fast" );
            break;

        }
    }
}


text:
How do I use a 5v/120v relay that is not mounted on a board
I bought an arduino kit, and it came with, amongst other things, a 5v relay to control 120-220v.
The relay is only that, there is only the 5 pin relay, and it's not on a board on which one can screw in the leads

I was wondering how I can use it..  i.e. how do I mount it somehow (especially since the leads are metric and most perf board is standard (or vice-versa)).
I don't mind soldering the 5v control leads from the arduino, but I'm not so sure about soldering or connecting 110v straight on the relay.  i'm worried about long term longevity.
I have soldered longer leads just to be able to fit it on a board for tests, but those are tiny, and aren't safe for higher voltage/current.
Any suggestions?
Thanks, Seb.

This question is not about Arduino, but DO NOT connect mains to the relay - this would violate all the basic safety rules.

What I did with a similar looking 'module' (An AC/DC converter), was to use a protoboard/perfboard. Some holes fitted in the existing holes, others I drilled with a small drill.
On the back you can solder the wires you need, so for the 110V wires you might use thicker wires than for the controls.
Than if you want to make it fancy, you add some terminal blocks to connect the external wires too. Terminal blocks looks like this:

thanks for the answer. so you're saying I should simply make the relay fit on a perfboard, then bring the 110v wires right to it. or make a bridge with actual 110v wires rather than soldering or smaller wires.  at this point is there an advantage to using a perfboard at all instead of simply soldering straight to the relay?  would it be to solidify the whole aparatus;  have some form of a structure?

well actually you do not really 'use'  the perfboard, only a fixed straight piece of material. So you also can use any other material; do not use the small wires from the perf board for 110/220V. The main reason to use perfboard, is you can have the relay fixed and also put the remainder of your (logic level) signals throught the perfboard. Or you can can use pin headers to 'mount'  the 'relay perf board' on top of the real circuit, and connect the 110/220V wires directly to the pins of the relay.


text:
Mesh with star topology
In my project I have an issue. I have more than 2 mesh network with Arduino + nRF240L01 with a star topology (one Arduino is master another 6 Arduino + nRF240L01 are the slaves likewise I can be able to have more than 2 networks).
So I want to communicate only with one mesh network but not to another. Is the different addressing enough to separate the networks? And I would like to have sample code as well.

Ideally you'd pick a different channel too - that way they won't interfere with each other on a physical level.

found this .... http://tmrh20.github.io/RF24Network/ .....  maybe you can use tree topology


text:
How to use millis instead of delay on Arduino for independent time intervals for two output pins
I wanted to use millis for the code below but stuck in between . can anyone help to change the given code to millis? Code here:
    void set(){
    digitalWrite(on, HIGH);   // turn the motor on (HIGH is the voltage level)
  delay(1500);
  digitalWrite(on, LOW);
  delay(ont);               //waits for given time
  digitalWrite(off, HIGH );    // stop the motor
  delay(500);
  digitalWrite(off, LOW );
  delay(offt);                  //wait for different

See https://www.arduino.cc/en/tutorial/BlinkWithoutDelay I see four different things. Use a counter from 0...3 and adjust the interval for each of the four situations. Can you give that a try and show a working sketch (so we can try your sketch). Do you have different pins for turning the motor on and off?

Here is the code for changing pin value without delay. Read it and try it.
#define on 2
#define off 3

//delay times
const unsigned int ont = {1500,  500};
const unsigned int offt = {500, 300};

//last millis
unsigned long last_tm_on = 0;
unsigned long last_tm_off = 0;

//position
byte pos_on = 0;
byte pos_off = 0;

void setup(){
  pinMode(on, OUTPUT);
  pinMode(off, OUTPUT);
}

void loop(){
  if(millis() - last_tm_on >= ont[pos_on]){   //check if millis() - last millis() is bigger than wanted time
    last_tm_on = millis();   //save last millis()
      if(pos_on == 0) digitalWrite(on, HIGH);
      if(pos_on == 1) digitalWrite(on, LOW);

      pos_on ++;   //add position
      if(pos_on > 1) pos_on = 0;   //check max position
  }

 if(millis() - last_tm_off >= offt[pos_off]){
    last_tm_off = millis();
      if(pos_off == 0) digitalWrite(off, HIGH);   // turn the motor on (HIGH is the voltage level)
      if(pos_off == 1) digitalWrite(off, LOW);

      pos_off ++;
      if(pos_off > 1) pos_off = 0;
  }
}

Matej, there is only one motor and you have two independent software timers with millis.

@Jot I thought, that on is one motor and off second. Lol


text:
12 V relay using Arduino
I want to control a 12 V relay using an Arduino 5 V signal, but due to some unknown reason the relay does not work. I am using a BC548 transistor as a switch for relay.
Please suggest where I go wrong.

issue aside, you need a flyback diode to save your NPN. Does the relay trigger if you feed the NPN +5v instead of a GPIO output?

I have added flyback diode in actual circuit forget to add in diagram.

yes the relay works when I give 12v to base

what about 5v, like the AVR would provide?

i didn't tried it but It only works when i give higher than 5v

It could be a lot of things then. I would swap the NPN for an NCHAN mosfet, preferably logic-level. I use the IRLZ44N in a lot of 3.3v projects, makes a great low-side switch.

Have you connected the grounds?

@Majenko yes i did.

If it's working with 12v on the input but not 5v, it sounds like the base resistor value
 (which is missing from the diagram) might be too high. A value of around 1k should ensure the transistor is fully switched on.


text:
How do I fill an empty array with the values from a sensor and compare it to another given array I filled before
I'm designing a safe lock of 4 digits, but the password is in terms of colors, I have 3 colors. we are obliged to use a grayscale sensor (SKU: SEN0147).
The assignment is as follows:
Write a program on Arduino that will be used as a safe lock.
Consider having 3 colors black white and grey. Black = 0, Red = 1 and White = 2.
• When  the microcontroller is  turned  on, the safe is locked. The Serial  Monitor should display:
“System is  online.”
• The combination lock should be saved in an array of integers called arr_code.
• The user has 3 trials to open the safe
• The system will wait for the user to enter 4 colors. To enter a color, the    grayscale sensor should be  place   on  top of  the desired color.  Once    ready   the push    button  is  pressed. Once released, the color   is  saved   in  another array called arr_user_code.
• Once 4    colors  are entered,    the system  should  test    automatically   if  the code    entered by
the user    is  equal   to  the code    saved   in  arr_code.
• If    the wrong   code    is  entered,    the serial  monitor displays:   “Wrong  Code.   Try Again.”
• If    the user    enters  the wrong   code    3   times   in  a   row the system  is  locked  and a   message is
displayed:  “System Locked.”
• If    the correct code    is  inserted,   the Led on  pin 13  is  turned  on.
• The   combinations    entered by  the user    should  be  displayed   on  the Serial  Monitor.
The Arduino program should  be  clear,  separated   into    functions   and documented.
The program I wrote is the following:
char led_pin = 13;
char pb_pin = 2;
int gs_pin = A0;
//the brightness of the flash light im using is giving 894 value so im using it for testing purpose
int arr_code[4] = { 894, 894, 894, 894 };
int arr_user_code[4];

int counter;
int Lock_Interval = 2500;

char trigger = false;
bool equal = true;
char led_state = false;

int Array_Compare(int *a, int *b) {
  for (int i = 0; i < 4; i++) {
    if (a[i] != b[i]) return 0;
    else return 1;
  }
}

void Button_Wait(int buttonPin) {//function to sense if button is pressed
  int curr_state;
  int prev_state;

  while (1) {
    prev_state = curr_state;
    curr_state = digitalRead(buttonPin);
    if (curr_state != prev_state) {
      if (curr_state == false) {
        delay(10);
        return;
      }
    }
  }
}

int GS_Value(int gsPin) {
  int gs_value = analogRead(gs_pin);
  return gs_value;
}

void setup() {
  // put your setup code here, to run once:
  pinMode(led_pin, OUTPUT);
  pinMode(pb_pin, INPUT);
  Serial.begin(9600);
  digitalWrite(led_pin, false);
}

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

  Serial.println("System Online");
  Serial.println("Please Enter Passcode:");

  for (counter = 0; counter < 3; counter++) {
    for (int i = 0; i < 4; i++) {//uploading user array with gs values
      Button_Wait(pb_pin);
      arr_user_code[i] = analogRead(gs_pin);
      Serial.print(analogRead(gs_pin));//printing values on monitor
      Serial.print(" ");
    }

    Serial.println(" ");

    for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
      if (arr_user_code[i] != arr_code[i]) {
        equal = false;
      }
      else equal = true;
    }
    if (equal == true) {
      Serial.println("System Unlocked");
      digitalWrite(led_pin, true);
    }

    else if (equal == false) {
      Serial.println("Wrong Passcode. Try Again");
    }
  }

  /*Array_Compare( arr_user_code, arr_code);
  if (Array_Compare) Serial.println("System UNLOCKED");
  else Serial.println("Wrong Passcode. Try Again");
  */
  if (trigger == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }
  delay(100);
}

I'm sorry for having a lot of functions not used and a lot of canceled algorithms by remarks but its my scratch. the issue is that my program is always giving me a wrong passcode even if its correct.
Can you help me find the problem please? Thank you in advance.

Are the values you see printed over Serial correct?

yes i set the password according to them

Since you have else return 1; in Array_Compare this will terminate always after the first iteration.. A return 1; must be placed after the for loop.

@MaximilianGerhardt you are correct, but the code isn't calling the function.

@RamblinRose true. A few more remarks.  In the code arr_user_code[i] = analogRead(gs_pin); Serial.print(analogRead(gs_pin)); the value in the array and the one printed out can be different since you're taking 2 different ADC measurements (is that even what you want)? You should print arr_user_code[i]. Also then before comparing it  to the other array you should print out its full contents. Then you'll see if there is a difference in the values.

@RayanHamadeh what is the purpose of the outermost loop on "counter"?

@RamblinRose the outermost counter is to block the whole system if the code is entered wrong 3 times

@MaximilianGerhardt, in this case, the value printed on the Serial  Monitor will be a random number 30 thousand something which isn't the value from the sensor for sure

@RayanHamadeh a analogRead returned a value beyond 30K? Should be 0-1023. Can you edit the question to show the current code that you're running?

Since you are trying to distinguish tree different colours, I assume you are using SEN0147 in analog mode. That means the sensor output is between 0-5V. I do not believe that this will always be exactly a value of 894.
I suggest to change your comparison check in a way not to check if values are identical but to check if values are in a certain range. (additionally to all the answers @RamblinRose already suggested)
Here is a modification of the comparison loop of @RamblinRose with the change I propose. Check with different values of threshold, starting from high to lower values.
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {

   int threshold = 500;
   int temp;
   for (int i = 0; i < 4; i++) {
       temp = a[i] - b[i];
       if (abs(temp) > threshold)
       return 0;
   }
   return 1;
}

Your program has a lot of issues, but the main problem revolves around
if (trigger == false)

The code initializes this to false and the logic never alters the value, thus the program will always indicate "System LOCKED!"
It looks like you've mixed the variables trigger and equal.  Get rid of the trigger variable and use equal.
if (equal == false) {//for locking the system
    Serial.println("System LOCKED!");
    while (1) {
      Lock_Interval = Lock_Interval * 2;//CHANGE TO MINUTES LATER ON!!
      delay(Lock_Interval);
      return;
    }
  }

I recommend a different variable name to equal, such as "unlock", as it makes clear the use of the variable.  Also, initialize variables such as "equal" at the beginning of loop().  Good luck.
EDIT
Your comparison check in loop() is valid.  However if you have to use Array_Compare, here is the fix.
// returns 1 if equal, 0 otherwise.
int Array_Compare(int *a, int *b) {
   for (int i = 0; i < 4; i++) {
       if (a[i] != b[i])
          return 0;
   }
   return 1;
}

Then in loop, remove your local comparison loop with
//for (int i = 0; i < 4 && equal; i++) {//testing if passcode is true
//  if (arr_user_code[i] != arr_code[i]) {
//      equal = false;
//  }
//  else equal = true;
//}

equal = Array_Compare(arr_user_code, arr_code);

I'm not comfortable writing your program for you, this is not a coding service.

but this doesn't solve the issue concerning comparing arr_user_code and arr_code

@RayanHamadeh the code is comparing the arrays in the loop() function, and altering the 'equal' variable according to the comparisons made.


text:
invalid pure specifier (only '= 0' is allowed) before 'int'
#include <PixySPI_SS.h>
#include <Pixy.h>
#include <Adafruit_MotorShield.h>
#define X_CENTER        ((PIXY_MAX_X-PIXY_MIN_X)/2)
#define Y_CENTER        ((PIXY_MAX_Y-PIXY_MIN_Y)/2)

Pixy pixy;
 int TrackedBlock(int n) =
{
 int trackedBlock=0;
 float maxSize=0;
  for (int k=0;k<n;k++)
  {
    float newSize= pixy.blocks[k].height * pixy.blocks[k].width;
    if (newSize>maxSize)
    {
      maxSize=newSize;
      trackedBlock=k;
    }

  }
   return trackedBlock
}

For some reason the code returns the error message in the title every time I try to compile it. I can't really find any issues online that's the same as my error. Any help is appreciated!

What happens if you remove the "=" from this "int TrackedBlock(int n) = " and add a ";" at the end of this "return trackedBlock"?

yeah, because int TrackedBlock(int n) =  is not how you write a function in C

Look, this isn't a forum. Please post your answer using the "answer" box. Then it can be accepted. The only answer here right now is a "thanks" for your comment. This is totally subverting how Stack Exchange is supposed to work.


text:
Bit Bang I2C with port manipulation on AtTiny84: new pinout doesn't work
So I am trying to understand bit banging and port operations. I'm developing a breakout board with an ADXL343 IMU read by an AtTiny44 via i2c. I adapted this code from MIT's How To Make Almost Anything which I also explained a bit here in this thread. Like I mentioned there, I got it working with the MIT code, and now have a basic sketch that works for my original board, where I define the pins like this.
#define SCL_pin (1 << PB0)
#define SCL_pins PINB
#define SCL_port PORTB
#define SCL_direction DDRB
#define SDA_pin (1 << PB1)
#define SDA_pins PINB
#define SDA_port PORTB
#define SDA_direction DDRB

UNFORTUNATELY, I designed and fabricated a new board where the SCL and SDA pins are now PA3 and PA2 respectively. I tried to adjust the sketch by changing the defines to all be PORTA, DDRA, etc like this:
#define SCL_pin (1 << PA3)
#define SCL_pins PINA
#define SCL_port PORTA
#define SCL_direction DDRA
#define SDA_pin (1 << PA2)
#define SDA_pins PINA
#define SDA_port PORTA
#define SDA_direction DDRA

Problem is, the tiny44 ceases to read from the IMU with the new pinout. The input/output functions in the program look like this:
#define output(directions,pin) (directions |= pin) // set port direction for output
#define input(directions,pin) (directions &= (~pin)) // set port direction for input
#define clear(port,pin) (port &= (~pin)) // clear port pin
#define pin_test(pins,pin) (pins & pin) // test for port pin

The pi I am using is getting the initial values of data[], so I know it is communicating fine with the tiny44
I realize the pin mapping changes depending on the core I'm using. I don't think that impacts the way the SDA_pin and SCL_pin are defined, because defining them PB0 and PB1 worked... Plus I tried about every pin name possible.
I have also tried the Damellis and Drazzy cores, and neither is working for me.
I tried using a few BitBang libraries like SoftWire, but with no luck.
I have tried a few boards as well, so I don't think it's hardware related.
I don't know what else to try. Any help would be much appreciated! Thanks!!

You could try this variant https://github.com/mikaelpatel/Arduino-TWI and https://github.com/mikaelpatel/Arduino-GPIO.

Thanks Mikael! It looks like the TWI won't work on the Tiny44 because the microcontroller only has a USI(which allows TWI, but called differently)

There is a software, bitbang, version https://github.com/mikaelpatel/Arduino-TWI/blob/master/src/Software/TWI.h.

A USI version can be found in Cosa (another Arduino core), https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/USI/TWI.hh.

As you have changed the pins you will have to use bit-banging as the USI module is fixed to specific pins.

yeah my plan was to use bitbang between the tiny and the IMU, and then hardware TWI for max speed with connection to Rpi. The code I posted is for the ports/pins for the bit-bang part.


text:
RS485 Arduino Communication Issue
Friends, I am trying to achieve half duplex communication between two Arduinos using RS485 Protocol. The hardware I am using is a MAX485 module and an Arduino Uno. I am using the SoftwareSerial library for Arduino, but I am not be able to transmit data from sender to receiver. The length of the wire between MAX485 modules is 1 meter.
My question is, what wrong I am doing here, please guide me.
The code:
SenderDevice
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);

String strCmd;
int counter;

void setup()
{

 Serial.begin(9600);
 mySerial.begin(9600);

 pinMode(5, OUTPUT);
 digitalWrite(5, HIGH);
 counter = 0;

}

void loop()
{

  counter++;
  strCmd = "Counter" + String(counter) + "$";
  Serial.println("Sending " + strCmd);
  mySerial.print(strCmd);

  delay(10);
  mySerial.flush();
  Serial.flush();
  memset(&strCmd, 0, sizeof(strCmd));
  delay(2000);

}

ReceiverDevice
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7);

String strCmd;

void setup()
{

 Serial.begin(9600);
 Serial.println("ready");

 pinMode(5, OUTPUT);
 digitalWrite(5, LOW);
 mySerial.begin(9600);

}

void loop()
{

   while (mySerial.available() > 0) {

        char c = mySerial.read();
        if (c == '$') {

           Serial.println("Received " + strCmd);
           memset(&strCmd, 0, sizeof(strCmd));

        } else {

          strCmd = strCmd + c;

        }

  }

}

My Wire Connections are :

(Both Sender & Receiver Device)
Arduino Uno 6 -> Max485 RO
Arduino Uno 7 -> Max485 DI
Arduino Uno 5 -> Max485 DE
Arduino Uno 5 -> Max485 RE
Arduino Uno 5V -> Max485 VCC
Arduino Uno GND -> Max485 GND

Sender Max485 A -> Receiver Max485 A
Sender Max485 B -> Receiver Max485 B

I have quite bad experience with using the software library using MIDI which has a very low baudrate; I advise to at least try with the hardware UART (RX/TX) to see if that solves the problem.

Do you have GND connected between sender and receiver?

@MichelKeijzers : I am already using the hardware UART for someother reasons.

@Matej : I have tried connection the ground of both devices too, But it did not work.
In real time my application is going to be 15 meters away.

I only said to try it, so you know if the problem is in the library/software; if it works with a hardware serial, than at least you know your code is ok.

@Michael : my general rx-tx communication is working. After searching a lot on web i have found this code. Actually modified the example code of the library.

@javabee I never had problem with it and I don't see anything wrong with your code or wiring. Do you have another modules to test it?

@javabee "I have tried connection the ground of both devices too" you absolutely MUST connect ground of both devices. Senders and receivers data lines are flipped? And do you have an oszilloscope to monitor the transfer? Timing is always critical in proticols that don't use a clock line

@Matej : I purchased new Arduinos and Max485 yestrday. Its not also working too.
I don't know why this simple piece of code is not working. Please someone help me.

@SimSon : I dont have oszilloscope. what other way can you suggest to debug.

@javabee So modules are all right. You can try this code:   https://github.com/matrn/RS485protocol    it worked for me but I am not sure if problem is in code. Also as Sim Son wrote you must have gnd of both devices connected.


text:
Using TMRpcm object, why is the SD Card failing to be found by arduino?
I am using this micro-sd card reader, and my wiring configuration is as follows (double and triple checked):
3.3v goes to 3.3v on the Arduino UNO
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 4 on Arduino UNO

When I run the 'basic' example from the TMRpcm library, everything compiles and uploads properly with no warnings. Looking at the Serial Monitor, I get "SD Fail", which, according to the comments, means that the SD card failed to initialize. The card is present, and works in my computer. Do I have something wired wrong, or is there another issue?
EDIT
I have tried using a different pin for D3, and changed the code as needed. Still no luck.

Without a ton of knowledge about your situation, it seems like the SD card isn't the proper format, the reader is bad, or the card isn't in all the way. Can you try a different card? Is the read only switch enabled?

The card is in all the way. It clicks into place. I don't see a read-only switch on the card or the reader. The reader may be bad, but the LED on board the reader comes on when the arduino is plugged in, which leads me to believe that is not the case. I don't have a second card on hand at the moment. What format does the card need to be in? FAT32?

As far as I can tell, FAT32. Also, a SDXC might be a problem here...

Didn't know what that was before now, but it looks like they're all larger than 32 GB. Mine is 8. I'm fairly certain it's FAT32. I had trouble with a FAT32 header it was trying to pull in earlier with the wrong path.

See  https://github.com/greiman/SdFat
Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.

Check if the reader is plugged in correctly. This will give a PEBKAC error.


text:
How to delay so that LED stays on a bit longer?
I have a circuit with a shift register which controls 8 LEDs: http://node-ardx.org/exercises/5. In code, I created a function cycle() cycle through each LED one at a time, but this occurs too quickly on the board. How can I add a delay inside the loop so that each LED stays on for 500ms?
Here's my code:
var five = require("johnny-five"), board, shiftRegister;

board = new five.Board();

board.on("ready", function() {
  shiftRegister = new five.ShiftRegister({
    pins: {
      data: 2,
      clock: 3,
      latch: 4
    }
  });

  var bytes = [
    00000001,
    00000010,
    00000100,
    00001000,
    00010000,
    00100000,
    01000000,
    10000000,
    00000000
  ];

  function cycle() {
      for ( var i = 0; i < bytes.length; i++ ) {
          console.log(bytes[i]);
          shiftRegister.send(bytes[i]);
      }
    }

  this.repl.inject({
    sr: shiftRegister
  });

  cycle();

});

The answer is already provided in the article.
  var i = 0;
  function cycle() {
    console.log(bytes[i]);
    sr.send(bits[i]);
    i++;
    if( i<bytes.length )
      setTimeout(cycle, 300);
  }

I don't want the cycle function to repeat. I do want to delay just after sending the new byte to the register just after changing the LEDs.

See edit above. It now only does one cycle.

Insert a delay of 500ms?
function cycle() {
    for ( var i = 0; i < bytes.length; i++ ) {
        console.log(bytes[i]);
        sr.send(bits[i]);
        delay(500);
    }
  }

JavaScript doesn't have a function called "delay".

Good job that's not the language we're discussing then!

Which variant of C or C++ is the "var" keyword supported in?

In that case you'll want this I imagine.

This isn't working for me. When I run the changes above, the REPL reports delay is not defined. I'm running Johnny Five v0.8.32. Where is delay defined by Johnny Five?


text:
How to read a Text file from server and store to a separate variable?
I am working on reading a text file from the server, using http://arduino.cc/en/Reference/GSMClientConnected. It gives me this code:
char path[]="/asciilogo.txt"

I want to store only the contents that are inside the text file to a variable (String). But client.read(); only reads a single character at a time. Also, it takes all the HTTP, GET, TIME parameters together.
How to store only the contents that are present in the text file to a string variable?

Here is what I found:
You need to have a special character like  "*" (a delimiter), from which important data will flow through.
char z = '*';
int s=0;

void setup()
{
  // usual initialization
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    // Serial.print(c);
    if (z == c)
    {
      s=1;
    }

  if(s == 1)
  {
    int i=0;
    k[i] = c;
    i=i+1;
    // Serial.print(k);
  }

  place +=k;

  Serial.print(place);

  }

.......
}

that'll work but you have to declare i outside of the loop() because the way it is now, it'll always be 0.


text:
relay working problem
I am using circuits.io with Arduino. my program is to blink the led with 2 seconds delay. The led in the circuit blink according to program but the bulb does not blink. I am very weak in electronics. This is what i starting to learn from the scratch. the problem here is the bulb doesnt blink according to the program. which is meant to blink. i have uploaded the circuit image below.. . thanks in advanced.

you show no ground connection between arduino and relay, does this represent what you have?

this layout... use the schematic editor.

In the circuit.io layouts that I have seen, they do connect power to the Arduino board.  You have yet to do this. (There are other problems, but let's start with the obvious one 1st.)

Sorry, I downvoted this, because even after three hours of being pointed to a lack of clear schematic, you haven't tried to improve your diagram. Thus, no answer can be given, and your question holds no value in itself.


text:
Strange power comsuption into sleep mode
I've finished my project and now I'm measuring the current but there is something wrong. I'm using an Arduino Pro Mini board and the LowPower library but the consumption is about 3.5 - 5 mA and not less than 500 uA (the board remains into sleep mode almost all the time).
When I began to work with the board its LED was removed but I think that this work was not made correctly. How can I check that LED was removed correctly?
Thanks to all.
EDIT1: The strange power consumption is not associated with board's LED.
EDIT2: @Gerben has suggested me to review the state of SPI pins connected to the board. I use in this project a SD card module and GSM/GPRS module but the guilty of this excessive power consumption is the first. Then I've disconnected all SD card module's pins and then I get about 60 uA, so the problem is on those pins but I can't reduce the power consumption. SD card module pins are 10,11,12 and 13 so I've used statements like digitalWrite(10, LOW), digitalWrite(11, LOW) and so on after reading/writing on the SD card but it is useless.
EDIT3: I've decided to upload a representation of my project using Fritzing. The external modules are not identical but they contain the same pins.
General view of the circuit:.
Detail of the connections:

I use these external components:

SD card module
A6 GPRS/GSM module

In my project there are some important details:

GPRS module is powered individually. The other battery is dedicated to power on the Arduino board and the SD card module.
Batteries are 6v.
Transistors base are controlled by 2 and 3 digital pins respectively.
The 8 and 9 pins of the Arduino board act like RX and TX pins using AltSofSerial.h library.

See Power saving techniques for microprocessors for some tips. I doubt it is anything to do with the non-existent LED.

How would you remove an LED in such a way that the missing LED draws 5 mA? That doesn't make any sense. Either it is still there, or it is not there. If the removal shorted the pins then you would have a lot higher current drain than 5 mA.

@NickGammon I think that the problem is the SD card module because if I disconnect the CS, DI, DO and CK pins then the consumption is around the 60 uA.

@PinaGamer did you just disconnect those pins or also the VCC and GND pins of the SD card module? If you didn't, try leavinf those pins connected: if it is a module it should have an onboard converter and maybe a level shifter which remain powered (if it is the case, power it through an arduino pin and turn it off when not needed). If you only disconnected those pins and left VCC and GND connected, see with an oscilloscope if the status is changing. If it isn't, try measuring also the current sinked by the SD card (module) when in sleep

@frarugi87 I've only disconnected the pins that I mentioned above so VCC and GND remain connected. So do you recommend me remove the transistor and activate or deactivate the SD card module using a digital pin?

@PinaGamer what is the transistor you mentioned? I suggest you to 1) try measuring the current flowing in the SD module only when in sleep. 2) leave the SD module connected, but disconnect only VCC and measure the whole current. 3) post a link to the SD module you are using; maybe some other ideas can come.

@frarugi87 The consumption in your proposed cases are: 1) 4.8 mA 2) 3.9 mA. The SD card module is this.

Wait, you blocked the ground of the modules?? If so, try writing a HIGH value on all the SD card pins, not LOW (otherwise you are trying to power the device through the digital pins). And.. Consider using a PMOS instead to block the VCC pin...

digitalWrite(10, LOW) or better digitalWrite(10, HIGH) don't work if you don't disable SPI first.

@frarugi87 I don't understand why I need HIGH value instead of LOW value to switch off the SD card module. Why do I need a PMOS transistor?

@PinaGamer because if you switch off the transistor, every node on the SD should float up to VCC, the only remaining connection. If you apply a 0V on any pin, you put a differential voltage over the board, thus turning on something. Try with a high value (so everything is at VCC) or put the pins in high impedance (aka input mode). A PMOS transistor (or a PNP) is used to interrupt the VCC pin instead of the GND one, so you can keep the grounds together (it's usually a better approach, since usually grounds are designed to be together)

@Gerben Do you recommend me to put digitalWrite(10, HIGH) to enable the internal PULL-UP of this pin? Why? With this statement current goes down to 80 uA.

See frarugi87's comment. Nothing to do with pull ups

@Gerben frarugi87 suggests me put the pins in high impedance so in void setup() I've put digitalWrite(10, HIGH)

digitalWrite(10, HIGH) doesn't mean high impedance. High impedance if when you change the pin to an INPUT. So pinMode(10, INPUT). But I was referring to him saying you should set the pin to Vcc not GND. Also there is no point in doing this in setup. But please, re-read all the comments, cause I feel you are totally missing the points we are making.

SOLUTION [by OP]
My problem was that the SD card module was consuming when it was controlled by a transistor and my Arduino board was into the sleep mode. So I wrote into the void setup() the digitalWrite(PIN, HIGH) statements where PIN represents all pins connected to the board that belong to the SD card module (DI, DO, CS, and CK pins), to enable the internal resistor of that pins. Then, I checked the power consumption and I reached less than 100 uA.

If you physically removed the LED make sure the pads for it aren't shorted together by old solder. If they aren't then you removed it correctly.
However: 5mA may be a perfectly reasonable current consumption for your project. Without seeing a full schematic and analysing your code it's impossible to say what kind of current you would expect to see.

I've upload a simple project like this: #include <LowPower.h> void setup(){  LowPower.powerDown(SLEEP_TIME, ADC_OFF, BOD_OFF); } void loop(){ }
And the consumption is a bit less than 3.5 mA. So I think that the code is not the problem

Like what? Also, how are you powering the board?

I power the project using 4 AA batteries with 1900 mAh.

TBH I'd be less worried about the 5mA consumption that I would be by the 30% power loss from the linear regulator. What else is connected to the board?

Interesting... I've isolated the board, I've measured again the current and now I'm getting 60 uA. So the problem is in the circuit... There are connected an SD card and GSM modules both controlled using transistors.

@PinaGamer If you remove power using a transistor, you must also make sure not the the SPI/UART pins are HIGH. Otherwise power will flow into the modules via this pin (and the clamping diodes in the modules ICs).

@Gerben I use AltSoftSerial.h library to communicate with the GSM module using digital pins 8 and 9 and pin 10 to begin the SPI communication with the SD card module but there is no any statement like digitalWrite(8,HIGH) or something like that.

@PinaGamer I'm not going to read all the library code to figure out if an output is set to HIGH while idle. You can do this yourself. Or you can do it the easy way, and while the arduino is sleeping, disconnect the modules, and use a multimeter to see if any of the output-pins that where connected to the modules read 5v. I recently did a project where I had to disable SPI and set the MOSI pin low, before powering down the device connected to the SPI bus.


text:
How are errors (not related to syntax) managed in arduino and in the AVR architecture in general?
I was just curious about how the AVR architecture manages errors that would cause a regular desktop program to crash. I'm talking about logical errors for example math problems that are undefined. Such as division by 0 and getting a square root of a negative number. At first I was expecting that by giving an error to the AVR chip it will just return 0. But I ran this program:
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

and got this output:
4294967295
0

After this I got really confused. Why would the result variable take the maximum value of an unsigned long? Since I declared an int the micro controller must have dedicated 2 bytes of dynamic memory to this variable but apparently it somehow managed to get additional 2 bytes to store the data. Could this mean that the AVR chip can corrupt data in other memory locations while allocating new data for the variable that just was fed a undefined in to it? Okay maybe the AVR chip just sets any mathematical nonsense to 4294967295. But no in the example of getting the square root of -10 we see that the value became 0. Although this is probably a function processed by some library so maybe there is some kind of protection against these errors. Also, I tried to run the program above but with a byte variable for the result instead of int.
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

And the result was the same. So, is there some kind of documentation about error management in AVR since this is important to know while development.
P.S. Everything was run on a real Atmega 328p chip on an arduino nano.

I think the standard is that it is undefined for integer math. The floating point is according to the IEEE standard and returns a nan, but no exception. Catching an exeption in the Arduino is not possible (I think) : https://stackoverflow.com/questions/10095591/enable-exceptions-in-the-arduino-environment When you find strange things with a byte, please give a full sketch that we can try and tell us which arduino board you use.

@Jot This is an interesting point but why would a nan be replaced with 4294967295. Apparently they don't have the same binary value. Why did Atmel not include a nan value (that maybe could be disabled through fuses) in their processor architecture. This is a useful troubleshooting feature that is heavily used in all major programming languages.

@Jot I used an Arduino nano with an Atmega 328p on board.

An integer can not be a 'nan', that is specified for floating point. Please update your question with board and microcontroller, and perhaps a full sketch.

I tried to make a sketch myself, and I have different results. Please show your sketch and tell us the results of the sketch that you show. Are you running this in a simulator?

@Jot No, everything is being run on a real arduino.

Thank you for the full sketch. I have added an answer. You have run into a very weird compiler bug that causes the 4294967295. Now I understand why my code did not show that number and your code does.

The simple answer is: they are not handled at all.
According to the C and C++ standards, what you are invoking is called
undefined behavior, meaning anything can happen. In practical
terms, it means that the compiler can do its optimizations assuming
you will never invoke undefined behavior, and completely disregard what
could happen if the assumption does not hold. The generated code could
be completely broken, it won't be the compiler's fault.
The AVR architecture cannot do divisions, nor floating point math. Thus
all the errors you have here happen at the software level. Note that
sqrt(-10) is not an error (it's NaN, which is correctly handled by
the avr-libc), but converting that to an int (which you do when you
assign it to result) is an error.
If you really want to know the details of what happens with each of
these errors, there is only one option: you have to disassemble the
executable program and read the assembly listing.

"... undefined behavior, meaning anything can happen." - It's worth emphasizing that this is completely a C/C++ thing, unrelated to the AVR chips. The exact same warning applies to code running on, say, an Intel i5.

Also worth noting that while the C++ standard states that the compiler can do anything, C++ compilers typically define additional behavior beyond the C++ specification.  For example, Visual Studio's compiler defines the behavior of x/0 which was undefined in the C++ spec, based on what it knows about the architecture.  This is really useful when you want to do something the spec forbids, but your particular compiler permits, like gcc extensions.

About the number 4294967295
To my surprise, the sketch produces indeed the number 4294967295. That is not okay.
It turns out that the compiler knows the numbers and tries to do the math itself (instead of runtime).
At runtime, the 50 / 0 results into a signed integer of -1.
When a byte is used, the 50 / 0 results into 255.
The result of that calculation is a variable with only 1's. That is 0xFFFF for a 16-bits variable. That results into 65535 for a unsigned integer and -1 for a signed integer and 255 for a unsigned byte.
So far, that is okay. It makes sense.
However, when the compiler tries to do the math itself with 50 / 0, it turns the result into a 32-bit variable of 0xFFFFFFFF. The compiler does not put the math into the binary result, but calls the Serial.println() directly with a 32-bit unsigned long of 0xFFFFFFFF, which is 4294967295.
The reason is not the variable type of the variable 'result', but the division with 'p/x'. The compiler thinks it is better to make a 32-bit integer when the math is done with two 16-bit integers.
I think that when the compiler optimizes, the result should be same as a runtime calculation.
There is an interesting discussion below this answer. @EdgarBonet calls the compiler behaviour weird but not a bug.
Below is a test sketch that produces 4294967295 with Arduino 1.8.7 for an Arduino Uno:
void setup() {
Serial.begin(9600);
}

void loop(){
  int x = 0;
  int p = 50;
  int result;
  result = p/x;
  Serial.println(result);
  delay(5000);
}

The code outputs normal results when 'x' or 'p' is calculated, for example the result from a function, or when one of the three variables is made volatile.

The handling of undefined behavior by the compiler is never a bug because, by definition, whatever the compiler does is acceptable per the language standard.

@EdgarBonet I think it should do whatever in the same way. In your opinion the compiler can insert code to whistle a tune when dividing by zero? I don't think so. Changing an int to unsigned long is too weird in my opinion.

Although the compiler may not deliberately do silly things, strange things do happen when you invoke undefined behavior. See for example the beginning of this blog post (the whole post series is a must-read for any C or C++ programmer). Weird? Yes. Bug? No.

@EdgarBonet, thanks, interesting to read that. The things they mention are straightforward. What happens here is that runtime a certain function is called, and when the compiler optimizes it, a different (overloaded) function is called. That is one step further into weirdness.

"In your opinion the compiler can insert code to whistle a tune when dividing by zero? I don't think so." - When you invoke Undefined Behaviour, everything goes, including unexpectedly large variables, tune whistling, or formatting your hard drive. Welcome to the wonderful world of C and C++. It would be interesting though to see if the same "variable promotion" occurs without UB.

It only happens when x is zero and p is non-zero. When the 4294967295 is printed, the sizeof(result) is still 2.


text:
Trying to determine the phase difference between two square signals
I have been looking for the phase difference between two square signals and this is the code:
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
  //Serial.begin(9600);
  pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
  pinMode(3, INPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);

  cli();           // disable all interrupts
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
  TCCR2B = _BV(CS20);    //set prescalar value to 1
  //TCCR1A = 0;
  //TCCR1B = _BV(CS20);
  //TCCR1B |= (1 << CS12); //256 values
  TCNT2  = 0;
  sei();             //enable all interrupts

  attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
  attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

  //Serial.print(OCR2A);
  //Serial.print(OCR1A);

}

volatile uint8_t t1, t2;

void loop() {
  if (t2 == t1)
  {
    OCR2A = 0;
    OCR2B = 0;
  }
  //compare time that one signal goes high to time the other signal goes high
  else if (t2 > t1)
  {
    OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
    OCR2B = 0;
  }
  else if (t2 < t1)
  {
    OCR2B = (t1 - t2);  //output PWM on pin 11
    OCR2A = 0;
  }
}
}

void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
  t1 = TCNT2;           //value to variable t1
}

void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
  t2 = TCNT2;           //value to variable t2
}

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560

Was there a question to go with this?

I do notice that the interrupts() and noInterrupts() right before loop are pointless.  That's at global scope.  You don't need to disable interrupts there, only in executing functions.  You should also be declaring any variables shared by your code and the ISR as volatile.

oh yes sorry! i took those off but the code won't work and I have declared t1 and t2 as volatile unsigned longs. I just wanted to ask what is wrong with the code?

What's wrong with this code?  Or the code you just described with a lot of things changed?  Please post the code that you actually want help with.
What does it do or not do when you run it and how does that compare with your expectations?  You haven't described any symptoms yet.  "It doesn't work" is a really useless statement.  It does something, and it's not what you wanted.  So you have to fill us in on what those things are.  Doesn't that make sense?

I posted again and this time its correct

No, they're still not volatile in the code posted.

i changed it with volatile int8_it

No you didn't.  The code in this question still doesn't say volatile.  You seem to have started another question, but I marked it as a duplicate so they should close that one.  You need to edit this question and put the code here.

It's suppost to read the phase difference as a PWM signal from 0-5volt and -5  to 0 volts

DO NOT REPOST, use the "edit" button to fix this, your original question.

"and -5 to 0 volts" an Arduino has no support for negative voltages!

Your re-post deleted. The "edit" link is there for a reason - edit the question if necessary to improve it.

I have declared t1 and t2 as volatile unsigned longs - no, you haven't.

I re-edited it, sorry I’m new. But for negative I just want the arduino to spit out the voltage so we can use a circuit to reverse voltage on that output so then it is negative

Maybe make t1 and t2 unsigned byte (ie. the byte type). If the high-order bit is set you may well get unexpected results.

I will try that. Thanks! Anymore suggestions on why it wouldn’t work?

Your timer 2 outputs on pins 10 and 11? Which Arduino is this? Please, add to your question the tag appropriate for the Arduino board you are using.

I am using pin 9 and 10 since I switched to arduino mega, it should be updated now, thanks!

how can I do this and read the difference of phase?

a few simple ways:
1) poll the input signals: For example, once a pin has gone high, wait for the other pin to go high as well.
2) xor the input signals: wait for the XOR of both inputs to go high, wait for it to go low. essentially the 1st approach;
3) use interrupts: once the first signal goes high, start a timer; once the 2nd signal to go high, stop the timer.
4) use input capture: ...
...

There are a few things very wrong here.
First problem: you are clocking Timer 2 with the prescaler set to 1.
This means the timer will roll over every 256 CPU cycles. Your
input signal, on the other hand, has a period of 25 µs, which is
400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you
know beforehand that the phase difference is within some window less
than 16 µs wide, your readings will be ambiguous.
You have to make sure the rollover period of your timer is larger than
the period of the input signal. This means either using a larger
prescaler (8 should do), which will decrease your phase resolution,
or using a 16-bit timer instead of an 8-bit timer.
Second problem: you are using a signed integer type for the timer
readings. This makes little sense. Worse: you are computing differences
like t2-t1, which can overflow. Signed integer overflow is undefined
behavior in C++, and
invoking it is always a bug.
You should declare t1 and t2 as unsigned, i.e. either
volatile uint8_t, or volatile uint16_t (if using a 16-bit timer).
Then you don't get overflows: you get instead a well-defined rollover
behavior.
Third problem: you are doing comparisons like if (t2 > t1). This,
again, makes no sense, if only because the timer is repeatedly
rolling-over to zero. You should instead just compute t2-t1 and work
your way from that.