Designing around Output pin limitations I'm new to Arduino and am working on a project with my son.  We are using the LillyPad USB board (schematic) to drive a bunch of LEDs (LED Datasheet).  Our project is based loosely off of the 'Turn Signal Biking Jacket'.

Our project calls for 7-11 LEDs in parallel on a single circuit.  In the 'Turn Signal' project the LEDs are driven off of a pair of output pins (1 HIGH and 1 LOW).  In a circuit that looks like this...

simulate this circuit – Schematic created using CircuitLab

Is this ideal?  Would it make more sense to connect the LED-chain to Vcc and have the return line connected to a single output set to LOW (to turn on the lights)?

If we were to have 3-4 of these LED-chains on at once, do I have to be concerned with total draw on the microcontroller?

Help? Thoughts?

If you know the forward voltage of the LEDs you can easily do some calculations.

For a typical red LED the forward voltage is around 2V.  Other colours vary.  So we can work out that, at 5V supply, each LED with its own 150R resistor, would take:

     V    5-2
I = --- = --- = 20mA
     R    150

With 11 LEDs in parallel on at once that would be 0.02 * 11 = 220mA.

That is far more than the 25mA an IO pin is able to supply, so you will damage the Arduino doing it like that.

Instead you will need to switch each chain of LEDs with a transistor of some form.  I'd choose a logic-level N-channel MOSFET as a "low-side" switch:

simulate this circuit – Schematic created using CircuitLab

Now your Arduino doesn't care about the current - all it sees is the MOSFET.

If your LED forward voltages are less than 2.5V you can also chain them together to halve the current:

simulate this circuit

Since the forward voltage is now double you use a smaller resistance to set the current (R=V/I, where V is 5-2Vf).


exchanging data between two hc05 bluetooth modules Iam working with gyroscope and Iam trying to send its values from one bluetooth(HC-05) module to another bluetooth module but the data exchange is not happening and I have used 2 arduino boards to do it.

Is there a simple way to do it?

I think there is no simple answer for that. First you have to pair 2 HC-05 modules. To do so, you have to configure one HC-05 as slave, and other HC-05 as master.

Steps for SLAVE:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Note the values of AT+PSWD?, AT+NAME? and AT+ADDR?(let's say 1111:22:123456) commands. You might set the password to 1234 for easy remembering. Issue AT+PSWD=0000...
Be sure to set the module to slave mode by issuing AT+ROLE=0 command.

Steps for MASTER:

Be sure to select correct Baudrate in your Terminal Emulator (Arduino IDE or Terraterm etc.) for your module. There is no default baudrate... Different manufacturers set the baudrate on their HC-05's differently... 9600 and 38400 are good starting points.
Enter AT mode, by providing high level(3.3V or 5V) signal on KEY pin(PIO11)
Reset the module to its original state by issuing AT+ORGL command.
Remove the previous parings(if any) by issuing AT+RMAAD command.
Set same password as slave by issuing AT+PASSWD=0000 command.
Change the role to master; AT+ROLE=1
Set connecting mode to any address it sees; AT+CMODE=1
Initialize the SPP profile lib ; AT+INIT
Be sure that you see the slave HC-05 module, AT+INQ command will list the modules you see.
Be sure that you see address of the slave module(1111:22:123456).
Last of all enter AT+LINK=1111,22,123456(note the commas).

With these steps you should exchange data...


how can i use multiple 7 segment in tinckercad I need to connect 5 (7 segments ) using tinckercad.
and as we know that tinckercad doesn't have an arduino mega to use it's pins.
so how can i do that without the a MEGA ?

It sounds like you will need to multiplex them.

Assuming common cathode LEDs:

Set up a transistor for each digit that activates the ground for that digit. (Lighting all the segments of a digit will probably exceed the max current sink of one of your digital pins.) You may be able to drive a single segment directly from an output pin, assuming it's current draw is ≤20 mA. If the segments draw > 20 mA then you will likely need transistors for the segment drivers as well. (The max output of a pin on most Arduinos is actually 40 mA, and if the average current when multiplexed across 5 digits is < 20 mA, you might get away with drawing up to 40 mA per segment. I'd ask somebody with more electronics experience than me to confirm this.)

Write your code to switch one digit's ground on at a time, after turning on the desired anode (segment) pins. Cycle through the digits rapidly and they will all appear to be on at the same time.

The pseudo-code:

setup {
   digit index = 0
   turn all pins (segment anodes and digit cathodes) to open state
}

loop {
   set up segments pins for digit[index]
   Turn on cathode for that digit
   short delay to allow segments of current digit to glow
   turn off cathode (ground) of current digit
   digit index = (digit index + 1) % num_digits
}

The above would require a digital pin for each segment, and a pin for the ground of each digit. (7 + 5 = 12 digital pins total.) Without multiplexing, you'd need 7x5 = 35 digital pins, and would still have to make sure you didn't exceed the total current output limits of the Arduino. (35 segments x 20 mA/segment would be 700 mA total.) Most Arduinos have a total current output of no more than 200 mA across all pins, so you could not light up all the segments of more than 2 digits at once, assuming 20 mA/segment.)

Note that it might be easier to ignore all of the above and get a serial LED display driver like a MAX7219. You just need 2 digital lines to drive that, and it will control 8  8-segment digits (7 segments plus a decimal point at each position)


Write to serial only if the state of a light sensor changes I need to know the times when an LED strip turns on and turns off.  The LED switch is driven by light dependent resistor.  When the sun goes down the LED strip turns on. This is all happening on a circuit that I did not create nor is it Arduino driven.  I need to know the times (in local time) that the LED turns on and off.  I have another light dependent resistor near the LED strip and I am using the Arduino Uno to print to the serial monitor its state every second.
I can listen to the serial port via Python and record the seconds via Python.  No worries
What I would like to do is have the Arduino code print to the serial monitor only if the state of the LED changes.  For example, when the LDR turns on the LED strip, Arduino prints to the serial monitor once, then in the morning when the LED goes off, print to the serial monitor once.  I am having trouble figuring out the code to do that.  The LDR is not like a button since it is always reporting back analog data.    Any help is appreciated.

You wrote: “I am using the Arduino Uno to print to the serial monitor
its state every second.” This is exactly the right thing to do. Make a
record of the analog readings for a few days, then plot the readings as
a function of time.

Once you have a nice plot, take a close look at it. You should be able,
by reading the plot, to decide on a threshold value that you can use to
tell whether the LEDs are on or off. Or, better yet, two thresholds in
order to have some hysteresis.

Then you can write something like this:

const uint8_t LDR_PIN = ...;
const uint16_t THRESHOLD_LOW = ...;
const uint16_t THRESHOLD_HIGH = ...;

uint8_t state = LOW;

void loop()
{
    uint16_t reading = analogRead(LDR_PIN);
    if (state == LOW && reading >= THRESHOLD_HIGH) {
        Serial.println("Reading is now HIGH.");
        state = HIGH;
    } else if (state == HIGH && reading < THRESHOLD_LOW) {
        Serial.println("Reading is now LOW.");
        state = LOW;
    }
}


Wireless Communication with NRF24L01+ I have decided to use NRF24L01+’s for my Arduino project for wireless communication. I am using the RF24 library by TMRh20 to talk back and forth.

Github Link: https://github.com/nRF24/RF24

I want to be able to send and receive data as fast as possible between the remote, and the receiver. After reading through the library I was able to create a some simple code that allowed the remote to transmit ~600 32-byte messages a second and the receiver was able to read ~490 messages a second.

Transmitter Loop Code:

if (radio.available())
  { radio.read( &myData, sizeof(myData) ); }

Receiver Loop Code:

radio.write( &myData, sizeof(myData), 1);

With this code however, the remote control cannot receive telemetry data back from the receiver. It is only a one way communication with no acknowledgments.

I have a few questions about wireless communication with the NRF24L01+. First, what is an acknowledgement? I understand it is a way for the transmitter to know that the receiver got the message, but what is being sent in the acknowledgment?

What is the difference between commands such as radio.write, radio.writefast, radio.startwrite, and radio.startwritefast. The RF24.h file has explnations of these commands but their desrciption does not make too much sense to me.

After doing some research, I found that to write, I must stop listening, write the message, and then start listening again for messages. The issue with this code is that the NRF is never listening long enough to receive a message (unless I add in a delay where it stays in RX mode). Is there anyway to keep a reading pipe open while writing and then pick it up from the FIFO when I am ready to read?

It seems that it is possible to write an ACK Payload, and this allows the NRF to transmit a message without leaving RX mode. Is this a possibility, and what is an ACK Payload?

What is the best practice for achieving the fastest speed two-way communication. Is it common practice to have two NRF’s and have one dedicated to listening and one dedicated to writing on each Arduino? Is there a good way to achieve high speed two-way communication rates with a single NRF?

firstly, the radio.write command is used for checking for the acknowledgement from the RX after the FIFOs are full for a single write. But radio.writefast will not wait for the acknowledgement from the RX and would continuously transmit the payload for a single write. Similarly for radio.startwrite and
radio.startwritefast commands.

Coming to the keeping the NRF in listening mode, even I haven't tried it before so I cannot suggest an exact solution for this problem. But as far as I know,  you can go for writestart command to keep the reading pipes open while you are sending. But I would personally suggest you to confirm this from datasheet again before experimenting.

For ACK payload, it depends upon the master unit controlling the SPI communication with the NRF chip and thus, by maintaining a mutual understanding between the RX and TX units, you can define the payload for acknowledgement signal as well.

Coming to best speed possibility, To increase speed, NRF has three speeds from which you can select the highest value available. Also see which pipe/channel works the best for you so that you can achieve the least number of lost packets.


Measuring current directly with Arduino Is it safe to measure current like this as long as measured voltage drop don't exceed 5V? I'm asking this because in almost all current sense circuits they used an opamp in their design.

Do I need a resistor between shunt resistor and ADC? Is there any noticeable current flowing to Arduino ADC that can damage it?

simulate this circuit – Schematic created using CircuitLab

Let's imagine that you expect to have 1A of current going through your circuit.
Resistor of 0.1 Ohm will give you a voltage drop of 0.1V.
This causes two problems.

