text:
Measure different Vcc using 1.1V bandgap
When I power my ATmega328P chip from 5.16V and 3.3V, there doesn't seem to be a single bandgap voltage compensation figure that works for both.
I'm using the following sketch, and I need the following InternalReferenceVoltage values to read the correct voltage from A0:

1255L to correctly output 5.16V.
1358L to correctly output 3.3V.

I have a couple of questions:

Should I be able to use a single InternalReferenceVoltage compensation value whe powering the ATmega328P from different voltages?
Aren't both of these values outside the specced 1.0 to 1.2 range?

The code is from, http://forum.arduino.cc/index.php?topic=56750.msg407897#msg407897, retolefty post @ Mar 28, 2011, 02:27 pm.
#include <SPI.h>

void setup()
{
  delay(5000);

  Serial.begin(115200);
}

void loop(void)
{
  // Determines what actual Vcc is, (X 100), based on known bandgap voltage
  int battVolts = readVcc1();

  Serial.print("Battery Vcc volts =  ");
  Serial.println(battVolts);
  Serial.print("Analog pin 0 voltage = ");
  Serial.println(map(analogRead(0), 0, 1023, 0, battVolts));
  Serial.println();

  delay(1000);
}

// Returns actual value of Vcc (x 100)
int readVcc1()
{
  uint8_t oldADMUX = ADMUX;

  const long InternalReferenceVoltage = 1255L; // Adjust this value to your boards specific internal BG voltage x1000

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
  // For mega boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc reference
  // MUX4 MUX3 MUX2 MUX1 MUX0  --> 11110 1.1V (VBG)         -Selects channel 30, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (0 << MUX5) | (1 << MUX4) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#else
  // For 168/328 boards
  // REFS1 REFS0          --> 0 1, AVcc internal ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0 << REFS1) | (1 << REFS0) | (0 << ADLAR) | (1 << MUX3) | (1 << MUX2) | (1 << MUX1) | (0 << MUX0);

#endif
  delay(50); // Let mux settle a little to get a more stable A/D conversion
  // Start a conversion
  ADCSRA |= _BV(ADSC);
  // Wait for it to complete
  while (((ADCSRA & (1 << ADSC)) != 0));

  // Scale the value
  int results = (((InternalReferenceVoltage * 1023L) / ADC) + 5L) / 10L; // calculates for straight line value

  ADMUX = oldADMUX;

  return results;
}

I have read these other references to try and find a solution:

Measure Vcc using 1.1V bandgap
https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/
http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/

I don't get the question. The idea is not to measure the 3.3v or 5v using the internal reference voltage as a reference, but the other way around. You measure the internal reference voltage in relation to Vcc.

Thanks. Do you know how I should change the code or the measurements then? I thought measuring Vcc using the internal reference would allow me to calculate how my particular internal reference varies from 1.1V.

After reading your question one more time, I finally get it. Forget what I said, as it's not related.

The internal reference won't change much. That's why it's a reference.
Running this code on my Atmega328P:
void setup ()
{
  ADMUX = bit (REFS0) | bit (REFS1);  // Internal 1.1V reference
}
void loop () { }

That outputs the reference voltage on Aref. I measured it as follows with different values for Vcc:
Vcc     Aref
------------
5.00   1.085
4.00   1.081
3.30   1.080
3.00   1.079

So you can see that it retains, more or less, the same voltage regardless of Vcc. In any case, there is no way of measuring Aref, unless you have another reference voltage around to compare it to.

Thanks. So do I measure the voltage on the AREF pin with a multimeter to calibrate an individual chip? I'm sure I read somewhere that the internal voltage reference was never made physically available externally. I'm still not clear on how to fine tune an individual chip to get more accurate voltage readings of the battery powering the chip.

What I posted above was done by measuring with a multimeter after running that code which puts the internal voltage reference onto the Aref pin. And yes, it varies from chip to chip. As you can see, mine is slightly under 1.1V.

Thanks. I measure 1.078V on AREF (using multimeter) following your sketch, but when I use that value as the InternalReferenceVoltage value (from your "Internal Voltage Sensor" code - http://www.gammon.com.au/adc) I get 4.35V printed, when my voltage is 5.16V. I measure Vcc continuously in the loop. Confused.

What raw ADC reading do you get? Mine reads low (4.95V - raw reading: 226) but not that low. See this thread on AVR Freaks - it appears that there are some inconsistencies between theory and practice.

The difference between 4.95V and 5V (that I got) is only 1%, so that is probably acceptable for checking input voltage. Your results of 4.35V sounds like some sort of error. I tried a different approach using an external reference voltage (TL431 chip) and got better results. I can amend my answer if you want to see that. However that may have other drawbacks (depending on whether you are using the analog inputs for other purposes as well).

A bit of testing with an external reference still gives readings that fluctuate a bit. I suggest an error of a percent or two is probably normal for the ADC.

Thanks for your suggestions and the AVR Freaks link.  I've tried another 328P and get 1.08V for bandgap, 255 raw ADC, and the 2nd code prints 4.32V for the 5.16V source.  I can measure the battery V using 'standard' ADC relative to my boost converter's 3.3V [1], but the 'native on-chip' way seems more portable so I'd prefer to do it that way unless I've missed something.  I am new to this after all!  I do have an old and cheap multimeter, so I probably ought to buy a second to verify my measurements.  [1] the boost converter is not involved in my testing, my 3.3V is from a LD33V chip.


text:
Erratic readings on Analogread with low voltages
I am using Arduino Uno for measuring sensor voltages. I am using multiplexer to switch between different sensors. The readings measured in the range of 800-900 mv are accurate, but at low millivolts (at about 20 mv) they are erratic. I read repeatedly to get average of 20 values. I get values such as 1.3, 1,4, 2,0, 3.8 etc.
Can any one help on why it is happening and how to avoid it.
Additional information: I am using reference voltage of 1.25 volt for better resolution.
I tried having delay between two readings, though there is some improvement, still the problem persists.
I appreciate the help by experts.
Thanks

May be this is because the voltages that you are trying to measure are way below the noise floor and the arduino is measuring the noise from the pin.

Noise problems always need multiple approaches / attacks: 1) Scope it to see what is any real noise needs to be dealt with. 2) Dive into the Atmel spec to see if the ADC can actually make such a measurement. 3) Use exponential smoothing and play with the alpha constant. 4) Try a different power supply or try something clean like a battery.

You need a stable power-supply. You need a stable measuring voltage. You could try adding the small capacitor to the output of the thing you try to measure. You could try using the ADC_sleep mode on the ATMega328. This will sleep the MCU during the measurement, keeping noise down.

Addition to the other comments, if that low voltages are common in your project, maybe you are using wheat-stone bridges with strain gauges or similar sensors, it might be the best option to use a good low noise instrumental amplifier between the sensor and the multiplexer. This setup will give you manageable voltage levels.

You are almost certainly running into the noise floor for your setup. When your target signal is a very low voltage your signal to noise ratio (SNR) is small. Because it is the noise floor setting the ADC for better resolution didn't help much. There are many ways to deal with noise. If your signal is "slow" and your noise is random you can try oversampling. If the noise is from the power supply you can add filtering on the input to your sensor. If you have done those and still want to reduce noise more you can try adding shielding to your device/wires.

source: Stack Exchange

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

sort: votes


text:
ESP8266: Is it safe to use pin 0?
This (maybe stupid) question is bothering me for a long time...
If the pin 0 has to be connected to the ground for uploading a sketch into ESP8266, and after the uploading the chip automatically starts the uploaded sketch (without waiting for reboot with pin 0 to be disconnected), then won't it destroy the chip if I do digitalWrite(0, HIGH) in my sketch? Correct me if I'm wrong, but it should short 3.3V directly to the ground through this pin... Is this problem secured somehow? Or maybe this pin can be safely used for reading only?
Edit:
I have seen it connected to ground directly on every schematic about ESP8266, but maybe I should just use a pull-down resistor? Or maybe the chip already has a resistor before this pin to solve this problem?