Firstly Arduino has a cheap ADC builtin. It's supposed to be easy to use, but not really precise. It has nonlinearities towards lower and higher range. You will get more precise reading when measuring voltages around 2.5V.

Secondly The precision of your measurement is cut by factor of 50. Arduino contains ADC that has resolution of 10 bits. This means that there are only 20 steps between 0V and 0.1V That's not really precise.

Solution? Use an opamp as "differential amplifier". If you multiply the voltage difference by 25 you will get 2.5V on the amplifier output when the resistor has 0.1V of drop on it. This value is much more precise when reading it by analogRead of the Arduino, and even a tiny change in voltage on the resistor will give you 25 times larger change on the amplifier output. This way it's much more precise and accurate.


Power on reset with arduino uno can never happen. Can this be fixed? When an Arduino Uno is powered on, the USB chip's DTR output pin may (is, in fact) low for a while.  This means that the capacitor C5 is connected from the 328p reset pin to ground.  Thus, when power is applied, the reset pin is held low for 10's of milliseconds after power up (while C5 charges) .

Thus, when the 328p starts, the reason for reset (the MCU register) always is "external reset", not "power on reset", even when  power turns on.

This can be fixed by removing C5, or opening the "reset en" jumper, but then the chip is never reset by the falling of DTR,...that is, bootloading is disabled.

Is there a solution that allows POR and external reset for the bootloader?
Thanks!

See 'DTR-reset' circuit of Arduino Uno below.

After powering-on, when DTR is set low (because a sketch is coming in) the falling edge causes a negative pulse on the 328P's external reset pin of ca. 3 ms (see here). The width of this reset pulse is independent of the time that DTR stays low.

During powering-on the 328P's reset pin is low until the capacitor C5 is sufficiently charged. How long this takes depends mainly on the start-up behavior of Vcc. When DTR is low the capacitor will charge faster because RN2D (from capacitor C5 to ground) is bypassed.

But the main thing is that the power-on reset and the external reset have the same effect (see datasheet): when the rising voltage passes a certain threshold a timer is started and after it times out program execution starts at 0x0000 or at the Boot Reset Address (depending on the setting of the fuses). So, in the powering-on situation it makes no sense to differentiate between Power On Reset and External Reset.


Unable to load programs onto Arduino Pro Mini Using FTDI? I'm pretty new to this, so forgive me if I get some things wrong. I am working with a piece of equipment that uses an Arduino Pro Mini. When I first got to it, I realized that some of the code was incorrect and wanted to fix it. Unfortunately, my Pro Mini is soldered into the board with the labels and pins down, so the only accessible pins are the top six, and even those aren't labeled. The reset button is also upside down. I tried using a FT232H FTDI
hooked up (using a pinout because of the aforementioned no labels)

D0-> TX

D1-> RX

which I was told should work, but when I plug in the micro-usb into the FT232H and try to upload the sketch, it gives me the error

avrdude: stk500_getsync(): not in sync: resp=0x00

and also blinks green but has a constant red light (from what I can see from looking under the board). Because this Pro Mini controls my equipment, I'm wary of doing anything too intense. Any ideas of how to fix this without breaking my apparatus?

Update!
I changed the pinning, and the IDE told me that it uploaded, but it still won't run the program! Help!

Same problem faced. Try out many times with proper connection but no success. After that, I found one unique and simple solution. I use Arduino Uno instead of FTDI. Follow below step, your problem will definitely solve.

First, remove Arduino Uno's IC means ATMEGA 328P-PU.
Now, do connection as shown in below figure.

Connections are like:

Arduino Uno(Without Chip)     Arduino Mini Pro

          RX                         RX
          TX                         TX
          +5V                        Vcc
          GND                        GND
         RESET                  RST(RESET PIN)

Now, plug your Arduino Uno to your computer and open your Arduino IDE.
Now, an open sketch which one you want to upload. Now, go to Tools and select board in which you want to upload code. Below, show in the figure.

Now, upload your program. It will definitely work.

I hope it will help you.


Is it possible to sample sound with arduino? I have the arduino duemilanove with atMega328.
The frequency is 16Mhz.

I want to sample and record from the audio jack.
I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.

That means this is unfeasible with my arduino, since my frequency is only 16MHz?

For the AtMega328's ADC the datasheet says

  • Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.
If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.

Edit:

To answer Connor's comment:
Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.

But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)


Implementing an external ADC in Arduino I'm planning to use a ADS1220 4-channel 24 bit adc but I really have no experience with SPI. I have found this library but I can't really understand the code that much and also this is measuring the differential voltage. I want to use this for my accelerometer (x, y and z data) but I can't seem to find how to do read from 3 channels, and I can't understand the code in the library :( I've also found a video for this adc in youtube but he didn't used it for multiple channels. I'm sorry for asking this, I'm just pressured since the deadline is really soon.

EDITED

sketch

#include "Protocentral_ADS1220.h"
#include <SPI.h>

#define PGA 1                 // Programmable Gain = 1
#define VREF 3.3
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

volatile byte MSB;
volatile byte data;
volatile byte LSB;
//volatile char SPI_RX_Buff[3];
volatile byte *SPI_RX_Buff_Ptr;

long int bit32, data1, data2, data3;
long int bit24;

Protocentral_ADS1220 ADS1220;

void setup() {
  pinMode(ADS1220_CS_PIN, OUTPUT);
  pinMode(ADS1220_DRDY_PIN, INPUT);

  ADS1220.begin();
  //ADS1220.Single_shot_mode_ON();
}

void loop() {

  byte *config_reg;

  data1 = aRead(0x81);
  data2 = aRead(0x91);
  data3 = aRead(0xA1);

  Serial.print(data1);
  Serial.print("    ");
  Serial.print(data2);
  Serial.print("    ");
  Serial.println(data3);
  delay(500);

}

long int aRead(uint8_t config_byte) {
  ADS1220.writeRegister(CONFIG_REG0_ADDRESS , config_byte);
  uint8_t r = ADS1220.readRegister(CONFIG_REG0_ADDRESS);
  //Serial.println(r,HEX);

  ADS1220.SPI_Start();

  while (ADS1220.NewDataAvailable == false) {
    SPI_RX_Buff_Ptr = ADS1220.Read_Data();
  }

  if(ADS1220.NewDataAvailable = true) {
    ADS1220.NewDataAvailable = false;

    MSB = SPI_RX_Buff_Ptr[0];
    data = SPI_RX_Buff_Ptr[1];
    LSB = SPI_RX_Buff_Ptr[2];

    bit24 = MSB;
    bit24 = (bit24 << 8) | data;
    bit24 = (bit24 << 8) | LSB;

    bit24= ( bit24 << 8 );
    bit32 = ( bit24 >> 8 );
  }

  return bit32;
}

I tried to use the above sketch and I successfully read from 3 different channels but I noticed that the readings vary too much, compared to the example code. In the example code when I turn my potentiometer full CW, it outputs 8388607 which is correct right? since it is signed int.

But when running this sketch, the image below shows the output when the potentiometer is fully CW. Also turning the potentiometer fully CCW leads to negative values (shown in the 2nd picture) but in the example code, it gives 100-300 decimal values.  Also these are the configuration registers I sent in registers 1-3 (I edited it in the part of the library) and for register 0, it is on the sketch.

Config_Reg1 = 0x00;
 Config_Reg2 = 0x40;
 Config_Reg3 = 0x00;

using accelerometer

format is (x,y,z)

To get an understanding of how to read from the various ADS1220 channels, first review Figure 38, Analog Input Multiplexer, in the Datasheet as obtained from a link on TI.com's ADS1220 technicaldocuments webpage.

As can be seen, you'll need to close a switch from an AINx input line to the AINₚ bus, and also close the switch between AINₙ and AVSS.  The IDACx switches and the BCS switches should remain open.

To operate those switches, first look at §8.6.1, Configuration Registers, in the Register Map section of the Datasheet.  You'll see that MUX bits are in register 0, BCS is in register 1, IDAC is in register 2, and IxMUX are in register 3.  To see what to put into those fields, look at Tables 16, 17, 19, and 20.  For the MUX field, you will want a binary value like 1000, 1001, 1010, or 1011 to select one of AIN0-AIN3 as the AINₚ input and AVSS as the AINₙ input.  BCS, IDAC, I1MUX, and I2MUX all should be zero.

For example, to read channels 0, 1, 2 in sequence, set MUX to 1000, set up other register fields, and trigger a conversion.  After reading the result, change MUX to 1001, trigger a conversion, read result,  change MUX to 1010, trigger a conversion, read result, etc.

Edit 1: In slightly more detail, one could do as follows.

  • Use a WREG command [as in §8.5.3.6; or some library equivalent] to send three bytes to set up Configuration Registers 1, 2, 3.
  • For i=0, 1, and 2 in turn, construct a configuration byte, send that byte to Configuration Register 0, start a conversion, await result, read result; as follows:

    Set the MUX field of a byte to i
    Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010)
    Set the PGA_BYPASS bit (as required when AINₙ = AVSS)
    Use a WREG to send the constructed byte to Configuration Register 0
    Use a START/SYNC command to start a conversion (see §8.5.3.2)
    Wait for DRDY to go low
    Use an RDATA command to read iᵗʰ ADC result (see §8.5.3.4)

Edit 2: In Protocentral's ADS1220.ino sketch, one finds the code sequence

  MSB = SPI_RX_Buff_Ptr[0];
  data = SPI_RX_Buff_Ptr[1];
  LSB = SPI_RX_Buff_Ptr[2];
  bit24 = MSB;
  bit24 = (bit24 << 8) | data;
  bit24 = (bit24 << 8) | LSB; // Converting 3 bytes to a 24 bit int
  bit24= ( bit24 << 8 );
  bit32 = ( bit24 >> 8 );     // Converting 24 bit two's complement to 32 bit two's complement

More competently and concisely, and with SPI_RX_Buff_Ptr renamed to SPI_RX_Buff, this could be written as:

  bit32 = (((long)(SPI_RX_Buff[0]<<8 | SPI_RX_Buff[1])<<8 | SPI_RX_Buff[2])<<8)>>8;

which acts as follows:  Assemble three bytes from SPI_RX_Buff into a 24-bit twos-complement-signed number.  Shift that number left 8 bits so that its sign bit now sits in the sign bit position of a 32-bit signed integer.  Shift that result 8 bits right with sign extension so that the final result is a signed 32-bit integer with possible values from -2²³ up to (2²³-1).

Sign extension occurs – usually – because in many implementations of C, the >> operator does an arithmetic shift instead of a logical shift when its operand is signed.


How to switch an external circuit with Arduino? I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.

What I've done is the following:

I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor
I connected the base of the transistor to a digital output (through a 1k resistance)
I connected the power to the led series while the digital pin was LOW (actually completely disconnected)

But with no current on the base of the transistor, the LED has turned on to my surprise. I may have completely misused the transistor and other items. How do I fix this circuit?

If I understand your writeup correctly, this is what you have built:

simulate this circuit – Schematic created using CircuitLab

What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.

Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.


How to connect a varying output voltage to the Arduino? I have a smart meter and I want to connect my output pulse meter to the Arduino in order to count the pulses, but the problem is my  output pulse voltage is varying (between 1V to 17V approximately) and the Arduino accepts only a stable voltage (5V).

Therefore, how can I make my output pulse voltage stable to connect it to the Arduino?

If “what I want is counting the pulses of my meter” means that you want to count the number of pulses the meter produces, you can use a circuit like the following to clip the voltage into the 0-to-5V range (as acceptable for inputs on Uno digital pins).

simulate this circuit – Schematic created using CircuitLab

Then, to count pulses, write a sketch that repeatedly reads the selected input pin.  Each time it changes from low to high, add one to your count of pulses.

If you don't have 5.1V zener diode like the 1N4733A, you could instead attach the anode of an ordinary diode to the junction of R1,R2 and its cathode (the cross-bar end) to 3.3V on the Uno.  This will clamp the voltage on the input pin to at most about 4V.  (Note, with such a diode clamp, there would be high-current problems if you subsequently changed the pin to a high output.  You could of course put a 100Ω resistor in series with the clamp diode if you are concerned about that.)


How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode) I have an Arduino Uno and a 555 timer configured to astable mode.

What I'm trying to do is to program my Arduino to increase a "counter" variable (counter++) everytime it gets triggered by 555 timer's output (through analogIN pin).

My problem is that Arduino takes 555 timer's output as a continuous triggering and increases my counter as long as the pulse in the analogIN lasts.
So instead of incrementing by 1, it is increased by approximately 97 (sometimes more or less).

I need to take the analog in as a "packet" so everytime analogIN is triggered, no matter how long the pulse lasts, it will be treated as a single event and not as continuous triggering.

What do I have to change?

My code:

int counter = 0;

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

}

void loop() {
  if(analogRead(A0) > 250) {
    counter++;
    Serial.println(counter);
  }

}

Thanks

You need to create a finite state machine with 2 states:

Waiting for input from 555 to go high.  When this happens increment the counter & advance to the next state.
Waiting for the input from the 555 to go low.  When this happens advance to the next state.  That is, the first state.

In the following Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial you do not need the complex code to debounce the switch.  However, the edge detection and state machine portion of the code can likely be applied to your project.


How to resolve my Timer Interrupt issue I am trying to work with arduino timer1 interrupts to make an led blink every bit on an 8 bit number, depending on whether its a 1 or 0. However, im trying to make a basic blinking program, and it does not seem to be working.

#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=1;
}

void loop()
{
    digitalWrite(13,val);
    while(!val);
    val=0;
}

The LED doesnt blink at all! Any help would be appreceitated!
thanks!

Try this instead.

#include “TimerOne.h”
bool val=0;
void setup()
{
    pinMode(13, OUTPUT);
    Timer1.initialize(500000); // initialize timer1, and set a 1/2 second period
    Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}

void callback()
{
    val=!val;
}

void loop()
{
    digitalWrite(13,val);
}


Node MCU Wifi connection problem I'm trying to connect my nodeMCU to my WiFi network also i have provided ip address  but it keeps printing ........ it is not connecting to the network. Below is my code.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Configration Parameter for Access Poin
char * ssid_ap = "";
char * password_ap = "";
IPAddress ip(192, 168, 1, 158);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255,255,255,0);

// Set up the server object
ESP8266WebServer server (80);

// Keep track of sensor data that's going to be sent by the client
float sensor_value = 0.0;

void setup()
{
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(ssid_ap,password_ap);

  Serial.begin(115200);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid_ap);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");

  server.begin();
  Serial.println("Server started");
  Serial.print("IP Address:");
  // Serial.print(WiFi.localIP());
  // Configure Server Router
  server.on("/",handleIndex); // use the top root path to report the last sensor value
  server.on("/update",handleUpdate);
  // server.begin();
}

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

}

void handleIndex()
{
  server.send(200,"text/plain",String(sensor_value)); //we'll need to refresh the page for getting the latest value

}

void handleUpdate()
{
 sensor_value = server.arg("value").toFloat();
 Serial.println(sensor_value);
 server.send(200,"text/plain","Updated");

}

You are creating a SoftAP (in essence creating a separate Wifi network). In this configuration, the ESP8266 will not "connect" to anything so polling WiFi.Status for the WL_CONNECTED status is meaningless.
To see if the SoftAP instance was created successfully, you should look at the output of WiFi.SoftAP() when you create the SoftAP instance, which returns a boolean indicating success (true) or failure. Or you should see the SSID of your newly created access point appearing on your PC or phone.
I suggest you look at the ESP8266 examples included in the Arduino IDE when you install device support for the ESP8266 to get some ideas about what you can do with a SoftAP.


Suggest me an Arduino development board, with a removable ATmega chip? I want to buy an arduino development board which has facility to remove its chip and insert a new one anytime. I want to use multiple chips in a single board for different purposes.

If it is not possible, Please suggest me any alternative.

Only the Arduino Uno has a socketed IC chip. All the rest are using soldered SMD ICs.


Configure input pullup through registers I can set pin mode to input or output through the DDRx registers. How can I enable the internal pullup resister through a register?

Credits to GoForSmoke.
Also see Gerben's comment below.
See: https://forum.arduino.cc/index.php?topic=286145.0
byte ddrcMask =       ~
(
        (1 << DDC0) |  // pinMode( 14, INPUT ); // Set to input
        (1 << DDC1) |  // pinMode( 15, INPUT ); // Set to input
        (1 << DDC2) |  // pinMode( 16, INPUT ); // Set to input
        (1 << DDC3)    // pinMode( 17, INPUT ); // Set to input
);

byte portcMask =
(
        (1 << PORTC0) |  // digitalWrite( 14, HIGH ); // Enable the pullup
        (1 << PORTC1) |  // digitalWrite( 15, HIGH ); // Enable the pullup
        (1 << PORTC2) |  // digitalWrite( 16, HIGH ); // Enable the pullup
        (1 << PORTC3)    // digitalWrite( 17, HIGH ); // Enable the pullup
);

byte pincMask = ( (1 << PINC0) | (1 << PINC1) | (1 << PINC2) | (1 << PINC3) );

void setup( void )
{
  // Configure the pins for input
  DDRC = DDRC & ddrcMask;

  // Enable the pullups
  PORTC = PORTC | portcMask;

  // Read all four inputs
  uint8_t Pdat = PINC & pincMask;
}

void loop( void )
{
}


Machine installed with arduino suddenly turns on when usb is unplugged Why is my machine suddenly turns ON when I unplugged the USB on my computer? Does it have connection on the auto reset feature of my arduino board?

String input = "";

void setup(){

  Serial.begin(9600);   // Sets up communication with the serial port

  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

  digitalWrite(11,LOW);

}

void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
    int data = Serial.read();
      // convert the incoming byte to a char
      // and add it to the string
    input += (char)data;

    recipe = input.toInt()+'0';    //recipe=0 if not a digit
    if(recipe == '0')
      recipe = data;

    if(data == '\n'){
      //Serial.print("Recipe: ");
      //Serial.println(recipe);
      //Serial.print("String: ");
      //Serial.println(input);
      input = "";
    }
  }

  if(recipe == 's'){
    digitalWrite(11,HIGH);
    delay(1000);
    digitalWrite(11,LOW);

    digitalWrite(6,LOW);
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
  }

  else if(recipe>'0' && recipe<'32'){

    recipe = recipe-'0';
    char binary[7] = {0};   // This is where the binary representation will be stored
    recipe += 32; // Adding 32 so that there will always be 6 digits in the string
    itoa(recipe,binary,2);  // Convert recipe to a string of base 2 and save it in array 'binary'
    char* signals = binary + 1; // Get rid of the most significant digit to get the 5 bits

  //Serial.print(signals);  // Print out the signals in binary

    int i;
    for(i=0; i<5; i++){
      if(signals[i] == '0')
        signals[i] = '1';
      else
        signals[i] = '0';
      digitalWrite(i+6, signals[i]-'0');    // write to pin; converts the bit of the string to HIGH or LOW
      //Serial.print(signals[i]);
    }

  }
  else
    loop();

}

Do not call loop from loop. You will quickly run out of RAM and the sketch will crash:

void loop(){

  int recipe;
  //Serial.print("Enter recipe number: ");

  while(Serial.available()==0){    // Waits for data from serial port
  }

  while(Serial.available() > 0){
...

  }
  else
    loop();

}

For the pins that are supposed to be high, I suggest pull-up resistors:

  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);   // for start of program operation

  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);

When the Arduino powers up it enters the bootloader for a second or so. Those pins won't be set high yet. A pull-up resistor would make sure they are high until such time as you want to drive them low.

If you are saying that the machine powers up when you disconnect the power to the Arduino, that is still a good reason for using pull-up resistors, to make sure that it does not operated until commanded to do so.

  where will i connect the pull up resistors and how?

Typically pull-up resistors will be around 10k, and are connected from the pin to +5V. Of course, if the Arduino is not powered, then you need another source of the +5V.

  please to clarify the "do not call from loop to loop"

Remove these two lines:

else
    loop();

When loop exits, is it immediately re-called. You don't need to do it that way, in fact it is a Bad Idea.