You can absolutely use GPIO0 as an output. The ESP will read the state of GPIO0 once at boot (And never again thereafter) to determine what boot mode to enter. During this time it is an input, so, whatever you hook GPIO0 up to must not hold this pin low (Unless you want to enter bootloader mode, of course), at least until the chip boots. As long as you satisfy this condition, you can use the pin for anything else. On my board for example, I use it to drive a simple status LED, and have never seen any issue from it.

What do you consider pin 0?
As I look at the schematics it could either be GND, VCC, RX or TX pin. Or do you mean GPIO0?
GPIO0 when connected to GND and in combination with RST to GND will put ESP into programing mode.
Good practice is to have separate programing board, something like This here. Go down to "Writing a program to the ESP8266" section and check out the schematic. Voltage regulator can be omitted if you are already powering it with 3.3v.

When I write digitalWrite(0, HIGH)  I mean GPIO0. I know how to flash ESP8266 and I'm using a circuit in which I just press Upload and it just uploads (no manual reset needed). I've got a switch by which I toggle when the GPIO0 is connected to GND or not (and I switch it off only if I have to restart the program without uploading the new version). I'm just wandering if I could use this pin as an output pin because I'm out of pins. And I'm using ESP-12 with its standard breakout board that you can just plug into a breadboard.

It may be stated that GPIO0 is safe to use as an output, but I challenge anyone to show he has actually done it. When configuring GPIO0 as an output I get only oscillations (about 70kHz), loaded or open, when driving this pin LOW.
Even GPIO15 works without issues when used as an output.
Several new ESP8266-12F modules were tested.

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

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


text:
ESP8266 blink not building to esp-01
I am trying the esp8266 esp-01, and did all it asked on the arduino IDE side, but i am having problems compiling and building the blink example into the board
Using: FT232RL usb-ttl in the 3.3v configuration, two 1.6v (new) batteries to power the esp, and all the conections as indicated here (not using the led though).
when I hit (go) it compiles, but as it transfers both boards blink sincronously and I recive the following errors:
O sketch usa 219.479 bytes (50%) de espaço de armazenamento para programas. O máximo são 434.160 bytes. Variáveis globais usam 31.172 bytes (38%) de memória dinâmica, deixando 50.748 bytes para variáveis locais. O máximo são 81.920 bytes.
error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed
I looks to me as a newbie that its trying to establish a link and failing... what could it be?
the configurations are default, programmer is "AVRISP MKII"

You did not put ESP8266 into programing mode.
the easiest way to do so is to make your own programing board, something like shown here. Go down to middle of the document to title "Writing a program to the ESP8266" where you will see a schematic of simple programing board. You will need two switches and a 10k resistor.
The voltage regulator can be omitted if you are powering it by 3.3v power. Also its a good idea to put a small capacitor (100uf) between vcc and ground to stabilize any drops in voltage which is primary cause of esp8266 rebooting it self.


text:
Unidentified constant value
im working on the following project kalman filter
and im working to implement in arduino.. i read the entire code and i succesfully implemented it into arduino but i couldnt implement the following function code line because arduino gives "not defined" error in PI_DIV_180
imu_MadgwickQuaternionUpdate(bUseAccel,elapsedTimeSecs,fax,fay,faz,fgx*PI_DIV_180,fgy*PI_DIV_180,fgz*PI_DIV_180,fmx,fmy,fmz);

it multiplies fgx with PI_DIV_180 but as i said arduino cant identify it
i looked into math.h to find the value of that define but there isnt anything in math.h related with this
the imu_MadgwickQuaternionUpdate function is in here IMU.cpp
can anyone help me please thanx..

Maybe it's pi (π) divided by 180?
Pi is roughly: 3.1415926535898
So:
3.1415926535898 / 180 = 0.017453292519943

So add this line:
#define PI_DIV_180 0.017453292519943

yeah it may be...will try it..thanx

authors: евгений иванов


text:
UNO's digital pin continue to read 1 for a while
I'm doing some tests and I notice a bad things with digitals pins. I have a wire that sends 1 signals. If i connect it to a reading pin, I read 1 - and it's ok. But if i disconnect it, for 5-6 seconds Arduino continues to read 1 instead of 0! How can I stabilize it more quickly?

Where is the pin connected to when you disconnect the wire? Probably nothing. You shouldn't have pins floating!

Digital inputs should either be low or high. In this image acceptable input voltages on the left represent common TTL voltages based on a 0 to 5 volt range:

It is bad practice to leave a digital input floating.  A floating or disconnected input implies the voltage is unknown.  I suspect in your case a small amount of input capacitance held a charge for several seconds.  Once leaked off the input appeared to change from 1 to 0.  Even though you know what might be happening, you should not depend on it as it is unreliable behavior.
If connecting a SPST switch use a pull up (or pull down) resistor to pull the input pin to the opposite voltage the switch is pulling.  In this image the switch is connected to ground so the resistor is connected to positive voltage as a pull up:

The fist image comes from this Logic Level tutorial.

For Arduino (Atmega328), at 5V an input of above 2.7V will read as 1 and under 2.2V will read as 0. (http://i.stack.imgur.com/Dqnbp.png) This doesn't really match the values of your source, but my source is the ATmega328 datasheet. (To avoid confusion on the voltages)

ATMega328P inputs are Schmitt Trigger. There is no such thing as an "unknown" voltage level - only a "last valid" voltage level. The voltage has to drop below VIL for it to start registering LOW and then rise above VIH to start registering HIGH. Anything in between retains the previous setting.

St2000 's reply above gives the background, which is valid for any digital input, not just the Arduino pins.
However, in the specific case of the Arduino, one more thing should be noted: You can skip the use of an external pullup resistor by configuring the pin to use the internal pullup resistor:
pinMode(pin, INPUT_PULLUP) ;

This assumes, of course, that it is easy to modify the part of your circuit that is connected to your input pin to have the following two states:
- ground
- high impedance (floating)

If, for example, it is a switch you are reading, just connect one pin of the switch to your arduino pin and the other to GND.


text:
How to connect a a three state switch (ON-OFF-ON) to arduino?
I have created a car that can detect obstacle and change its direction, but now I want to add a bluetooth module to control it and I want to switch between the two circuits using a three state switch (ON-OFF-ON), so how can I do that and how can I upload two different codes on the arduino.
Here is a fritzing diagram, (the pins for the bluetooth will be changed).
Sensor:

Bluetooth:

And here is the code for the sensor:
   #define echopin  8 // echo pin
   #define trigpin 9 // Trigger pin

   int maximumRange = 30;
   long duration, distance;

    void setup() {
        Serial.begin (9600);
        pinMode (trigpin, OUTPUT);
        pinMode (echopin, INPUT );
        pinMode (4, OUTPUT);
        pinMode (5, OUTPUT);
        pinMode (13, OUTPUT);
        pinMode (6, OUTPUT);
        pinMode (7, OUTPUT);
    }

    void loop ()
    {
        digitalWrite(trigpin,LOW);
        delayMicroseconds(2);

        digitalWrite(trigpin,HIGH);
        delayMicroseconds(10);

        duration=pulseIn (echopin,HIGH);

        distance= duration/58.2;
        delay (50);
        Serial.println(distance);
    }

        if (distance >= 30 ){
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
            digitalWrite(6,LOW);
            digitalWrite(7,LOW);
            delay (200);
        }
        else if (distance >=15 && distance <= 25) {
            digitalWrite (4,HIGH);
            digitalWrite (5,LOW);
            digitalWrite (6,LOW);
            digitalWrite (7,LOW);
            delay (1000);
        }
        else if (distance < 15){
            digitalWrite (4, LOW);
            digitalWrite (5, LOW);
            digitalWrite (6,HIGH);
            digitalWrite (7,HIGH);
            delay (1000);
            digitalWrite (4,LOW);
            digitalWrite (5,HIGH);
            digitalWrite (6,LOW);
            digitalWrite (7, LOW);
            delay (1000);
        }
    }