creating array using string name I appreciate if someone can help me.
I have a function that counts the time and I would like to store values according to the day.

For example: day_7.11.2015 = [gain = 100.23, cost = 78.0 ...]
              day_8.11.2015 = ...

I do not know how can I create an array with these values taking as input the day, month and year. Does anyone have any idea?

String test = "day_" + String(day) + "." + String(month) + "." + String(year);
float String(test)[] = {11.2, 10, 20, 31.2};
 Serial.println(test);

Thanks a lot!

What you're talking about is often called a Hash or a Map or sometimes both together as a HashMap.

Unfortunately it's a facility that isn't supported in the Arduino C++ language

There are map objects available in normal C++, but they are incredibly expensive to use with regards to memory and they just aren't practical for use on a small microcontroller with memory measured in the kilobytes.

The closest you can probably get is to "invert" the storage, so you have a list of values that happen to be in date order (because that's when you added them) but the "key", a simple sequential number, doesn't define the date.  Instead you store the date inside the array along with the data - assuming you really need to know the date.

A good concept to get to grips with for this is the struct.  This is a custom data type which you define and can store a number of other different data types within itself.  You can then make an array or linked list out of those new data types.

For instance, you may have:

typedef struct {
    int year;
    byte month;
    byte day;
    float gain;
    float cost;
} Data;

You can then create variables of type "Data" and assign values to the items within it:

Data myEntry;
myEntry.year = 2015;
myEntry.month = 11;
myEntry.day = 7;
myEntry.gain = 100.23;
myEntry.cost = 78.0;

Or assign them directly at creation time:

Data myEntry = {2015, 11, 7, 100.23, 78.0};

If you wanted to store 100 days' worth of data you could use an array:

Data myArray[100];

Then you access each slice:

myArray[0].year = 2015;
... etc ...

I mentioned above "assuming you really need to know the date".  Most of the time with this kind of method you really don't need to store the date.  If you have one entry per day and you know when you started gathering data then you know that each entry is one day more than the one before it - so you know that the tenth entry is ten days later than when you started gathering data.  Alternatively, if you have a 100 entry circular array (that is, when you reach the end of the array you start filling from the bottom again, so you keep the last 100 days' worth of data) and you know what the date is today you can count backwards from today to work out what date each entry is.


Are there ultrasonic transducers which are able to produce a "chirp" sound wave? I'm working in a ultrasonic radar project and the supervising teacher wants us to produce a chirp sound wave (a frequency-varying sinusoid).

I'm familiarised with the usual ultrasonic module, but as far as I know, it cannot do the task.

I searched on-line for transducers that I could use, but couldn't find anything useful.
Are there any commercially available component that could do this task? If not, what could I possibly do?

Piezoelectric speakers, the kind commonly found in ultrasonic transducers generally operate in a narrow frequency range when operating at ultrasonic range (a resonate frequency of the metallic diaphragm). This is very true once you get above about ~60 kHz. However if the ultrasonic "chirp" you are looking for can be in the range of say 20-60 kHz you could be in luck, i.e., http://www.conrad-electronic.co.uk/ce/en/product/710991/KEPO-piezo-element-25-60-kHz-515-mm

You could use the Tone function (which goes up to 65535 Hz) to produce the frequency sweep you desire. However if you want to go up to frequencies in the 100+ kHz range you will be delving into research territory and hence extremely expensive equipment.

Having said that, technologies change very quickly and I my knowledge may already be out of date. Hope this helps.


_delay_ms() is much slower than expected (by a factor of 6) on TinyAVR 0/1 (ATTiny1604) I designed a custom AVR development board using the Atmel ATTiny1604 microcontroller. It belongs to the new Tiny-0 family, due to its recentness, some required changes to relevant toolchains have yet to be included into the stable version  (I prefer to use the original upstream toolchains instead of Atmel/Microchip's SDK). Thus, I compiled the latest versions of toolchains from source. They include...

AVR GCC 10.2.0

avr-libc, svn trunk, with patch avrxmega3-v10.diff applied

After I installed the toolchains, I wrote a LED blinking program to verify whether my toolchain was working properly. The program was built with avr-gcc -mmcu=attiny1604 -Wall -Os -o blink.elf blink.c -Wl,--section-start=.text=0x200 and uploaded via the Optiboot_X bootloader.
#define F_CPU 20000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    PORTB.DIRSET = 0b00000001;

    while (1) {
        PORTB.OUTSET = 0b00000001;
        _delay_ms(500);
        PORTB.OUTCLR = 0b00000001;
        _delay_ms(500);
    }
}

However, I found that _delay_ms(500) doesn't work as expected. Instead of a 500-millisecond delay, the actual delay is closer to 3000 milliseconds as seen on the oscilloscope, it has been slowed down by a factor of 6.

I've double-checked my fuse settings.
$ pyupdi -d tiny1604 -c /dev/ttyUSB0 -fr
Device info: {'family': 'tinyAVR', 'nvm': 'P:0', 'ocd': 'D:0', 'osc': '3', 'device_id': '1E9425', 'device_rev': '0.0'}
Fuse:Value
0:0x00
1:0x00
2:0x02
3:0xFF
4:0x00
5:0xF6
6:0x07
7:0x00
8:0x02
9:0xFF
10:0xC5

I saw pyupdi reported that the fuse OSCCFG (No. 2) has been programmed to 0x02, which according to the datasheet, means "Run at 20 MHz with corresponding factory calibration". Why do I get incorrect delays even when the system clock is running at the correct speed? Is my toolchain broken?
Note: This is a question I already solved. But consider there are relatively few tutorials about the new TinyAVR 0/1 on the web, I posted the question and answer here to serve as a reference for the community.

Your toolchain is not broken. In the ATTiny804/1604 datasheet, page 77, it shows the CPU clock is divided from the 20/16 MHz oscillator by a prescaler (the ATTiny1614 datasheet shows the same clock prescaler in page 80. So it's a feature found in both tinyAVR 0/1 microcontrollers).

Source: Microchip ATTiny804/1604 datasheet, fair use.
The datasheet says...

10.3.3 Main Clock After Reset After any Reset, CLK_MAIN is provided by the 16/20 MHz Oscillator (OSC20M) and with a prescaler division factor of 6. Since the actual frequency of the OSC20M is determined by the Frequency Select bits (FREQSEL) of the Oscillator Configuration fuse (FUSE.OSCCFG), these frequencies are possible after Reset:

16 MHz ---> 2.66 MHz
20 MHz ---> 3.3 MHz

By default, the division factor is 6. It means the CPU is actually running at 3.333 MHz when the OSCCFG fuse is programmed to 20 MHz.
Solution
Use the correct F_CPU
If a slower CPU is not a problem to you, you can simply report the correct CPU frequency to the compiler by change #define F_CPU 20000000UL to #define F_CPU 3333333UL.
Or disable frequency division
Alternatively, you can disable the frequency division and run the CPU at its 20 MHz full speed.
#define F_CPU 20000000UL

int main(void)
{
    /* Set CPU clock to 20 MHz */
    _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0);

    /* your code */
}

But don't overclock the CPU
Nevertheless, you should note that 20 MHz operation is only guaranteed by Atmel at 4.5 V and above. If you are running the microcontroller at a lower voltage, such as 3.3 V, you are overclocking the CPU by putting it outside the safe operating area designated by Atmel. See datasheet page 473.

Source: Microchip ATTiny804/1604 datasheet, fair use.
Although an overclocked microcontroller will probably work, and in a hobby project, you are unlikely to see any issue. But still, at this point there is no guarantee of stability from the manufacturer. For example, the microcontroller is officially rated at 105°C, but an overclocked microcontroller may start crashing. Increased power consumption is also likely. The worst possible problem could be mysterious malfunction under certain rare conditions. Thus, if reliability and stability is important, you should not overclock the microcontroller.
At 3.3 V, given a 20 MHz system clock, the CPU should only operate at 10 MHz by setting the prescaler to 2x. And at 1.8 V, at 5 MHz with a 4x prescaler.
/* Set CPU clock to 10 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_2X_gc | CLKCTRL_PEN_bm);

/* Set CPU clock to 5 MHz */
_PROTECTED_WRITE(CLKCTRL_MCLKCTRLB,
                 CLKCTRL_PDIV_4X_gc | CLKCTRL_PEN_bm);


XBee shield communication I need to communicate between two Arduinos using XBee. I am new to XBee and hardware. The two Arduino Unos need to send a message (number) to each other and light an LED or play a sound, when they come close within a 10 meter distance.

So my doubt is which XBee shield and XBee module I need to purchase. I read about XBee series 2, XB24 etc.

The only way I can think of accomplishing this without some sort of proximity sensor is to measure the signal strength of the XBees.

From page 41 of the datasheet:

  DB (Received Signal Strength) Command

  AT Command: ATDB

  Parameter Range [read-only]:  0x17-0x5C (XBee), 0x24-0x64 (XBee-PRO)

   DB parameter is used to read the received signal
  strength (in dBm) of the last RF packet received. Reported values are
  accurate between -40 dBm and the RF module's receiver sensitivity.
  Absolute values are reported. For example: 0x58 = -88 dBm (decimal).
  If no packets have been received (since last reset, power cycle or
  sleep event), “0” will be reported.

You can use this as a rough estimate of the distance between two sensors. You will have to correlate signal strength to actual distance and obstructions and other factors will cause the reported value to be off.

How to measure XBee signal strength?

This page has an example using Processing (on the computer): XBee Signal Strength


Arduino DS3231 error: no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)' I am building a arduino based bicycle speedometer with time and temperature display.
Im currently stuck with the DS3231 (zs-042) chip. I found online a lot of library issues, i tried using
multiple libraries (Rinky-Dink, ds3231-master) but nothing works. I found a simple code online to test the chip but when I upload it the following error shows up: "no matching function for call to 'DS3231::DS3231(const uint8_t&, const uint8_t&)"
#include <Wire.h>
#include <DS3231.h>
DS3231  rtc(SDA, SCL);

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

  // Initialize the rtc object
  rtc.begin();
  rtc.setDOW(WEDNESDAY);     // Set Day-of-Week to SUNDAY
  rtc.setTime(12, 0, 0);     // Set the time to 12:00:00 (24hr format)
  rtc.setDate(1, 1, 2014);   // Set the date to January 1st, 2014
}

void loop()
{
  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  // Wait one second before repeating :)
  delay (1000);
}

The error occurs in the third line (rtc (SDA,SCL)) - I have checked the pins and switched the battery on the chip. I also tried using A4 and A5 instead of SDA and SCL pins...
Any type of help would be awesome.
Best regards,
Marin

Alright I found the problem.
https://www.youtube.com/watch?v=BM3A7w3bhqM&ab_channel=MERTKILIC
In this video at 5:00 you can see the following:
First you have to download the library, unzip it and copy the files inside.
You will have to paste it to your Arduino/Libraries/DS3231 folder.

On the left is the current DS3231 Library which I added through the arduino library manager. Its not the same as the one the right, it should be, but its not, copy the files from the unzipped DS32321 library into the Arduino/library/DS3231.
Works fine now !


ESP8266(01) doesn't work when servo connected to GPIO-2 the wiki here says http://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

0 Low
1 High
x floating
MODE                   GPIO15   GPIO0   GPIO2
SDIO (BootSDCard)       1       x        x
UART (UploadCode)       0       0        x or 1
FLASH (NormalRunning)   0       1        x or 1

Can connecting my GPIO 2 to a servo Signal Wire cause it to go LOW? because some how my ESP8266 doen't boot when I have a servo hooked up to it.
I tried to change it to RX (which is GPIO3 on ESP8266) and everything seems to work fine. But I wanna know the reason why GPIO2 didn't work.

Thank you.

p/s:http://www.goodluckbuy.com/ld-1501mg-metal-gear-digital-servo-17kg-for-rc-robot.html this is the servo, if it matters. Also GPIO-2 works when I use another servo of different type instead (I don't know its name though)

It's what Juraj said.

  add external pull-up to io 2 -Juraj

sovled it


How to reset Arduino from software As you know, the Arduino IDE resets the Arduino when the Serial Monitor is opened. I want also my program to do it. But I don't know how.

I examined the source code of the Arduino IDE (Serial.java & SerialMonitor.java), but I can't find where it sends the reset command. Where is it?

I use C# to communicate with serial.

OK, I have solved this by sending DSR pulse as seen on code below:

mySerial.DtrEnable = true;
mySerial.Open();
Thread.Sleep(1000);
mySerial.DtrEnable = false;


How can I use a 'Global' class object? I created a class inside the sketch file(not in another file) and init it as object before setup() and loop() as a global object, after I change some parameters inside the object in setup() , I found in loop() the parameters in the global object remain unchanged.
Here is the pseudocode code to describe my question:

//all of the code below are in the same ino file.
class Animal{
public:
  bool alive = false;
  Animal (bool liveStatus){
    alive = liveStatus;
  }
}

Animal dog(false);
Animal cat(false);
Animal lion(false);
Animal animalArray(dog,cat,lion);

void setup(){

  for (int i=0;i<3;i++){
    Animal current_animal = animalArray[i];
    current_animal.alive = true;
  }
  //here when I print each animal's alive flag is 'true'
}

void loop(){
  for (int i=0;i<3;i++){
         // here the alive flag of each animal is still false  , they should be all true!!
  }

}

It looks like after I quit setup() somehow every change of the global object inside the setup are all gone .

Thanks for helping me ..

Your problem here is that Animal current_animal = animalArray[i]; is making a whole new Animal object that starts as a copy of animalArray[i];, but after that the two are no longer associated. Then when you call current_animal.alive = true;, you are not actually changing the animal in animalArray[i] anymore.

The simplest way to fix this is to make current_animal a reference to the object you pick out of the array, although a pointer would work the same way. With this code:

Animal& current_animal = animalArray[i];
current_animal.alive = true;

current_animal becomes a reference to animalArray[i], instead of a copy. Then operating on current_animal changes the same data that is stored in animalArray[i] like you intend.


Project Showcase '14 The logo is a derivative of the Arduino Community Logo licensed under Creative Commons license CC-SA-BY-NC 3.0

Update: Winners Announced

The winners of the contest have been announced. Please see the Meta post for details.

To celebrate 10 years of Arduino, we are proud to announce the first event ever on Arduino Stack Exchange.

  Get your boards and soldering equipment out, dig out the ICs and
  resistors. The first Arduino Stack Exchange contest is just round the
  corner. We will be looking for interesting projects that are built
  using Arduinos. The contest is aimed towards sharing, discussing and
  providing feedback on projects that you and other members are working
  on. See announcement post

Details:

The prize is an official Stack Exchange t-shirt
Limit two entries per person. If more than two are provided, only the first two will be considered.
Clones are allowed.
Projects for consideration will be accepted through March 29th, 2014 at 4:00 UTC. The question will still remain open in case someone wants to show off their project they made on Arduino Day 2014.

Visit the Meta post for discussion about this event and further information.

Answer Format

You may post up to two projects (as two separate answers) as entries for the contest. All extra entries will be deleted. Consider following the following template for entries:

  Project Title

  Very Brief Description

  Description

  What is your project? What does it do? What problem does it solve?

  Design

  Things to include in this section:

  Schematics and other design documentation. Fritzing is a good tool for drawing breadboard schematics like the one shown in the
  project logo above.
  Components used to build the project
  Pictures or video

  Conclusion

  Final thoughts. What did you learn from doing this project? What would
  you do differently if you had to start over?

You can copy/paste the following text if you want to use this template.

# Project Title
**Very Brief Description**

# Description
What is your project? What does it do? What problem does it solve?

# Design
Things to include in this section:

- Schematics and other design documentation. [Fritzing][8] is a good tool for drawing breadboard schematics like the one shown in the project logo above.
- Components used to build the project
- Pictures or video

# Conclusion
Final thoughts. What did you learn from doing this project? What would you do differently if you had to start over?

Prizes

There are two prizes! The winner will be the submission getting the maximum number of upvotes (downvotes do not count) and will get a Stack Exchange T-shirt*! There will be something for the runner-up as well. The runner-up will be decided at the discretion of the event organizers.

*Certain restrictions may apply. International shipping may take a few weeks.

Where do I submit my projects?

Post your projects as answers to this post.

Stateful questbox

A GPS powered box that makes you visit a few spots before opening

Description

It is similar to questbox, but it stores a small amount state of information in EEPROM, so you have to visit two or three different places before it opens.

Design

Needed hardware:

Arduino Uno
Reverse Geocache Version 2 (or a protoshield)
GlobalSat EM-406A GPS module
2×8 blue LCD with connector header and cable
Hitec HS-55 servo motor
4-40 push rod and clevis for latch (some versions provide a Z-bend rod instead)
2 AA battery holder
Metallic push button with embedded blue LED and 4-pin cable
Pololu low voltage switch
Pololu 5 V boost regulator
JST connector for EM-406A GPS module
Straight and right-angle header pins for the display, servo, and pushbutton connectors
Two resistors for current limiting and display contrast adjustment
Two small capacitors for power smoothing
larger capacitor for display contrast circuit

Total hardware cost: 137$ + shipping

Aditional materials:

A nice box
Epoxy glue, wood to cover pieces, tools

You can find assembling instructions in sundial page (you can buy most materials from them)

I will upload stateful code and post a link here, unfortunately I wont get all need hardware on time, so this is just an idea :)

Code written so far:

Persistent state machine library

Inspiration:

Conclusion

Learned how to integrate many components and libraries all toghether, I'll have to travel a bit to test it :)

Budget can be cut quite a bit changing the concept a bit:

Change GPS with a numerical keypad: the 'player' has to guess/obtain a code instead of traveling to a location
Polulu switch and regulator can be exchanged for a latching relay with capacitance coupling


How to turn I2C Sensors on and off with an Arduino Mega 2560? I want to turn on and off I2C Sensors with the Arduino Mega 2560.

I use one max. 0.4A NPN Transistor, which controls the Vcc line to the sensor.

When I plug my Arduino into my laptop and the sketch begins working everything is fine. The sensor is turned on and is working.

But when I set the Transistor Base to Low and cut the Vcc the sensor acts weird.
The LED on the sensor breakout board shines very weak. So the sensor/breakout board is getting electricity from somewhere else; probably from the I2C connections.

Same results with this small experiment:

Breakout board directly connected to the Arduino (without Transistor)
Vcc-3.3V pin wire disconnected from the Arduino female pin

How can i properly turn on and off an I2C sensor with an Arduino?

Do I have to use additional transistors for every I2C line? Are better circuit solutions available or maybe a software solution?

How should I design my circuit and my software if I have multiple I2C sensors connected to my Arduino and I want to use them independently from each other?

Used hardware: Arduino Mega, Sensor Breakout Board

Software excerpt for power control:

void setup() {

    pinMode(7, OUTPUT);
    digitalWrite(7, HIGH);

    ...

    delay(10000);
    digitalWrite(7, LOW);

    ...
}

The SDA and SCL pins have pull up resistors on them. So their voltage is 5V. By disconnecting Vcc on the sensor you are running the sensor out of spec. since the voltage on the SDA and SCL pins exceed Vcc.

Most chips have clamping diodes. So the chip is clamping the 5V on the I2C pins to Vcc. So you are powering the chip through the pull-up resistors on the I2C pins.

This would explain why the power led is lit, but not as bright.


How do I create a state machine for my purpose? I am new to Arduino.

I have a motor which drives a sliding door back and forth. The motor is connected to an H bridge which has two control pins (direction, speed). I have a switch which is intended to activate the motor for a set amount of seconds to open the door fully. When the switch is deactivated, the motor reverses for the same duration as opening.

I have written some basic code using the 'if' argument, but my issue is that the code under the 'if' argument loops when my switch is activated/deactivated whereas I want it to run once per switch activation. Looking online I saw that a state machine may be my solution, but my lack of expertise with coding means I cannot create a state machine. This is my code:

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH) {
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //I only need the motor to activate for four seconds, but 'if' loops it infinitely
  } else {
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, HIGH);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW); //Same issue  here
  }

;
  delay(1);
}

Creating a few boolian variables could help with this.