Please write in the most details and write any code as I am still a beginner.

Stackexchange is not a free coding service. The questions and answers should be useful to more than one user. You did the first steps right and supplied schematics and code. But you cannot expect to get your code written here.

As stated by st2000, it's not common practice to have two separate programs running on one microcontroller.
The solution is simple, use the switch to "switch between" behavior.
if(switch is on){
  //Automatic
}else{
  //Bluetooth
}

You should also use functions, to make your code more readable.
This might work:
#define echopin  8 // echo pin
#define trigpin 9 // Trigger pin
#define switchPin 10

int maximumRange = 30;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode (trigpin, OUTPUT);
  pinMode (echopin, INPUT );
  pinMode (4, OUTPUT);
  pinMode (5, OUTPUT);
  pinMode (13, OUTPUT);
  pinMode (6, OUTPUT);
  pinMode (7, OUTPUT);

  pinMode(switchPin, INPUT_PULLUP);
}

void loop ()
{
  if (digitalRead(switchPin)) { //If the switch is pressed.
    automaticLoop();          //Do the automatic control.
  } else {                   //If not pressed.
    bluetoothLoop();          //Do the bluetooth control.
  }
}

void measureDistance() {
  digitalWrite(trigpin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigpin, HIGH);
  delayMicroseconds(10);

  duration = pulseIn (echopin, HIGH);

  distance = duration / 58.2;
  delay (50);
  Serial.print("Distance is: ");
  Serial.println(distance);
}

void automaticLoop() {
  measureDistance();

  if (distance >= 30 ) {
    digitalWrite(4, HIGH);
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    delay (200);
  }

  else if (distance >= 15 && distance <= 25) {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
  else if (distance < 15) {
    digitalWrite (4, LOW);
    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
    digitalWrite (7, HIGH);
    delay (1000);
    digitalWrite (4, LOW);
    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
    digitalWrite (7, LOW);
    delay (1000);
  }
}

void bluetoothLoop() {
  //Code for bluetooth.
}

While a simple concept, having 2 different selectable programs (sketches) in 1 Arduino is not the way the Arduino paradigm works.
Most Arduinos contain an Atmel processor.  This processor contains a boot loader program.  This program only knows how to deal with 1 other program (the sketch).  In order to switch between 2 different programs (sketches) you would have to re-write this boot loader.
But you still have to deal with the creation of the 2nd program.  In order to do this you need to change the SDK used to create the 2nd program (sketch).  Specifically, you need to link the 2nd program (sketch) so that it can operate out of a different location in the Atmel processor's memory.
It would be far easier to combine the two programs (sketches) into a single program (sketch).  Then use your switch to change the program's (sketch's) behavior.

The question ends with: I am still a beginner., I believe your answer is unnecessarily "technical".

I'm trying to give you some more general advice.
How to combine two Arduino sketches into one
There is no general rule, how to do this. But there are some common problems to solve.

Code has to be merged for setup and loop independently
You can have only one setup() and one loop() when finished.
If there are variables with same names in both sketches, you have to rename those in one of them.
If you operate with delays, be aware, that delays sum up and retard processing of your loop accordingly.
Having your code merged in most cases you need additional variables to transfer information from one code part to another.

How to use two different hardware setups with one Arduino
There are some general rules, too:

Except for some meticulously and intricately designed electronics, you can use each port only once. You have to move hardware to another port if they are conflicting.
If you run out of ports, you may have to use port expanders or some logic circuitry to gain more inputs and outputs
Check if your hardware does not overload your arduino power supply. some shields and modules can easily suck up the available power.

authors: Максим Парфёнов


text:
Creating an Arduino Tic Tac Toe game
I'm trying to create a Tic Tac Toe game using the Arduino Uno. Since the Uno has a limited amount of pins to use, I am trying to see if there is a configuration that would make the project possible.
For the button detection circuit I am using a simple voltage divider and an analog pin. I made the following in a circuit simulator:

Now for the LEDs, since the Uno only hosts 9 pins, and we need 18, we need some sort of wizardry to get something working. I came up with the following design using the circuit simulator:

I would use 9 of these, one connected per Arduino pin. Since only one of the LEDs in each of the 9 sets should be on, this type of circuit should allow the Arduino to control all of the 18 LEDs. In the simulation I get about 5mA draw from each side (with 5v and GND).
However my problem is that the LED setup doesn't work. The lights are extremely dim. At first I simply thought that 5mA was not enough for the LED. I decided to measure the current going through the LED and found that it was about 0.8mA. What happened to my 5mA calculation? After all, isn't Arduino pin able to handle about 40mA? Am I asking for too much current?
Where have I gone wrong with this? Thanks in advance for any help.
tommis15

Worth mentioning, what are the specifications, or the make of your LEDs bring used

I bought them through Tayda Electronics. The spec sheet says 20mA forward, but they work when I use the GND or 5v pins on the Arduino. It just doesn't when I use the digital ones.

yes, those are pretty normal specs, also I wouldn't put the LED straight across 5V and GND. What I would like yo know is the voltage drop across the LED. Could you also clarify the reason why you have 3.3V on the one LED anode?

No, I am using the circuit above, but instead of a digital pin I am using the 5v and GND pin.

yes but why the 3.3V supply??

can you connect one LED and resistor to a digital PIN and toggle it with some code. First use your 330ohm resistor and then try with a 220ohm. And reply with the observation

I use the 3.3v supply because current flows without it and both LEDs turn on at all times.

This question is similar to Increasing the numbers of I/O pins on Arduino Uno.

I was working with it more and I found that my mistake was that I was using pin 0 and 1 to test (serial) and switching to pin 2 and above works.

Please accept it by clicking on the "tick" icon next to the answer. This indicates to other users that you found the solution, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

You should really provide more info:
- your program
- what exactly you are trying to achieve (you seem to be driving two leds per 'board position'. What do they represent?) and schematics.
It would also help if you measured the voltage level at the pin in both the ON and OFF state and mentioned it here.
However, one thing that should be noted (hopefully before it is too late) is that your 40mA/pin assumption is wrong. First of all, 40mA is the absolute maximum rating for one pin (i.e. the value you should stay clear of). Secondly, although one isolated pin can source or sink close to 40mA, the total of all GPIO pins should stay below 200 mA. See also http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations .

"The total of all GPIO pins should stay below 200 mA", yes. This is why I wanted to draw only 5mA from each pin (which would result in way under the limit).
As far as my program, I have not written it because I want to hardware to work before I write. (I am using digitalWrite to test if the led will turn on).