bool opening = 0
bool closing = 0

const int Switch = 2;
const int hbridge1 = 13;
const int hbridge2 = 12;
const int threshold = 400;

int buttonState = 0;

void setup() {

  pinMode(hbridge1, OUTPUT);
  pinMode(hbridge2, OUTPUT);
  pinMode(Switch, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {
  int buttonState = digitalRead(Switch);
  Serial.println(buttonState);

  if (buttonState == HIGH && opening == 0) { //variable "opening" is tested
    opening == 1  //variable "opening" is set to on
    closing == 0  //variable "closing" is set to off
    digitalWrite(hbridge1, HIGH);
    digitalWrite(hbridge2, LOW);
    delay(4000);
    digitalWrite(hbridge1, LOW);
    digitalWrite(hbridge2, LOW);
  }
    else if (buttonState == Low && closing == 0){ //variable "closing" is tested
      opening == 0    //variable "opening" is set to off
      closing == 1    //variable "closing" is set to on
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, HIGH);
      delay(4000);
      digitalWrite(hbridge1, LOW);
      digitalWrite(hbridge2, LOW); //Same issue  here
  }
  delay(1000) // delay is in milliseconds. So 1000 = 1 second
}

These new variables are set when the code is ran the first time. Therefore, no looping.


Sanity check with potential project. IoT with a dishwasher So sanity check for a potential project.

We have an old dishwasher at work, a GE QuietPower 3, and being a technology company, we want to connect it to our chat room to notify that the cycle is done, so someone can unload it.

The first iteration of the project we were just going to cover the "finished" indicator light with a photoresistor, so when it lights up, the microcontroller will know it is done.

However, that is not very nice looking, the second approach, after quickly looking at the technical maintenance manual. Is to literally solder the ground and + of the "finished" indicator light to a digital or analog pin, and the ground pin on the micro controller, so the results are more precise.

I suspect the LED is probably less than 12V, (will confirm with a multimeter). I will step it down to 5V.

Then it is just a matter of checking if the pin is high or not on the microcontroller, is this simple enough to solve the problem, or am I overlooking something obvious?

If connecting to the wiring, using an opto-coupler will ensure that your Arduino's days will be long on the face of the land. If it is an LED indicator you may be able to connect the opto-coupler LED  input directly across the existing LED, but use of an appropriate series resistor would be wise. Optocoupler LEDs may have about 2 V forward operating voltage which is in the same range as a red LED. Some use lower forwards voltage LEDS (probably IR).

If your opto coupler has low input current requirements then connecting it via a series resistor across the existing LED will allow the indicator to still operate.

R series = (Vsource - V_opto_LED) / I_opto.
eg 12V source, 2V opto_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.

For direct connection across an existing red LED a 100 Ohm series resistor should avert disaster.
V drop in resistor at 1 mA:
V = IR = 0.001 x 100 = 0.1 V
= liable to be OK.

Ask if more information wanted.


Controlling LED from web server I have a LED attached to my Arduino wifi shield that I want to control from my PHP web server.  In terms of communication, should I

Make my Arduino a web server and then communicate with PHP web server via HTTP
Make my Arduino a web client and receive commands from my PHP web service.  I would parse the JSON response

Also my other question is should I communicate with JSON between my PHP web server or is there a better way to send commands to my LED light?

There's no need for either PHP or JSON. Simply detect when one of two URLs (say, /led/on and /led/off) has been accessed on the Arduino's web server, change the LED state, and return a 204 response.


modbus slave ID setting I have small problem in setting device ID for Mosbus slave arduino. Here is simple example

In Modus library; device ID being configure hardcode while program. This code works for Me.

Modbus slave(1,0,0);

Now I wanted to recognise 0-255 device ID , I am using 8:1 digital Multiplexer & DIP switch to select the port. I am reading status of digital pin & depend on status of 8 DIP pin i come to know whats device ID. Below function return device ID. I have checked Serial it returns value properly. If i assign the value to Device ID it wont work . Please let me know how can i solve this.

unsigned int ID_Check() {
      unsigned   int ID_value;
      for(int row=0;row<8;row++)
      {
        digitalWrite(SO_enable,array[row][0]);
        digitalWrite(S1_enable,array[row][1]);
        digitalWrite(S2_enable,array[row][2]);
        Status_Out[row]=digitalRead(Output_Read);

      }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

Below is complete code.I tried to call function loop But it wont work

#include <ModbusRtu.h>
int SO_enable=5;
int S1_enable=4;
int S2_enable=3;
int Status_Out[8];
int Output_Read=2;
Modbus slave(ID_Check(),0,0); // this is slave @1 and RS-232 or USB-FTDI
int array[8][3]={
  {
    0,0,0    }
  ,
  {
    0,0,1    }
  ,
  {
    0,1,0    }
  ,
  {
    0,1,1    }
  ,
  {
    1,0,0    }
  ,
  {
    1,0,1    }
  ,
  {
    1,1,0    }
  ,
  {
    1,1,1    }

};

unsigned int ID_Check() {
  unsigned   int ID_value;
  for(int row=0;row<8;row++)
  {
    digitalWrite(SO_enable,array[row][0]);
    digitalWrite(S1_enable,array[row][1]);
    digitalWrite(S2_enable,array[row][2]);
    Status_Out[row]=digitalRead(Output_Read);

  }

  ID_value = 1 * Status_Out[0] + 2 * Status_Out[1] + 4 * Status_Out[2] + 8 * Status_Out[3] + 16 * Status_Out[4] + 32 * Status_Out[5] + 64 * Status_Out[6] + 128 * Status_Out[7];
  return(ID_value);
}

uint16_t au16data[16] =
{
  3, 1415, 9265, 4, 2, 7182, 28182, 8, 0, 0, 0, 0, 0, 0, 1, -1
};

void setup() {
  slave.begin( 9600 ); // baud-rate at 19200
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Output_Read,INPUT);
}

void loop() {
  slave.poll( au16data, 16 );
}

The other way i tried

void Modbus_Setup()
{
  Device_ID=ID_Check();
     delay(100);
    Modbus slave(Device_ID, 0, 0);
     slave.begin(9600);
  //slave.setID(Device_ID);

}

It looks like the problem may be initialisation order. In C/C++, global variables/objects are usually initialised in the order they are declared, and before any global functions run.

In your case, this means ID_Check() gets called before array is populated, and before setup() runs.

It looks like you need to make sure everything else is setup before your attempting to initialise the Modbus object. I'm not familiar with the library, but perhaps there's a way to set the device ID after it's been constructed (i.e. not in the constructor)?

If not, you could declare slave as a global pointer, and then instantiate it using new in setup().

As a side note, I'm guessing your Modbus_Setup() function didn't work because the slave object in there is completely separate from the slave object that's declared globally and used in loop().


Count specific range of output as 1 single output The LDR sensor gives a range of values to show whether a LED is OFF/ON, let's say above LDR range 400, the led is ON. When a LED is ON, after reading the sensor values it shows above LDR range 800, because the LDR sensor measuring in ms, a single LED blink shows six LDR 800+ values. Is there any way to count all the six  LDR 800+ values to increase counter by 1?
Here's my output in serial monitor. 314 to 322 is led OFF state and 816 to 851 is led ON state.
LED : 314
LED : 314
LED : 314
LED : 321
LED : 322
LED : 322
LED : 816
LED : 817
LED : 818
LED : 817
LED : 817
LED : 815
LED : 351
LED : 329
LED : 323
LED : 327
LED : 326
LED : 339

There are two distinct problems here.
The first problem is to convert the analog reading into a binary value.
You measure a value between 314 and 856, and you want to know whether
the LED is ON or OFF. The simplest solution is to compare the reading to
a threshold that is roughly in the middle of the range you measure. You
could say, for example, that the LED of OFF if the reading is below 580,
and is ON otherwise:
bool led_is_on = analogRead(ldr_pin) >= 580;

If the readings are noisy while they cross the threshold (does not seem
to be the case in the short span of data you show), you may want to use
some noise cancelling techniques. You could, as suggested by Michel
Keijzers, require multiple consecutive “ON” reading before deciding the
LED is actually ON. Or you may research the technique of using
hysteresis, which would be my favorite solution, as it is extremely
simple. However, if your readings are always as clean as what you are
showing us (never fluctuating mid-range), you can stick with the simple
threshold solution shown above.
The second problem is called edge detection. You want to count the
blinks. For this, you need to count how many times the LED turns ON,
which is not the same as how many times the LED is ON. You know that
the LED turned ON if you just detected it is ON and, on the previous
iteration it was OFF. So you have to remember whether the LED was ON
last time you looked at it. This means you have to store this
information (whether the LED was ON) in a static (or, if you prefer,
global) variable. Which leads to the following program:
int blink_count;

void loop() {
    static bool led_was_on = false;
    bool led_is_on = analogRead(ldr_pin) >= 580;
    if (!led_was_on && led_is_on) {
        blink_count++;
    }
    led_was_on = led_is_on;
}

Note the condition: !led_was_on && led_is_on means “The LED was not
ON and now it is ON”.


Stepper motor is not working according to code #include <Stepper.h>
#define STEPS_PER_MOTOR_REVOLUTION 32
#define STEPS_PER_OUTPUT_REVOLUTION 32 * 480  //2048
Stepper small_stepper(STEPS_PER_MOTOR_REVOLUTION, 8, 10, 9, 11);
int Steps2Take;
int dirpin=8;
int steppin=9;
int buttonApin=2;
int buttonBpin=3;

void setup() {
  pinMode(dirpin,OUTPUT);
  pinMode(steppin,OUTPUT);
  pinMode(buttonApin,INPUT);
  pinMode(buttonBpin,INPUT);
}

void loop() {
  int valA=digitalRead(buttonApin);
  int valB=digitalRead(buttonBpin);
  if(valA==HIGH) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(40000);
    delay(1000);
  }
  if(valB==HIGH) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(-40000);
    delay(1000);
  }
  if((valA==LOW)&&(valB==LOW)) {
    digitalWrite(steppin,HIGH);
    digitalWrite(dirpin,LOW);
    small_stepper.step(0);
  }
}