How do you expect to test the hardware without running a program? And what is the voltage level of the pins? And what exactly is the meaning of each LED pair (I would expect one to represent an X and the other an O, but I can't see how your circuit would have them both off (to represent an empty position).


text:
How to use the analog comparator to determine when an analog pin has reached a certain voltage?
I am trying to find some information on how to use the analog comparator on an Atmega328 to detect when an analog pin has reached a certain voltage (3.16 volts).
I cannot find any example code that says how to do this, although I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin. I do not understand how this would work as the PWM pins do not output an analog voltage, but a pulse width modulated square wave. Is it possible to use the comparator to compare with a certain voltage this way?
I have tried polling with analogRead(), but it is too slow for my application.

I have read that the analog comparator can compare the voltage on an analog pin with the voltage output by a PWM pin - do you really need to vary the reference voltage, or is 3.16V what you want? The analog output pins do not output analog voltages (they are not DAC), they are PWM output.

Alternatively, you could check the ADC voltage every now and then, to see if it's above 3.16V

@Paul: I tried that, but it is too slow for my needs.

@jBot-42 it can be usefull to state timing requirements in your questions, or the things you've tried yourself (:

This works fine to enable comparator mode, but I can't seem to restore normal ADC operation after using comparator mode. Joe

I have a page about the analog comparator that has code:
volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop

This is for a fixed reference voltage, for example:

I might be missing something, but in this diagram won't the voltage on AIN1 always be lower than that on AIN0 ?

Er, yes, my example resistances were not well chosen. Probably AIN1 should have a voltage divider more in the middle range (eg. 4.7k and 4.7k making AIN1 = 2.5V which the LDR would be above in one situation, and below in another.

You need a low-pass filter between the PWM output and the comparator input. This will allow you to produce an analog voltage from the PWM output, which can the be used as a reference voltage for the comparator.
Typically, a simple RC LPF is sufficient. Choose a large time constant relative to your PWM frequency (the Arduino defaults to 490Hz) so that you don't have ripple in your reference voltage.


text:
Arduino not in sync unique error

When I try uploading to my Arduino/Genuino UNO I get the following not in sync error with "unique" resp(resp=0X54) or (resp=0X81) please solve ... I have to submit my project tommorow......

error message:
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x54
  Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

[![enter image description here][2]][2]

I think this is more likely to get an accurate answer on the stackexchange Arduino forum. So would you ask it there? Have you tried something much simpler, like uploading the 'Blink' example?

Are you able to compile code? Are you using arduino board? If yes, disconnect external circuitry and try uploading the code. If it works, re-check your external circuit. If it doesn't, replace your arduino. If you are not using arduino board, let us know. Also, it's always a good idea to show us the circuit/ schematic etc. Help us help you.

i have uploadeed the schematic and the code

Have you previously successfully loaded a program using this same computer and same Arduino? Is it possible that the software has changed since then? Have you access to a 2nd Arduino or 2nd computer? Is this computer in a classroom? Please post the whole text of the new error message.

You have a BT module attached to Arduino Tx Rx pins. That's the culprit. Disconnect anything from Tx and Rx pins of arduino while uploading code. Once the code has been uploaded, re-connect the BT module.
Edit:
Since this didn't solve your problem, you need to pin point the issue. If you have removed everything from Arduino and still not able to upload the code - either your drivers are not up to date or your arduino is faulty.
Test the arduino:
Try uploading blinky sketch. Didn't succeed? Restart arduino IDE and try again. Didn't succeed? Restart PC and try again. Didn't succeed? Re install arduino and try again? Didn't succeed? Try on a friend's PC? No luck? Arduino is faulty.
Note: This answer is for the exact schematic you have given. If you have done something else, there might be other reasons why you are not able to upload the code. Post a real picture of what exactly you are doing and we might be able to help you further.

Yup. You beat me to it, but that's all I would have written too. +1

i did that mistake but i removed all the wires from arduino and tries to reupload but the same happens

please reply Whiskeyjack and gbulmer

So you get the same error with ALL wires disconnected except for the USB lead? Are you SURE you have selected the correct board and port? If you have. I would disconnect the Arduino from the USB port, reboot the PC, and try loading Blink. It is possible (but unusual) that you have damaged the Arduino's Rx or Tx pin or the USB-to-UART's pins.

@gbulmer - What sorcery is this? Are you a mind reader or something? :)

@gbulmer i tries rebooting but the same error bur this time with(resp=0Xe6)...

@Whiskeyjack - I teach Arduino stuff every week to children from 12-16. These incantations become reflexes :-)

please answer i get different resp no i got(resp=0Xob)

Attach the real image. You might be hiding too much useful info by assuming we don't need that to answer your question. For ex - Whether you are using arduino UNO or Arduino Pro mini, whether you bought one or made one using atmega 328.

NOTE
That schematic shows you are trying to power the motors from the Arduino's 5V power supply. That is a 'bad idea' unless they are good quality, low-current, motors.
The electrical noise from the motors may cause the Arduino to reset, and run the same program from the beginning until it reaches the part where the motor's electrical noise resets it.
Worse, current drawn if the motors stall may damage the Arduino's power supply. The Arduino's voltage regulator is supposed to protect itself from damage, but it doesn't always succeed. This is rare, but I have had students break it.
I have elevated this comment to an answer to warn other people against trying to use the schematic in the question.

uare a genius .. after 2 hours of research, i found that my arduino is bricked and the bootloader is curropt. i ave to buy avr usbasp cuz that is the cheapest . to reupload the bootloader ........thanks ...........................

It is possible to get the same chip working if you try re uploading the bootloader to it. I have seen it in a few cases. Use the arduino bootloader burning guide to do so.

@AnirudhRaghavanS - if you already have access to another Arduino, you can use that to reload the bootloader.

@gbulmer  i dont have another arduino so the cheapest programmer in the the market is avr usbasp which costs around 3 dollars , so i am thinking of buying that stuff, anyway thanks

@whickeyjack i dont have another arduino so the cheapest programmer in the the market is avr usbasp which costs around 3 dollars , so i am thinking of buying that stuff, anyway thanks – Anirudh Raghavan S just now

@gbulmer and whiskeyjack\ , please give me your facebook id, i want to have you as a guide for my arduino project


text:
PIR sensor and sleep (interrupt) on Mega2560
So I was starting to gain some knowledge on the PIR sensor and how to let the Arduino 'sleep' while there is no movement detected by the PIR.
I found the following code somewhere and looked fairly simple. So  I thought I would give it a try and grabbed my Mega2560, a LED and a PIR sensor.
While it was seeming to work at first sight, the Arduino is doing the opposite from what I was expecting. It turns off the LED and the Arduino when there is movement, instead of turning off the Arduino when there is NO movement. As I said before, it is doing pretty much the inverse.
Probably an easy solution, but can't figure it out on my own.
The code:

#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led = 13;

void wakeUpNow() {
}

void setup() {
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    digitalWrite(led,LOW);
    sleep_mode();            // here the device is actually put to sleep!!
    // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    digitalWrite(led,HIGH);
}

void loop() {
  sleepNow();     // sleep function called here
}

Thanks in advance.
EDIT
Adapted the code to the following and seems to work now. When motion is detected by the PIR it turns on the LED on pin 13; when no motion is detected, the LED is turned off.
Two questions still remain:
1) How can I be sure that the Arduino really sleeps now?
2) When the Arduino just entered sleep, it takes a couple of seconds (+/- 6s) before it can pick up another motion. Can I get a faster detection or another 'sleep' or 'powersave' method that lets the Arduino react faster to motion?
#include <avr/sleep.h>

const int wakePin = 2;                 // pin used for waking up
const int led = 13;

int wakeVal = 0;
int wakeState = LOW;

void wakeUpNow() {

}

void setup() {
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  //attachInterrupt(0, sleepNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    sleep_mode();            // here the device is actually put to sleep!!
}