Here I have written this code to rotate stepper motor. When the input on digital pin 2 becomes high, then the motor should rotate clockwise. When the digital pin 3 becomes high, it should rotate in a different direction. When the input on both pins is low, the motor should not move.

But with this code the motor is moving continuously even if you apply high input to digital pins.

Please suggest how to fix this problem. For input signal I am taking signal from relays: if relay is in on condition, it should give a high signal and vice versa.

Does the relay actually connect the pin to ground when it is off?  Or does it leave the input floating?  If it leaves it floating then you should use a pull-down resistor to make sure the pin actually sees ground and not stray interference.

If you can rewire the relays you can use an active low configuration and save the resistor since the Arduino has built-in pullup resistors.


Arduino with NRF24L01. Getting correct data from unkown transmitter I want to use my Arduino with this: VAC8010F measure unit. It communicates with NRF24L01. The problem is I simply don't know which band or information it is receiving. Can somebody help me with this?

Thanks for any suggestions!

Don't have full details yet. But the VAC8010F uses modbus RS485 protocol.
My research shows that the NRF24 just transmitts and receives the MODBUS protocol to and from master/slave. I have found modbus libs and samples of code on the net. There is a command driven program to communicate with MODBUS free for linux, which is the o/s I use. I don't know about win. Anyway, once I receive the MAX485TTL interface for my ARDUINO MEGA I will write code for data  logging to p.c. then modify to use the NRF24, as I should be able to extract the ADDRESS, and CHANNELS etc, and packet construct.
Hope this is of some help.
Patrick


How to control Keyboard inputs using arduino(serial monitor) and python keyboard libraries? I am able to control my monitor and most other applications by giving serial input to python through arduino.
Arduino code:

void setup()
 {

  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(7, INPUT);
  Serial.begin(9600);

}

void loop()
{
  if(digitalRead(2) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("up");
  }
  if(digitalRead(3) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("down");
  }
  if(digitalRead(4) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("left");
  }
  if(digitalRead(5) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("right");
  }
  if(digitalRead(6)== HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("space");//orange
  }
  if(digitalRead(7)==HIGH)
  {
     delay(5);
  }
  else
  {
    Serial.println("nitro");//brown
  }
 }

Python code:

import serial
from pymouse import PyMouse
from pykeyboard import PyKeyboard

k = PyKeyboard()

ser = serial.Serial('COM7', 9600)

#sp.write("AT\r\n".encode('ascii'))

while True:
    p=ser.readline()
    print p
    if ('up' in p):
        k = PyKeyboard()

        k.tap_key(k.up_key)

    if ('down' in p):
        k = PyKeyboard()

        k.tap_key(k.down_key)

    if ('right' in p):
        k = PyKeyboard()

        k.tap_key(k.right_key)

    if ('left' in p):
        k = PyKeyboard()

        k.tap_key(k.left_key)

    if ('space' in p):
        k = PyKeyboard()

        k.tap_key(k.space_key)

    if ('nitro' in p):
        k = PyKeyboard()

        k.tap_key(k.enter_key)

My problem is that..I am not able to play games such as NFS and other similar games using these controls..
What should i do??

Your examples of sending input to the Arduino IDE monitor and to Python involve the Arduino sending data via "Serial over USB" convention. However this is not seen by the operating system (Windows, MacOS) as legitimate keyboard/mouse/joystick input.

There are separate USB conventions (device types) for keyboard/mouse/joystick. Only Arduinos where the USB interface is programmable are able to present those conventions, and some more easily than others, and require understanding some USB client libraries.  The link provided by Chris Stratton has some useful background.

A particularly easy way to get into this is with the PJRC Teensy, https://www.pjrc.com/teensy/, which comes with libraries and examples that let you do this out-of-the-box. See the "Teensyduino" section of their website for USB Keyboard, Mouse, Joystick and so on. These pages are useful background even if not using Teensy. It has attracted a small following of users interested in this area. Plus the various Teensies are conveniently small boards that fits nicely in some user-interface device you might want to build.


Programming Attiny45 using Arduino Uno with weird behavior I bought an Arduino Uno a few days ago.

I programmed an ATtiny45 using an Arduino Uno following "How-To: Shrinkify Your Arduino Projects" video on YouTube.

I uploaded the blink example successfully. I altered the sketch in a way so there is also a blinking on pin 4 (which is ATtiny45 pin 3).

Now, if I connect +5V from the Arduino to ATtiny45 pin 8, ground to pin 4 and the LEDs from pin 2 and 3 to ground everything works as expected.

But if I use 4 AA batteries instead of the power from the Arduino I only get a blinking on ATtiny pin2.

What could be the reason for this behavior? Is it because I use 4 AA -> 6 V instead of 5 V? I tested it also with 3 AA batteries and got the same result.

So why does it work if I use power and ground from the Arduino but not from the batteries?

If you take a look at Attiny45 datasheet, you will find at the very first page:

Operating Voltage

1.8 - 5.5V for ATtiny25V/45V/85V

2.7 - 5.5V for ATtiny25/45/85

Your circuit will have unpredictable behavior out of this range. If you want to use four AA cels, you can organize them to have a 3V output or use a step-down voltage regulator.


how to increase the range of KY-005? I am using a KY-005 with an Arduino Uno. I have the knowledge that Arduino can provide a forward current of 40 mA. How can I make it to 55 mA or above upto 60 mA to unlock its full potential, so as to get efficient IR communication without data being distorted at the KY-022 IR receiver?

First, I think 40 mA to output from a GPIO is not a wise idea, because those are Arduino Pin Current Limitations.

What you can do is:

The VCC pin can handle 200 mA. So you can use this pin to power your KY-005 and use a transistor to switch it via a GPIO (much less than 40 mA is needed for that).
Or (high likely not needed): use an external power source and use a transistor in the same way.

For knowing all details about using a transistor this way, google for "transistor as switch".


Powering Arduino Uno R3 with battery packs I am using Arduino Uno R3 with MPU 6050 for a personal project. MPU 6050 is being powered by the 3.3V supply pin in the Arduino board.

In order to make the sensor mobile, I ordered this battery, which has one power output of 5V 1Amp that I plan on plugging into the Uno's USB Power/Data Outlet.

I know that when plugged into the computer via the same USB port, around 5V 500 mA is supplied. I was wondering if someone could tell me, whether the 1A battery that I ordered would burn my board or not.

Also, is there a built in fuse inside this board?

Power sources like batteries and wall warts are voltage sources: they will deliver a fixed voltage, more or less. The current that they supply will be determined by the load you attach to them.

The "Amps" listed on a power supply is not how much current it will put out, it is the maximum current that the manufacturer has decided it can put out safely, without acting funny or overheating. So when you read that the USB port on a computer supplies 5V and 500mA, that means that it will supply 5V and up to 500mA. If you draw more than a 500mA current from your USB port, you would exceed the max current rating of the USB port. USB ports usually have an emergency shut-off mechanism built in, so they would just turn off if you drew more than 500mA out of them. I wouldn't try it though :). Your battery seems to have pretty similar safety features: "Super protection: overshoot, over-discharge, short circuit, over voltage, leakage, and many other protective functions".

If you had a 5V 20 Amp power supply, it will act the same as the USB port power supply, except it will be able to handle putting out much more current. As long as you don't exceed a voltage source's max current rating, the amount of current that a voltage source puts out depends on how much current the load draws, not on the voltage source. For example, a resistor will draw a current in Amps equal to the voltage supplied to it divided by the resistance (I=V/R), via Ohm's Law. For microcontrollers, you can often find their current draw on their datasheet: your MPU 6050 with the Gyro + Accel running has an operating current of 3.8mA when you give it ~3.3V. An Arduino Uno draws about 80mA by itself, though I don't think this includes the 3.3V power regulator on the 3V3 pin. So you're looking at somewhere a little over 84mA (=0.084A) in total. Your battery can supply 2.5A or 1A depending on which of its ports you use, so you are nowhere near exceeding the battery's max current rating, which is a good thing.

There are no fuses built in to the Arduino Uno R3. If you exceed its maximum current limitations, you will mess it up. There's a ruggedino available with more safety features if you're worried about frying your arduino. But as long as you're careful you should be fine with a standard R3.


Programming other Atmel chips(excluding Atmega 328 and 168) How can we program any other chips of Atmel using Arduino Nano as a Arduino ISP ? Excluding the Atmega 328 and 168.

Since you say:

  Excluding the Atmega 328 and 168.

I'm going to assume that you already understand the general process for using your Nano as an ISP.

The Arduino IDE includes the Arduino AVR Boards hardware package which provides hardware definitions for specific configurations of:

ATmega328P
ATmega168
ATmega2560
ATmega1280
ATmega32U4
ATmega8

If your hardware matches the configuration of one of the Arduino AVR Boards then you only need to select that board from the Tools > Board menu.

It is also possible to program many other Atmel microcontrollers or alternative configurations of the microcontrollers included with the Arduino AVR Boards hardware package with your Nano but you will first need to install the 3rd party hardware package that contains the definitions for the part you want to program. You can find a fairly comprehensive list of these hardware packages here:

https://github.com/arduino/Arduino/wiki/Unofficial-list-of-3rd-party-boards-support-urls

Once you have found the hardware package that contains the necessary definitions you will need to install it. For this you have two options:

Boards Manager

The easiest installation option Boards Manager. Most Arduino hardware packages allow this type of installation (and certainly all of them on the above list):

Copy the Boards Manager package index URL.
File > Preferences > Additional Boards Manager URLs > paste URL > OK
Tools > Board > Boards Manager
Wait for downloads to complete.
Scroll down until you see the entry for the hardware package you want to install. Click on it.
Click "Install".
Wait for installation to finish.
Click "Close"

Manual Installation

Another option is to manually install the hardware package. For a simple package this would involve:

Download the hardware package
Copy the contents of the downloaded file to {sketchbook folder}/hardware. You can find the location of your sketchbook folder at File > Preferences > Sketchbook location.
Restart the Arduino IDE if it's running

After installation you will only need to select the correct board from the Tools > Boards menu. In some cases selecting a board may also add custom menu items to the Tools menu that can be used to adjust the configuration of the board (part, clock, BOD, etc.).

  using Arduino Nano as a Arduino ISP