void disSleep(){
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void loop() {
  wakeVal = digitalRead(wakePin);
  if (wakeVal == HIGH){

    disSleep();

    digitalWrite(led,HIGH);
    delay(1000);

    if (wakeState == LOW){
      Serial.println("Motion detected");
      wakeState = HIGH;
    }
  }
  else{
    digitalWrite(led,LOW);
    delay(1000);

    if (wakeState == HIGH){
      Serial.println("Motion stopped - Going to Sleep Mode !");
      wakeState = LOW;
      delay(1000);

      sleepNow();     // sleep function called here
    }
  }
}

Are you assuming that your sensor gives a low output when it detects movement? Perhaps it's the other way around?

@uint128_t is right. Most PIR sensors go HIGH when they detect movement.

attachInterrupt(0,wakeUpNow, HIGH); maybe?

Yes I know movement = high & no movement should be low. I tried attachInterrupt(0,wakeUpNow,HIGH) already. Doesn't seem to resolve it.

This is a problem with the Arduino Mega board. On the Mega, D2 is not INT0 as it is on the Uno. It's INT4. There's a footnote in the spec sheet that says only level interrupt is supported. That means you can't use RISING, FALLING or CHANGE. Your only choice is to use LOW. So the Arduino will be woken up when the motion turns OFF, not on. That's why it's backward. If you use an Uno instead of a Mega, you can use RISING and it will work as you think it should.

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


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

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

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

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

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

@Majenko which means a fried servo?

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

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

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

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

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

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

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

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

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

Your servo is dead if:

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

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

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

Since a servo is basically the combination of this components:

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

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

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

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

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

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

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

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

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

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

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

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


text:
build fixed size strings from floats
This is likely a duplicate, but I couldn't find the original question. This is really basic, but just can't figure it out.
I'm trying to combine a few char arrays together. This is what I've tried so far.
float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[4];
dtostrf(a, 4, 1, a_string);

char b_string[4];
dtostrf(b, 4, 1, b_string);

char c_string[2] = {'0', '\0'};
if (c) {
  c_string[0] = '1';
}

char output[12] = "-----------";

output[0] = a_string[0];
output[1] = a_string[1];
output[2] = a_string[2];
output[3] = a_string[3];

output[4] = ' ';

output[5] = b_string[0];
output[6] = b_string[1];
output[7] = b_string[2];
output[8] = b_string[3];

output[9] = ' ';

output[10] = c_string[0];

Serial.println(output);

Results in an empty string in seems.
If I remove the second dtostrf(), and change b_string[0] ... to a_string[0] Then I get 12.3 12.3 1. Doesn't seem to like having dtostrf() called more than once, but it seems like the function I want, since it allows me to set a fixed strint size. The output I'd be looking for is 12.3  5.4 1
another approach
String a_string = String(a, 1);
String b_string = String(b, 1);
String c_string = String(c);

String output;
String space = " ";

output.concat(a_string);
output.concat(space);
output.concat(b_string);
output.concat(space);
output.concat(c_string);

Serial.println(output);

This outputs 12.3 5.4 1. Is there a way to make the String fixed width? I'm looking for
12.3  5.4 1 instead of
12.3 5.4 1
What's the proper way of doing this?
EDIT

After trying to use the @Majenko's answer I sometimes get garbage values printed. Any ideas why?
float a = analogRead(A1) / 1023.;
float b = analogRead(A2) / 1023.;
bool c = analogRead(A3) / 1023;

char* output = createString(a, b, c);
Serial.println(output);

char* createString (float _a, float _b, bool _c)
{
    char a_string[5];
    dtostrf(_a, 4, 1, a_string);

    char b_string[5];
    dtostrf(_b, 4, 1, b_string);

    char out[12];
    snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
    return out;
}

and the output:
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.6  1.0 0
 0.�tS
�
 0.6  `S
�
 0.6  1.0
}
 0.6  1.0 0
 0.7  1.0 0
 0.6  1.0 0
 0.6  1.0 0

using
  Serial.print(a_string);
  Serial.print(" ");
  Serial.print(b_string);
  Serial.print(" ");
  Serial.println(c);

doesn't produce the errors

Other than figuring out how long each string is or using *printf()?

The simple way would be to format the string with sprintf - however sprintf on the Arduino lacks floating point support (although it is possible to enable it).
So if you convert your floating point numbers into strings first (remember to provide room for the NULL terminating character!) you can then use sprintf to format those converted numbers into what you want:
float a = 12.3456;
float b = 5.4321;
bool c = true;

char a_string[5];
dtostrf(a, 4, 1, a_string);

char b_string[5];
dtostrf(b, 4, 1, b_string);

char out[12];

snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);

%4s is replaced by a string which is padded to at least 4 characters wide. The padding is to the left of the string. If you want the padding to the right you can use %-4s instead.

Addendum:
In your new posted code you are making a fundamental error:
char out[12];
snprintf(out, 12, "%4s %4s %d", a_string, b_string, c ? 1 : 0);
return out;

out is a local variable to the function. Its memory is allocated on the stack. You fill that with data and then return the address of that location on the stack. As soon as you leave the function that memory allocation is lost. Yes, the data is still there, but the moment you call another function that memory gets overwritten with the call frame of the new function you have called - thus corrupting your data.
You have two main options:

Make out global
Make out static

The effect of the two options is pretty much the same, except that in the second option the scope of out is restricted to the function which means you can use the name out elsewhere without it conflicting. In both options though the memory allocated to out is in the BSS not the stack and thus won't get overwritten.

Thanks, that works great. When I try to use analogRead values for it though I sometimes get garbage. I updated by question. Any ideas?

See my addendum.


text:
Is there a way to combine a 3-axis accelerometer/gyroscope into one value?
I have a three-axis accelerometer that reads me its x, y, and z components.  This results in three graphs.  Is there a way to "combine" these components into one reading, hence, one graph?   Same question holds for a gyroscope.
The datasheet for my device is here:

The answer is: technically, yes, it is possible. The combined result is called Quaternion. This is what is typically used in 3D programs.
But most likely that is not what you had in mind.
Usually one can do a simplification and reduction of dimensions when in presence of some constraint.
Imagine that your moving object is bound to a planar surface: no matter how you tilt and rotate and pan it, it is still a 2D surface, plus a quaternion indicating the rototranslation.
But, once you have established the coefficients applied to the rototranslation, it is 2D.
Similar 1D case: imagine that your moving object is bound to some well-known geometrical shape, say a circumference. Once you have established how the circumference is oriented in the 3D space and its radius, you can express the position of your device by indicating either the angle or the distance from a reference point on the circumference.
In both cases you can simplify the representation because of constraints that do not allow for real 3d movement.
But if your device is a flying drone that can rototranslate freely within certain boundaries (max horizontal range, min/max altitude), there is no way that you can simplify the 3d coordinates.
If, instead, your question was related to the protocol used to read info from the accelerometer, you are bound to the protocol defined in the datasheet, by the manufacturer.


text:
Hardware Interrupts Issues
My program has a hardware interrupt to digital pin 2,  it is an IR obstacle detection sensor which gives “open collector” signal.  My program is executing an array — “for” loop.   At some point it has to wait for the input from the IR sensor, so I am using a “while” loop to pause and wait for the input.
When the program gets the signal from the sensor at which point the interrupt occurs, the program collects the data (millis) and goes on for another round.  Everything works fine, but I would like to limit the time that the program is waiting for the interrupt signal, let’s say to 5 or 10 seconds. I do not want it to just sit there forever if the signal is not coming for some reason.   So what I am trying to do is to trigger the same interrupt pin (2) by another digital pin.  I  set this pin (7) on OUTPUT wrote a little “if-then” statement  so it will go HIGH when the time is up and connected this pin (7) to pin 2.
The scheme works partially.  When the pins are connected and the time limit is reached the pin 2 gets signal and gets triggered.   But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.  I tried to connect pull-up and pull-down resistors to no avail.  It seems that when the pins are linked the IR signal disappears.  I do not even get any voltage readings on that wire. If I disconnect the pins the IR signal works again and I get voltage readings on the wire.
Can anyone tell me what is going on and how can I make it work.  Is even possible?  Or what I have concocted is just plain silly?
Thank you!

To be honest, how you are working around your interrupt problem is confusing.  There may be a better way.  Regardless, how to OR together open collector outputs is an interesting problem to solve.

I hope you see that by "working around" your first problem, you created another problem. Why don't you just break out of your while when it is holding on too long? Fixing software issues in hardware is just not the path to go.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.

It is likely that the Arduino's digital output is of a totem poll type.  That is, it is both actively being driven high and low.  And when high, is probably over powering the IR sensor's signal.  You should not use this setup!! As it could possibly short out both your processor and IR sensor.
Instead you could emulate an open collector Arduino output.  By switching the second pin from a digital input to a digital output sending 0 then back to a digital input. (Never set this pin to digital output and send a 1 as this could short to ground through the IR open collector.)
I am assuming that the IR sensor, when activated, is momentarily pulling a pull up resistor low through the open collector to ground.  Let us know if this is incorrect as the above description would then not apply.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.

Wouldn't it be easier just to have the interrupt call a function, that you also call after 5 seconds are up? This sounds a round-about way of doing it.
If you must do this, setting your other pin to output is not correct, because then the IR sensor and your other pin (7) are fighting each other. You should set the pin to input, and when you want it to do something briefly make it OUTPUT, and send HIGH. Then send LOW, and go back to INPUT.
However this might still make the output pin "fight" the IR sensor pin.

But the IR signal seems to be disabled and not functioning while it is waiting for the time limit.

Naturally, as your output pin is holding the line low.

If the sensor just uses a pull-down resistor (and not actively drive the line low) then my scheme should work.

However a simpler scheme is just to set a flag in the ISR, (which you test for in the main loop) and if the flag isn't set within your timeout period, do whatever you want to do if it times out. Then you don't need to try to trigger the interrupt yourself.

Thanks everybody for the help, and God Bless this forum and its members.  I do not know what I could have done without it…
Software solution is exactly what I needed, but because my knowledge of Arduino and programming is so meager I just did not know how to get out of the “while” loop properly.  The “break” was exactly what I needed All works great!
I was so caught up in trying to trigger the interrupt pin I could not see the forest for the trees.
Here is the link to the video of the prototype I am working on.
https://www.youtube.com/watch?v=--y6LWQXjzw
Thanks again!
Vladimir.


text:
Split string into an array of string
I have a SIM900 module connected to an Arduino Uno, using an AT command for listing the SMS I get this output, how can i split this based on (,) to store each data in an array?
AT+CMGL="ALL"

+CMGL: 2,"REC READ","+639321576684","Ralph Manzano","16/04/25,21:51:33+32"
Yow!!!

OK

Since arduino is very limited in memory and available flash, I suggest you to avoid trying to split the whole line in chunks, but rather just take the segments you need. If you can't, then it would still be better not to store it, but rather analyze the segments one by one while you read them. Anyway I suggest you to parse the whole line one char at a time and check it, but be careful that there is a comma also between the date and the time, so if you don't want it to be split you should also group the parameters according to the double quotes

You could try to use strtok. Code from my mind and not tested:
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char string[] = "AT+CMGL=\"ALL\"\n"
    "\n"
    "+CMGL: 2,\"REC READ\",\"+639321576684\",\"Ralph Manzano\",\"16/04/25,21:51:33+32\"\n"
    "Yow!!!\n"
    "\n"
    "OK\n";
    char delimiter[] = ",\n";

    // initialize first part (string, delimiter)
    char* ptr = strtok(string, delimiter);

    while(ptr != NULL) {
        printf("found one part: %s\n", ptr);
        // create next part
        ptr = strtok(NULL, delimiter);
    }

    return 1;
}

Outputs:
found one part: AT+CMGL="ALL"
found one part: +CMGL: 2
found one part: "REC READ"
found one part: "+639321576684"
found one part: "Ralph Manzano"
found one part: "16/04/25
found one part: 21:51:33+32"
found one part: Yow!!!
found one part: OK

thank you so mcuh! but the strings may vary depending on the message sent, who sent the message and when it was sent, how can i parse this?

@Ralph I updated my answer. You can have multiple delimter. I think you should be able to parse all the needed information out of the string you get ;)

ohhh thank you! does this mean ill just store the response of the at command in the string[] array? and ill be able to parse it despite the content?

@Ralph imho yes

sorry im really new to parsing, will definitely try this, thanks!


text:
How can I interface HMC5883L compass board to a smartphone with OTG?
Friends... I have an idea to attach the compass sensor (HIMC5883L) with my  android smartphone using arduino, but I don't clearly know how to do this. I mean I want to make an OTG compass for smartphone for map navigation etc.(Many Smartphones have compass but mine have not).  If anyone had do this or know how to do this, please guide me. Thanks!

Bluetooth might be easier. I'm not sure if OTG and Arduino go along fine.

A cheaply available USB OTG adapter cable (ask eBay) will connect the Arduino to the phone.
You can then connect the compass sensor to your Arduino and write a sketch to retrieve the data from it and send it through the USB serial connection.
Then you need to write some software for the phone to receive and interpret the serial data and display it as a compass.  That is unless you are happy just to have a simple text display (like the Arduino's Serial Monitor) with the compass information showing in it, in which case there is off-the-shelf software that would do that (search Play)


text:
Measure current and consumption
I'm trying to measure kWh with an Arduino that I have connected to a ESP8266 that communicates this value to a web server I have. And I've been trying to find the best and easiest way to go about this.
I'm thinking that I can hook a PMAC903 up to the Arduino using the interrupt pins and measuring the pulses, but I don't really know how I'm supposed to do that? Will it even work? Is this the way it's normally done? I can't really say I've found an easy solution to measure current.
You can find documentation for the PMAC903 here and I'm currently in possession of an Arduino Uno that I'm using.

You might get away with only the ESP8266, it's good enough to count pulses. The PMAC also seems to talk "Modbus-RTU protocol" RS485. I figure you're trying to measure consumption of a house and not something like the consumption/current of an LED?

Somewhat related project

The state of this meter can be read in 3 ways:

Pulse, this is very easy to implement. But depending on the stability of the hardware u can miss pulses leading to inaccurate values. In this way u have to calculate the meter value yourself.
RS485, this is a communication bus not default on arduino. But given this link https://arduino-info.wikispaces.com/RS485-Modules i think it is doable but not easy. This will read the value from the meter.
M-Bus: There is special hardware needed to interact with it. This is the industry standard of doing it. It's not cheap. But u can link many meters together. This will read the value from the meter.

Depending on your time/knowledge/other requirements u have to make a chose what way your going to use.


text:
Power Arduino from 230v with battery fallback
I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be
Here's the current setup:

Arduino running off the 9 V battery
A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
Arduino is reading light level from the light meter every 200 ms.
Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.
Problem
In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.
Idea
But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.
I could approach it in two ways:

When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.
If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:
a) have Arduino on all the time, regardless of whether button is pressed or not
b) power Arduino from the doorbell to avoid having to use a battery
Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)
Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?
Or maybe I'm missing some easier, simpler solution here?

This kind of setup lasts around 2-3 days off a single battery.

I measured 15.8 mA consumption on my Pro Mini, running from 9V. A typical 9V battery may have a capacity of 500 mAh, so that is 500 / 15.8 = 31.6 hours. Thus your observed consumption is about right.
Probably 10 mA of that is the LED, so removing it would help. I have a page about power saving. You would want to investigate going into sleep mode, and waking long enough to check the light. You might be able to arrange a LDR in such a way that it generates an interrupt and wakes the processor immediately from a deep sleep.

Example of waking using an LDR
I made up a test like this:

D2 is one of the external interrupt pins so we can write a simple low-power sketch that sleeps all the time until the LDR gets enough light that the resistance drops, and D2 goes HIGH.
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precautionary while we do other stuff
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  }  // end of setup

void loop ()
{

  // flash LED 5 times
  for (byte i = 0; i < 5; i++)
    {
    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
    delay (100);
    digitalWrite (LED, LOW);
    delay (100);
    }

  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes high
  attachInterrupt (0, wake, RISING);
  EIFR = bit (INTF0);  // clear flag for interrupt 0

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

My example just flashes an LED on pin 9 five times, that is where you can play your doorbell sound. Now, with no major external circuitry (like LEDs that are always on) it should have low power consumption.

What would be a good replacement for it, with low power draw and support for interrupts?

The LDR as described above. I measured 3 µA through the LDR when it was partly covered with a black box (my glasses case) and the room lights off. However it was daylight. I think that is pretty acceptable.

Come to think of it, you could probably turn this into a nice "doorway detector" (like they have in shops where it plays a sound when you break a light beam at the doorway). By arranging the LDR in a tube at one side of the door, and shining a light across the doorway into it (and probably tweaking the resistor values a bit) it would play a sound once you cross the beam.

Thanks! So if I'd remove the LED, I'd prolong battery life up to ~500 / (15.8 - 10) =~ 3.5 days. That's fine, but the big savings would be if my light meter supported interrupts, Unfortunately, BH1750 I use doesn't - no mention of "interrupts" here. What would be a good replacement for it, with low power draw and support for interrupts? I don't need a big resolution, light meter and a bulb are going to be in a box, so it'd be very dark inside when bulb is off. Also, do you have any pointers for the powering Arduino from a AC + battery?

See amended reply.

That's interesting. If I'd follow instructions here and disabled built-in LED, and then followed your sketch, by using a single 500mAh battery I could get 500mAh / (0.0541mA+0.003mA) / 24h =~ 365 days. And I even could use couple of AA batteries to go beyond that. Obviously minus speaker power consumption. Let's try that, but first I need to practice using multimeter to actually measure this stuff, and order LDR. Many thanks!

You can run a Pro-Mini just fine of a battery. It's the UNOs that cause a lot of problems, because of the onboard USB-to-Serial chip. The only thing you might want to tweak on this board, is removing the power-led, which I've recently done with a knife.
I poll the reflectivity of my power-meter every 250ms, and I'm getting at least 3 months of battery life out of 2 AA-batteries.
Depending on the light sensor you are using, you could even use interrupts to wake up the Arduino when the light is on, instead of having to poll every few milliseconds.

Thanks! I read about removing this LED. I'm surprised you get as much as 3 months of life with polling every 250ms. Maybe my speaker draws some power then, when off? I connected it to one of the outputs via small resistor and a NPN transistor. Collector and emitter are connected to battery VCC and GND. It's a simplest, 8 Ohm, 1 Watt speaker. I also used different battery, the 9V rectangular one. And I'm getting 2-3 days, measured on a brand new battery.

Do you put the arduino into sleepmode? Not just using delay.

I think so. I used "Low Power" library - here's the relevant line in my code: https://github.com/kamituel/arduino/blob/master/src/doorbell/rtttl_bin/rtttl_bin.ino#L43

The BH1750 takes around 16ms to do a measurement, so you are are already spending 15% of the time awake. I'd suggest just using a simple LDR (light dependent resistor) instead. They are only a few cents, and will be more than adequate in this case. Do you have a multi-meter, so you can measure the (average) current consumption? Low power can be hard to figure out sometimes. There's a lot of variables.

I did just borrow one, but it has quite big "plugs" so it's hard to connect it to the breadboard, so I wasn't able to measure anything meaningful. It's not "arduino-specific" multimeter,  rather one that can be used in more electric application. Can you recommend one that would be more convienient to use, would be sensitive enough to cover this kind of applications, and also not overly expensive? :)

Those "plugs" are standard on multimeters. There aren't any "arduino specific" multimeters. Any simple multimeter will be fine for a beginner. I got mine for 20 euro at a local hardware store. Not the best, but fine for basic usage. You want to measure the current used, so you put the meter into mA mode. Just place two wires with one side into the breadboard, the other two ends of the wires, you can just press against the two "plugs" with your fingers.

A small solar cell would not require excitation and would probably generate enough voltage to trigger an interrupt pin and wake up the MCU.

If you make it so that the light only goes out when you press the button, and connect a battery charger with that bulb in parallel, put a battery in the charger and plug the arduino into the battery, then use the light sensor approach to detect the button press and play a tune, it would work just fine... Really the only 3 things you might wanna worry about are the user holding the button for a few hours (which is very unlikely), power outages (can be solved using a UPS), and replacing the battery/bulb once every few years, depending on how good it is... Probably the simplest approach, not sure if it is the best tho...
But why not just plug the arduino to a phone charger that is then connected to the wall, and then use the doorbell switch as input for the arduino?


text:
Use distance sensor to trigger LED strip and stay on while the person is in range
I'm trying to use a distance sensor to trigger an LED light, as you can see below. However, I also want the LED to stay on/white when a person is within the 38 inches range. How should I do that?
//Tell the Arduino IDE to include the FastLED library
#include <FastLED.h>

//Setup the variables for the HC-SR04
const int trigPin = 9;
const int echoPin = 6;
//Setup the variables for the NeoPixel Strip
#define NUM_LEDS 60 // How many leds in your strip?
#define DATA_PIN 4 // What pin is the NeoPixel's data line connected to?
CRGB leds[NUM_LEDS]; // Define the array of leds

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
}

void loop() {
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The sensor is triggered by a HIGH pulse of 10 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(2);
  digitalWrite(trigPin, LOW);

  // Read the signal from the sensor: a HIGH pulse whose
  // duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  if (inches <= 38)  {
    for ( int colorStep = 0; colorStep < 256; colorStep++ ) {
      int r = 255 - colorStep;
      // Redness starts at zero and goes up to full
      int b = 255 - colorStep;
      // Blue starts at full and goes down to zero
      int g = 255 - colorStep;
      // No green needed to go from blue to red
      // Now loop though each of the LEDs and set each one to the current color
      for (int x = 0; x < NUM_LEDS; x++) {
        leds[x] = CRGB(r, g, b);
      }
      // Display the colors we just set on the actual LEDs
      FastLED.show();
      delay(10);
    }
  } else if (inches > 38) {
    fill_solid( &(leds[0]), NUM_LEDS /*number of leds*/, CRGB::Black);
    FastLED.show();
  }
  delay(1000);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second). This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

Your code appears to be doing just that. Could you explain what the current code is doing, that you want different?

You could set the pinmodes in the setup, for improved performance, but other than that, your code looks sane. As Gerben said, what is the actual problem here? Try uncommenting the "fill solid white" function in your if? En commenting the colorwheel thingy

if (inches <= 38)
That You might want to change. Try using "while(inches <= 38)" and moving sensor calculations to that loop. When ever the distance stays less than You want the light should stay on.


text:
Arduino Nano not showing up in /dev
When I plug in my nanoatmega328 to my computer, nothing shows up in /dev as I expect it to. If I plug in my Uno, /dev/ttyACM0 shows up. I have tried several Nanos.
Linux Mint 17.2.

Genuine Nano or cheap Chinese clone?

@Majenko Genuine uno, cheap Chinese nano.

lsusb and dmesg are key points of investigation - you are looking for a USB device and or failure or driver messages after insertion.  Something that is not CDC/ACM would probably be more likely to be /dev/ttyUSB0 or similar, if it recognized with a driver available.

usb-devices is also useful - it can show what driver (if any) is attached to a USB device.

It is not showing up in lsusb. Cannot decipher anything useful from dmesg.

dmesg should be the tool to help you.
Run:
$ dmesg -w

Then hit return a few times (to get some blank lines).
Next plug in your Nano.  Some text should appear on the screen, which will give you a clue as to what is going on.  I don't have a Nano to try with, but a typical working device would look something like:
[29125.599800] usb 9-1.4.1: new full-speed USB device number 13 using ehci-pci
[29125.694742] usb 9-1.4.1: New USB device found, idVendor=04d8, idProduct=0208
[29125.694747] usb 9-1.4.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[29125.694749] usb 9-1.4.1: Product: Lenny
[29125.694751] usb 9-1.4.1: Manufacturer: chipKIT
[29125.694753] usb 9-1.4.1: SerialNumber: CK1660A05353C5
[29125.695213] cdc_acm 9-1.4.1:1.0: This device cannot do calls on its own. It is not a modem.
[29125.695240] cdc_acm 9-1.4.1:1.0: ttyACM0: USB ACM device
[29125.695768] cdc_acm 9-1.4.1:1.2: This device cannot do calls on its own. It is not a modem.
[29125.695791] cdc_acm 9-1.4.1:1.2: ttyACM1: USB ACM device
[29125.697772] input: chipKIT Lenny as /devices/pci0000:00/0000:00:1a.7/usb9/9-1/9-1.4/9-1.4.1/9-1.4.1:1.4/0003:04D8:0208.0004/input/input19
[29125.698394] hid-generic 0003:04D8:0208.0004: input,hidraw2: USB HID v1.11 Mouse [chipKIT Lenny] on usb-0000:00:1a.7-1.4.1/input4

If it doesn't know what the device is it will give you a fraction of the information, and probably tell you it can't attach a driver.
If the device is faulty and not recognisable you will get messages similar to:
[29125.698394] usb 2-2.1: device not accepting address 5, error -71

If you get absolutely nothing displayed then it can't even recognise that anything has been attached to your computer.  Try different USB sockets and different USB cables to see if that helps.
Note: some cheap USB cables used purely for charging small batteries don't have any data wires in them - just power. Using one of these will fail for sure.

Thanks, this clarified the issue for me. The Nano seems to mount by default on /dev/ttyUSB0 whereas the Uno mounts on /dev/ttyACM0, which is what I was used to.

Did you try with lsusb and dmesg?
They should show if the Arduino was detected and what are its parameters (use lsusb -v for more detailed info).
If it is detected but you do not get the corresponding tty device, it might be because of missing/different rules.
You could check out this link and edit the parameters idProduct and idVendor to match what you get from lsusb, in case your rule is not matching.
Then remember to reload the modified rules.
Protip: compare the parameters of your working Uno against the ones from the Nanos and the values set in the rules.

Not showing up in lsusb. Nothing helpful in dmesg

Are you sure that the Nano works? Have you been able to make it do something? In some cases they are shipped blank, without even the bootloader and the only way to make them work is to use an external programmer.

Like Majenko said, if dmesg shows nothing then your cable could be to blame. It could be for power only (no data lines). This happened to me. I wouldn't have even thought of the cable if I did not read it here.
My hardware is also Arduino nano clone (atmega238 + ch340) and the machine runs Ubuntu 15.04. With a good cable the device is recognized like this (dmesg -w):
usb 4-2: new full-speed USB device number 24 using ohci-pci
usb 4-2: New USB device found, idVendor=1a86, idProduct=7523
usb 4-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
usb 4-2: Product: USB2.0-Serial
ch341 4-2:1.0: ch341-uart converter detected
usb 4-2: ch341-uart converter now attached to ttyUSB0

No it was because it was a Chinese clone which don't have serial numbers.


text:
Can't figure out how to distribute the power
so I'm making a project, kind of BB-8 droid replica, and I stumbled upon a problem. Since I am using two RC brushless motors, ESC's and batteries, I want to make my Uno board fed up from those batteries. Also, I want to use inductive charging set that would charge both batteries. Can anyone tell me or give some kind of scheme how should I distribute the power from batteries and what additional boards should I buy?

Comments are not for extended discussion; this conversation has been moved to chat.

The best option is to connect the 5V/2A output of the UBEC to the 5V pin on the Arduino. In my experience, 7.4V is not enough to feed into the input jack on an Arduino especially if it is from a battery, as the voltage will drop when current is being drawn by other loads. I have built an Arduino controlled robot using a 6V NiMH battery and brushed DC gearmotors (so no ESCs or UBEC) and used a $5 5V 1A step-up/step-down converter so that even if the battery voltage dropped below 5V, it could still power the board. However, since you have a UBEC that is not in use, use it. Note that if you put voltage into the 5V pin, disconnect it when you are connecting the arduino over USB or you might damage your board.
As for inductive charging, I don't know of any off-the-shelf solution designed for charging a 2S lithium ion battery. The best option for charging would probably be an easy way to open the ball to access the batteries.

About that problem You wrote in bold I had already known since I tried programming my ESC.

EDIT
I agree that opening and then charging would be the best choice but I'm making this as a gift and not much people have Li-ion chargers laying in their houses :D so the idea is to make it like Sphero BB-8 which is with inductive charging system. I found something in adafruits page https://www.adafruit.com/products/1407 which might work just fine because it would really fit into my project. The problem is that I would need a board that would take power from inductive set to charge the batteries... but any sketch I  have made is messed up and I don't want to try anything that I don't get it.

That inductive charging system is only capable of 5V at 500mA. You could easily step this up to charge a 6V or 7.2V NiMH battery as they are relatively forgiving about charging conditions, but it would probably be difficult (as well as dangerous) to try to charge a 2S LiPo this way.


text:
Gesture sensing TV coffee table - what sensors would you use?
A 32 inch flat screen was embedded in a coffee table and covered by a protective layer of glass. Sensors around the edge of the glass surface need to be able to detect the precise location of an object on the glass so that a mouse cursor can be controlled with a stylus.
What sensors would you use to ensure accuracy of stylus location above the screen?

"precise" doesn't mean much - you should be more specific and define the desired spatial resolution: what is the minimum distance you need to discriminate?

Perhaps I didn't state a level of accuracy because I wanted to encourage a wider range of replies @igorStoppa. Unfortunately this also encourages your not very helpful reply. A minor side effect.

The helpfulness of the replies you receive is correlated to the precision of the questions you ask. If you are open to a wide range of options, you should say so, instead of intentionally asking vague questions, hoping that they will bring a variety of solutions. My previous reply was meant to show you how to ask better question.

It sounds like you want a glass capacitive touch screen like on a tablet.  While you can get them this large, you usually have to buy the monitor already integrated with the capacitive touch screen.  I have never seen it were people add the capacitive touch screen afterwards.

Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection (FTIR) IR scheme.  But at that shallow angle it will be tricky and may require several cameras around the edges.

added later...
Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen.  FTIR is better when you project the image onto the touch screen.
If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel.  Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons.  Not enough to control a mouse with any accuracy.  But enough to control a GUI designed with such constraints.
Loose high resolution capacitive touch screens can be bought with out a monitor.  However they tend to be much smaller then 32 inches.


text:
DVD drive stepper motors with polulu a4988 on Arduino
I am new to arduino, I started learning about it today and i'm stuck. I ripped out a small stepper motor from an old DVD drive. I got a polulu a4988 driver and I have wired it up as follows:

/*     Simple Stepper Motor Control Exaple Code
 *
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *
 */
// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}
void loop() {
  digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000); // One second delay

  digitalWrite(dirPin,LOW); //Changes the rotations direction
  // Makes 400 pulses for making two full cycle rotation
  for(int x = 0; x < 400; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(1000);
}

But nothing happens, the motor doesn't even vibrate. Any idea what could be wrong?

Check the data sheet and see if you can truly leave all of those pins on the left side unconnected.  Additionaly, you need the /sleep pin high - you seem to be hoping there is a /pullup resistor on the reset line which will accomplish that for both of them?

According to Pololu's website, the VMOT pin needs at least 8V to function. Try a 12V switching (important!) wall wart supply that can supply at least 1A instead of your USB supply. Avoid supplies that can deliver currents >3A, as they are overkill for a small stepper motor and can be dangerous if shorted. Be sure to put a large (100uF is good) capacitor across that supply to prevent voltage spikes. To prevent damaging the motor from the higher voltage, follow the information Pololu provides on setting the current limit and set it to about 350mA. If you notice the motor is too hot to touch, try 200mA.

thank you! I found a psu for an external hard drive which outputs 12v and 2A. Would this be suitable?

That is almost definitely a switching supply and it should be suitable. Make sure that you pay attention to the polarity when hooking it up.

Great, thank you. I still haven't got it to work, my arduino switches off for some reason. Not sure why though.

I recently bought one of these and it had an internal short from the STEP pin to ground. This caused my Arduino to shut off too. Check all the pins connected to the Arduino with a multimeter to see if there are any shorts to ground, VCC, or VMOT. Post a picture of your soldering and wiring too. The Arduino should not be shutting off if this is wired correctly

Oh I see, i'll do it as soon as i get home tomorrow! thanks for your help, I really appreciate it :)

It turns out my arduino is fried. Not sure when/how that happened. I ordered a clone now and i'll try it again and see if it works! Thanks for your help

Is it the entire arduino or just one of the pins connected to the A4988?

Before you connect it to the arduino, connect the motor, hook up VMOT and its ground pin to your 12V supply, connect Vcc and its ground pin to your USB 5V supply, connect RESET to SLEEP, connect DIR to Vcc, put a 10K resistor from STEP to GND, and wire a pushbutton from STEP to Vcc. Turn on the power supplies and press the pushbutton. If the motor does not move, it could be that the motor is wired incorrectly (likely), the motor is defective (unlikely) or the A4988 module is damaged (somewhat likely). If you can't get it working in this configuration, contact Pololu customer service.

authors: مصمم الدواسر