Note that the correct term is Arduino as ISP. There is a programmer named ArduinoISP that is completely different from the Arduino as ISP. The confusion is increased by the sketch used on the Arduino as ISP being named ArduinoISP.


Parsing and comparing strings on Arduino: different behaviour from gcc? I am trying to parse a simple string, print the result of the parsing via serial.println, and trigger a function on the basis of the received command. I wrote the code below, which perfectly works in c (see the c file attached). However, the behaviour of the same code on the arduino IDE is completely different and I really can't figure out why.

#include <string.h>

void rcv_msg(char *rcv_msg) {

  char *all_tokens[2];
  int i = 0;

  all_tokens[i] = strtok(rcv_msg, "{,}");
  while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{,}");
  }

  char *command = all_tokens[0];
  char *value = all_tokens[1];

  /*
  //These printls do not work, they are ignored, why?
  Serial.println("all_tokens[0]: ");
  Serial.println(all_tokens[0]);
  Serial.println("all_tokens[1]: ");
  Serial.println(all_tokens[1]);
  */

  if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {

    Serial.println("message 1: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }

  if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {

    Serial.println("message 2: ");
    Serial.println(command);
    Serial.println(value);
    Serial.println(" ");

  }
}

void setup() {

    Serial.begin(115200);
}

void loop() {

    char msg1[] = "{message_1,1}";
    char msg2[] = "{message_2,0}";

    Serial.println("Send msg1: ");
    rcv_msg(msg1);
    delay(5000);

    Serial.println("Send msg2: ");
    rcv_msg(msg2);
    delay(5000);
}

This code gives the following output on the serial monitor, which is wrong:

Send msg2:
message 2:
message_2
{message_2,0}

Send msg1:
message 2:
message_1
{message_2,0}

Send msg2:
message 2:
message_2
{message_2,0}

Send msg1:
message 2:
message_1
{message_2,0}

Firstly, I don't understand why at the beginning, message 2 is printed before message 1, although message 1 was sent first. Second it is not clear to me the comparison done with strcmp is always returning the message 2.

More importantly, why running the same code in c has instead the correct output? I wonder if there is any error in my arduino code. BTW, I am testing the code on Teensy 3.2 but I plan to use it also on Arduino Uno.

The c code (which is perfectly working is this:

#include <string.h>
#include <stdio.h>

void rcv_msg(char *rcv_msg) {

    char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value
    int i = 0;

    all_tokens[i] = strtok(rcv_msg, "{, }");
    while (all_tokens[i] != NULL) {
        all_tokens[++i] = strtok(NULL, "{, }");
    }

    printf("all_tokens[0] : %s \n", all_tokens[0]);
    printf("all_tokens[1] : %s \n", all_tokens[1]);

    char *command = all_tokens[0];
    char *value = all_tokens[1];

    printf("command : %s \n", command);
    printf("value : %s \n", value);

    if (strcmp(command,"message_1") == 0 && strcmp(value,"1") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }

    if (strcmp(command,"message_2") == 0 && strcmp(value,"0") == 0) {
        printf("activating command : %s %s \n\n\n", command, value);
    }
}

int main() {

    char msg1[] = "{message_1, 1}";
    char msg2[] = "{message_2, 0}";

    rcv_msg(msg1);
    rcv_msg(msg2);

}

Both versions of your code have undefined behavior. On the given input your code will call strtok three times and store its result into the array three times: for the first token, for the second token and, finally, for the null pointer. You store all three (including that null pointer!) into the all_tokens array, which has size 2.

You are obviously aware of the potential array overrun danger: you even wrote this comment in your code

char *all_tokens[2]; //NOTE: the message is composed by 2 tokens: command and value

and yet in the following cycle

int i = 0;

all_tokens[i] = strtok(rcv_msg, "{, }");
while (all_tokens[i] != NULL) {
    all_tokens[++i] = strtok(NULL, "{, }");
}

you still insist on storing more than two values into all_tokens array.

Also, the second version of your code uses completely different message key values (why is it suddenly "motor1_pattern1" instead of "message_1"?), which makes it unclear how you compared the functionality of the second version with the functionality of the first.


Arduino timers. How they work Explain this line in simple words.

TCCR0B=TCCR0B&0b11111000|0x01;

As the variuos arduinos have different chips. They also have different timers and different pins which use them.

Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.

I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me.
Shortcuts like the following.

TCCR0B=TCCR0B&0b11111000|0x01;

What does that?

TCCR0B

TCCR = Prefix for timers. Correct?

0 = Timer1 or 0 call it however you want.

B = What is A,B,C and sometimes D for? What does this?why in that code is the programmer using B and not A,C or D

TCCR0B= Timer 0 B is equal to:

TCCR0B& if Timer 0 B return True .. exists "&" ?

0b11111000 What is this? i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.

|0x01; I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

First I'll tackle what

TCCR0B=TCCR0B&0b11111000|0x01;

means from a pure programming perspective:

Let's break it down into parts:

TCCR0B = TCCR0B & 0b11111000 | 0x01;

TCCR0B is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.

0b11111000 is a binary representation of a value.  It's the same as the hexadecimal number 0xF8.  F is 15.  15 in binary is 1111.  8 is 8 in both hexadecimal and decimal.  8 in binary is 1000.  Put the two together and you have 11111000.  Incidentally, in decimal that is 248.

0x01 is hexadecimal for 1 in decimal - it's also 1 in binary.

Between them are bitwise operators - & is a bitwise AND operation, and | is a bitwise OR operation.  AND calculates which bits in a pair of binary numbers are both on, and OR calculates which bits in a pair of binary numbers are on in either of the numbers.

So take the first one first.  Say the TCCR0B register contains the value 0x6F, which is 157 in decimal, or 01101111 in binary.  The first operation is to AND that with 11111000:

01101111
11111000 AND
--------
01101000

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the & operator.

Ok, so the next operation is to OR it with 0x01:

01101000
00000001 OR
--------
01101001

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.

So finally the value is then stored in TCCR0B.

In summary that specific operation clears the lower three bits then sets the lowest bit of TCCR0B.

Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip.  For instance, take the ATMega328P chip from the Arduino UNO board.  Page 109 of the datasheet describes that register in detail.  The bit-wise overview looks like this:

Those bits all correspond 1:1 to the binary bits from above in the same order.  So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0.  The second stage, ORing 0x01, then sets CS00 to 1.

The datasheet goes on to tell you what those mean:

  Bits 2:0 – CS02:0: Clock Select

  The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock.  If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)".  So your masking would change to:

TCCR0B = TCCR0B & 0b11111000 | 0x02;

Or more explicitly so you can see the bits easier:

TCCR0B = TCCR0B & 0b11111000 | 0b010;

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer.  They each serve a different purpose.  TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.

Not to be confused with OCCR0A and OCCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs synchronised from the same timebase.


Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State I Took a output from ESP8266 and Connected it with Arduino Nano Analog input A0
i use BLYNK app to on/off D0 pin in ESP8266 , and i connected ESP8266 D0 pin with Arduino Nano A0 analogPin.
when esp8266 D0 in high state , the analogRead value in arduino nano serial monitor it show the value 395.
why not 1023 on high state .

There are two problems here - one immediate and one which will be come apparent.
First off, you appear not to have connected the ground pins of the two boards together. This is important. Voltage is not an absolute value, it's a value relative to some other point in the circuit. This is why "voltage" is sometimes called "potential difference". Normally the point in the circuit that voltages are referenced to is termed "ground". Note: there is nothing special about ground, it's just an arbitrary point in the circuit - usually, but not always, the point where the voltage is lowest.  If the ground of the Arduino that it's using to compare incoming voltages against is not the same as the ground that the ESP8266 is using to create its output voltage in relation to, then the Arduino really can't know what the voltage is.
You can think of it as a person standing on the ground. Now I am about 6 feet tall. When I am stood up the top of my head is about 6 feet above the ground. But to someone who is stood on a nearby rise in the ground my head is only maybe 3 feet above the ground. Their ground is not the same as my ground.
The second problem, which will become apparent once you have connected the grounds, is that the Arduino measures voltages between 0 and 5V as values between 0 and 1023. However the ESP8266 doesn't operate at 5V, it operates at 3.3V. The highest voltage it can ever put out is 3.3V. The Arduino can never read that as 1023 because it's not 5V.  Instead it will read somewhere around 675. That is, 3.3V is two thirds of 5V, and 675 is two thirds of 1023.


How safely write to SD or Eeprom on Arduino power off I want to constantly store data to sd. But how I make sure data is not corrupted on moment of power off? I think I could add small capacitor on 5V and check when voltage drops, so I would stop data write. Or is there better solution for safe data write?

I think a "small" capacitor here is not going to do the job as you need to keep power stable until the write is completed.  You need to determine:

How much power am I using?
How quickly can I detect a power outage?
How much time do I need to keep power on the Arduino to complete the write operation(s) I want to complete.

Then you will be in a position to calculate how much capacity you need and whether a capacitor or battery is more appropriate.


How to identify pinout of ATmega 2560 derivative board? My 3d printer, Creality Ender 4, has an ATmega 2560 chip based card, and I need to identify the number associated with a particular Pin.
I read, on the official Arduino website, a simple tutorial in which through a small led connected to two pins of the card, you wrote a code (sketch) that made it turn on, but you had to know the Pin number.
I would like to do this on my board, I unplug all cables (power supply, motors, etc.) and connect it to the PC via USB and from Arduino IDE, I execute the code, connecting the LED on the ground and on the signal (see image).
To identify the Pin number I thought I would go to exclusion, because I know all the PIN numers of the chip, until the LED lights up.
So I ask, is that correct? is there a chance of damaging the card? or is there a better method?
Thanks in advance

Disconnect everything but the switch.
Run this:
for each pin,
  set the pin to INPUT_PULLUP mode;
  do,
    read and print the pin number and pin state;
  until operator touches a key;
  read and discard the serial input;
end;

You do:

Each time a new pin number prints on the terminal,
toggle the switch a few times to confirm whether you are seeing the result of your actions.
If not, touch the spacebar to try the next pin #
else, you found it.