Ways to turn a knob with a stepper motor and an ATMEGA32u4 Hey all I am wondering what would be the best items to purchase for me to be able to turn this know (continuous) below:

As I mentioned above, I would need the stepper motor to have a continuous rotation in order for it to work with either of these dry food dispensers above.

There is a decent tutorial HERE but really doesn't give much information about how they went about building it and the mentioned Yocto-LatchedRelay seems over priced for something that can be done with just a stepper motor and some logic behind it.

I plan on using a ATMEGA32u4 with this project. I will have a total of 6 of these to control.

So any suggestions on what would be best for this type of project would be great and I look forward in hearing them! :o)

I'm just needing to know what kind of servo torque I would need in order to turn that without issues of it getting stuck mid-ways.

update

i spoke to the original creator of that web site project that i linked to and this is what they had to say about the parts that were used:

  We used a  small geared Maxon motor (great but expensive hi-tech
  stuff).

  motor RE-max 13 Ø13 mm, Precious Metal Brushes CLL, 1.2 Watt, with
  cables  Part-No.: 203888

  gear Planetary Gearhead GP 13 A Ø13 mm, 0.02 - 0.35 Nm, Metal version
  Part-No.: 110316

  Torque was on the low side: it was enough for regular cornflakes but
  clearly insufficient for muesli  :-)

  The problem is not only about finding a motor with enough torque, it's
   also about finding a motor small enough to fit in the dispenser.

  Here are the files. The pulleys were 3D printed, but the bracket was
  laser cut in 3mm acrylic glass.

Are there any servos that have a hole in the middle so that i can slide it over the turning rod and screw down to tighten on it in order to spin it as if you were spinning it yourself with the handle?

Something like this:

Looks to be a screw driven by a motor through a set of greats. It doesnt matter if the motor is a regular (dc) motor or a stepper.


arrange vector in descending order im trying to arrange the vector in descending order but its not happening..

int fibonacci[15]={0, 1};
int a=0;

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

  for (int i=0; i<=14; i++) //loop to create the array
  {
    fibonacci[i+2]=(fibonacci[i])+(fibonacci[i+1]);
  }

  //Now arrange in descending order
  for (int i=0; i<16; i++)
  {
    for (int j=i+1; j<16; j++)
    {
      if (fibonacci[i]>fibonacci[j])
      {
        a=fibonacci[i]; //mux number
        fibonacci[i]=fibonacci[j];
        fibonacci[j]=a;
      }
    }
  }

  for (int k=0; k<16; k++)
  {
    Serial.println(fibonacci[k]);
  }
}

void loop() {
}

I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :

/*
  SORTING IN DESCENDING ORDER
*/

const int nbElem = 15; // 24 max
int fibonacci[ nbElem ] = { 0, 1 };

void createFibonacciArray( int inputArray[], int arraySize )
{
  fibonacci[ 0 ] = 0;
  fibonacci[ 1 ] = 1;
  for( int i=0; i<nbElem-2; i++ )
    fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
}

void displayArray( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize; i++ )
    Serial.println( inputArray[ i ] );
}

void displayArrayReverse( int inputArray[], int arraySize )
{
  for( int i=arraySize-1; i>=0; i-- )
    Serial.println( inputArray[ i ] );
}

void reverseArray( int inputArray[], int arraySize )
{
  for( int i=0; i<nbElem/2; i++ )
  {
    int fTemp = fibonacci[ i ];
    fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
    fibonacci[ nbElem-i-1 ] = fTemp;
  }
}

void inverseBubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] < inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

void bubbleSort( int inputArray[], int arraySize )
{
  for( int i=0; i<arraySize-1; i++ )
  {
    for( int j=0; j<arraySize-1-i; j++ )
    {
      if( inputArray[ j ] > inputArray[ j+1 ] )
      {
        int temp = inputArray[ j+1 ];
        inputArray[ j+1 ] = inputArray[ j ];
        inputArray[ j ] = temp;
      }
    }
  }
}

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

  // Create and display Fibonacci array
  createFibonacciArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI ARRAY\n" );
  Serial.print( "===============\n" );
  displayArray( fibonacci, nbElem );

  // Solution 1: Display array starting from the end
  Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
  Serial.print( "=====================================\n" );
  displayArrayReverse( fibonacci, nbElem );

  // Solution 2: Reverse array
  reverseArray( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
  Serial.print( "========================\n" );
  displayArray( fibonacci, nbElem );

  // Solution 3: Inverse bubble sort array
  createFibonacciArray( fibonacci, nbElem );
  inverseBubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
  Serial.print( "====================================================\n" );
  displayArray( fibonacci, nbElem );

  // Ascending order sort array
  bubbleSort( fibonacci, nbElem );
  Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
  Serial.print( "=================================\n" );
  displayArray( fibonacci, nbElem );
}

void loop()
{}


What are ideal delay times between commands for RF24 lib Am working on a WiFi based irrigation system that utilises the RF24 lib for comms.
Have got prototype of remote sensor up and running which has a standby current of 0.036mA and transmits data every hour using around a peak of 12mA.
While running the prototype I see various retry attempts which seem to vary with every transmission – despite the setup being under the same conditions all the time. I have coded a retry loop to limit this to 10 tries connecting to the master – don’t want the sensor to continuously be sending without getting a confirmation from the master

What I am trying to find is the ideal delay required between various RF24 commands to limit transmit times as much as possible to conserve power usage.
Any ideas??
(code snippets attached)

   pinMode(mostureSensorVCC, OUTPUT);
   digitalWrite (mostureSensorVCC, HIGH); //VCC to sensor
   pinMode(mostureSensor1, INPUT);      //moisture sensor on
   delay(10);
   int sensorValue1 = analogRead(mostureSensor1); // read the input on analog pin
   Serial.print("Current Value Sensor 1 is : "); // debugging
   Serial.println(sensorValue1); // print out the value you read:
   msg[0] = sensorValue1;
    digitalWrite(mostureSensor1, LOW);
    digitalWrite(mostureSensorVCC, LOW);
      while (message != sensorValue1)
        {

          Serial.print("sensorValue in while loop is "); // debugging
          Serial.println(sensorValue1);                   // debugging
          Serial.print("Message One is ");                // debugging
          Serial.println(message);                        // debugging
          radio.powerUp();
          delay(70);

          radio.stopListening();
          delay(50);
          radio.write(msg, 2);
          delay(40);
          radio.startListening();
          delay(50);

         Serial.println(d);               // debugging

          if (radio.available())
            {
             Serial.println("Radio available");     // debugging
              radio.read(msg, sizeof(msg));
              message = msg[0];
              Serial.print("Check Message received from master ");// debugging
              Serial.println(message);

            }
            if(d>=10)
            {
              Serial.println("Unable to send to master");
              break;
            }
       d++;
  }

delay(1000);
radio.powerDown();
message = 0;
msg[0] = 0;

Remove all delays except the one after startListening.

You could replace it with a "wait for radio.available to be true OR 50ms to have passed" piece of code. There is no need to wait for 50ms if the message was already received after e.g. 10ms.

Even better would be to use the ACK-package feature of the NRF. With this feature the master already prepares a package for the slave. Then when the slave sends it's message (every hour), the prepared package is included in the ACK (acknowledgement) packet.

As to optimizing it even further. It would be better to optimize the sleep code, then the send code. The sleep part will still use more power in an hour than the sending code, even if it takes 10 second to do so.

As to the lost packages. Try using a different channel. You also might want to get an NRF module with an real antenna, and maybe even an amplifier, for the master.

PS You can remove the serial.print in the deployed version.


Do ISRs have to be defined in top level Arduino program? I'm currently attempting to implement some interrupts on an Arduino project. Looking through some of the examples, it appears that all the ISRs are defined in the top level Arduino program. I'm organizing my project by C++ classes and namespaces, so I'm curious, is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++  namespace? This question has been spawned primarily for organizational purposes.

Otherwise, I could always just use a #include to import a file that defines the ISR such that they're imported to the top level.

Thanks!

Why don't you try it and see?

  is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++ namespace?

Yes. Example here:

const byte LED = 13;
const byte BUTTON = 2;

namespace foo
  {
  // Interrupt Service Routine (ISR)
  void switchPressed ()
    {
    if (digitalRead (BUTTON) == HIGH)
      digitalWrite (LED, HIGH);
    else
      digitalWrite (LED, LOW);
    }  // end of switchPressed
  }  // end of namespace foo

void setup ()
{
  pinMode (LED, OUTPUT);  // so we can update the LED
  digitalWrite (BUTTON, HIGH);  // internal pull-up resistor
  attachInterrupt (0, foo::switchPressed, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  // loop doing nothing
}

I put the ISR in the namespace "foo" and it compiled OK.


How to switch on 32A/240VAC with Arduino? I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.

I'm based in India and I am unable to find a relay switch rated higher than this.

I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

I don't want to try anything that results in a fire hazard.

That's a good idea.

Besides those toy relays there are real ones:
440 V AC * 63 A (Around there, you can find smaller ones too)

BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)

If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)


How high of a baud rate can I go (without errors)? The standard is 9600 baud. That's just the standard. Using a Arduino Uno SMD R2, what is the highest practical baud rate I can achieve?

Bonus points for the audacious: How would you go about creating an error checking mechanism and then increasing the baud rate ridiculous high to get high transfer rates?

There are several factors here:

How high of a baud-rate can the ATmega328P MCU achieve?
How high of a baud-rate can the USB-Serial interface achieve?
What is the oscillator frequency on the ATmega328P?
What is the oscillator frequency on the USB-serial interface (if it has one)?
How tolerant is the USB-serial interface of baud-rate mismatch?

All of these factors are relevant to determining the maximum achieveable baud rate. The ATmega328P uses a hardware divisor from it's clock-rate to generate the base-clock for the serial interface. If there is no integer ratio from the main clock to the bit-time of the desired baud rate, the MCU will not be able to exactly produce the desired rate. This can lead to potential issues, as some devices are much more sensitive to baud-rate mismatch then others.

FTDI-based interfaces are quite tolerant of baud-rate mismatch, up to several percent error. However, I have worked with specialized embedded GPS modules that were unable to handle even a 0.5% baud rate error.

General serial interfaces are tolerant of ~5% baud-rate error. However, since each end can be off, a more common spec is +-2.5%. This way, if one end is 2.5% fast, and the other is 2.5% slow, your overall error is still only 5%.

Anyways. The Uno uses a ATmega328P as the primary MCU, and a ATmega16U2 as the USB-serial interface. We're also fortunate here in that both these MCUs use similar harware USARTs, as well as 16 Mhz clocks.

Since both MCUs have the same harware and clock-rate, they'll both have the same baud-rate error in the same direction, so we can functionally ignore the baud error issue.

Anyways, the "proper" answer to this question would involve digging up the source for the ATmega16U2, and working out the possible baud-rates from there, but since I'm lazy, I figure simple, empirical testing will work.

A quick glance at the ATmega328P datasheet produces the following table:

So given the max stated baud-rate of 2 Mbps, I wrote a quick test program:

void setup(){};

void loop()
{

  delay(1000);
  Serial.begin(57600);
  Serial.println("\r\rBaud-rate = 57600");
  delay(1000);
  Serial.begin(76800);
  Serial.println("\r\rBaud-rate = 76800");
  delay(1000);
  Serial.begin(115200);
  Serial.println("\r\rBaud-rate = 115200");
  delay(1000);
  Serial.begin(230400);
  Serial.println("\r\rBaud-rate = 230400");
  delay(1000);
  Serial.begin(250000);
  Serial.println("\r\rBaud-rate = 250000");
  delay(1000);
  Serial.begin(500000);
  Serial.println("\r\rBaud-rate = 500000");
  delay(1000);
  Serial.begin(1000000);
  Serial.println("\r\rBaud-rate = 1000000");
  delay(1000);
  Serial.begin(2000000);
  Serial.println("\r\rBaud-rate = 2000000");
};

And then looking at the relevant serial port with a serial terminal:

So it appears the hardware can run at 2,000,000 baud without problems.

Note that this baud rate only gives the MCU 64 80 clock-cycles per byte, so it would be very challenging to keep the serial interface busy. While the individual bytes may be transferred very rapidly, there is likely to be lots of time when the interface is simply idle.

Edit: Actual Testing!

The 2 Mbps is real:

each bit-time is 500 ns, which matches exactly with what is expected.

Performance issues! Overall packet length:
500 Kbaud:

1 Mbaud:

2 Mbaud:

Note: The noticeable overshoot is due to poor scope probe grounding practices, and is probably not real. I'm using the ground-clip-lead that's part of my scope probe, and the lead-inductance is likely the cause of the majority of the overshoot.

As you can see, the overall transmission length is the same for 0.5, 1 and 2 Mbaud. This is because the code that is placing the bytes in the serial buffer is poorly optimized. As such, you will never achieve anything better then an effective 500 Kbaud, unless you write your own serial libraries. The Arduino libraries are very poorly optimized, so it probably wouldn't be too hard to get a proper 2 Mbaud, at least for burst transmissions, if you spent a bit of time on it.


Using 2 RGB lights over Bluetooth with a DigiSpark I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)
Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.)

The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module.

So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream?

Which means, analog connections.

Nope. It means PWM.

How would you control the brightness of a single LED?

By generating a PWM signal with:

sufficiently high frequency to not be able to notice the flickering;
duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive.
Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.

Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.

If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: I2C 6-channels PWM generator.


Is there an Arduino motor shield library? I have an old motor shield but can see the revision 3 is still being sold: https://store.arduino.cc/arduino-motor-shield-rev3

When I follow the link for "Getting Started section" the page lists a lot of shields but not the motor shield.  I must be missing something really obviously but I can't find a library for the motor board.

I'm trying to drive 2 DC motors.

From Chrisl's comment: https://github.com/gallingern/arduino-motor-shield-r3

You don't really need a library though as the code is simple enough:

void setup() {

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

}

void loop(){

  //forward @ full speed
  digitalWrite(12, HIGH); //Establishes forward direction of Channel A
  digitalWrite(9, LOW);   //Disengage the Brake for Channel A
  analogWrite(3, 255);   //Spins the motor on Channel A at full speed

  delay(3000);

  digitalWrite(9, HIGH); //Engage the Brake for Channel A
}

From here.


Can an Arduino Micro receive commands from another microcontroller when hardwired together? I plan to build functioning reaction wheels, controlled by an Arduino Micro. Ideally, I'd like to have the reaction wheels, and the micro, be a single unit which would receive external commands from another microcontroller.

I know you can link Arduino microcontrollers, and every time I've seen it done it has been with a RC module such as XBee. Is it possible to link units using something like the micro-usb on the Arduino Micro?

If this is possible, is it as simple as connecting the micro-usb ports on my microcontrollers, and then working out the programming?

You cannot do this with the micro USB ports.  You will need to use I/O pins.  Either serial or I2C would be good options.  It might be advisable to use I2C if you want to control multiple 'slave' microcontrollers as they can all sit on the same bus.  Using the serial port would require multiple transmit and receive pins on the master controller, likely requiring software serial ports (high overhead).  Also, if you don't use the serial port for comms, then you can use it for debugging.


Connecting HC-06 and LM35 Hello I am trying to send temperature data via bluetooth using the HC-06 module. Since TXD and RXD only allow 3.3V I have divided the circuit into two like the below image.
Is this method correct? or is there a better way to connect both two?

Any help is appreciated.

As mentioned by chrisl, you cannot use HC-06 as a master device. Its firmware restricts it to behave only as a slave. So even if you are able to process the analog data from LM 35, you won't be able to send it using HC-06. It would be better if you go for HC-05 module and try the command AT+ROLE: x (x = 1 for master/0 for slave) to get the job done.

Coming to the 3v3 voltage constraint, I would suggest you to go for any Zener diode (in reverse biased mode) with 3.3V Reverse breakdown voltage. You can check the circuit for this here and order it from this link. If this is not possible anyhow, then you can also go for LM1117 3V3, but I would personally suggest you to go for zener diode. Comment back if you need any help in future.


Difference between WiFiClient and HttpClient Apologies if this question appears to be too vague but I would like to know the key differences between these two clients.

While WiFiClient comes pre-loaded with Arduino IDE, HttpClient doesn't. Also, to send HTTP commands to a server (XML/JSON), which one to go for?

WiFiClient provides a raw connection to the internet through a WiFi access point (such as your home router).

HttpClient provides a connection to a web server via an existing Client connection, such as a WiFiClient connection.

So the simplest answer to your question

  to send HTTP commands to a server (XML/JSON), which one to go for?

is "Use both".

You use WiFiClient to connect to the internet, then you use HttpClient on your WiFiClient connection to communicate with a website.  As it states in the readme on HttpClient's github repository:

  Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with EthernetClient, WiFiClient and GSMClient.

To understand the concept more fully you will first need to understand the OSI 7-Layer Model which is essential reading for anyone doing anything with networking software.


How to parse 20180810T143000Z to time_t What is the shortest/most elegant way (i.e. use existing lib functions) to parse a string in the form of 20180810T143000Z to a time_t? Note that the literal always represents a UTC timestamp.

I started parsing the string and assigning values to a struct tm *tm in order to do a mktime(tm) at the end. That feels overly complicated, though.

Parsing the string really is the only way. However there are many ways of doing it.

My preferred method is to first check that the format is correct, by looking for the T and Z being in the right place:

if (timeString[8] == 'T' && timeString[15] == 'Z') {
    ... parse in here
}

And the parsing is just making numbers with multiplication:

int year = (timeString[0] - '0') * 1000 +
           (timeString[1] - '0') * 100 +
           (timeString[2] - '0') * 10 +
           (timeString[3] - '0');

You can clean things up with a macro if you like:

#define NUM(off, mult) ((timeString[(off)] - '0') * (mult))

Then:

int year =   NUM(0, 1000) + NUM(1, 100) + NUM(2, 10) + NUM(3, 1);
int month =  NUM(4, 10)   + NUM(5, 1);
int day =    NUM(6, 10)   + NUM(7, 1);
int hour =   NUM(9, 10)   + NUM(10, 1);
int minute = NUM(11, 10)  + NUM(12, 1);
int second = NUM(13, 10)  + NUM(14, 1);

And then, yes, put them in a struct tm (or directly assign them calculation results without using the intermediate variables) and call mktime().


How to save data in arduino when it's power goes off I am doing a project 'arduino based switch operation'. Here the user needs to set a time to turn on relay and set time to turn it off. The problem is that I want to supply power to arduino using adapter connected to the ac supply (where the relay will also be connected). When the on time is set and if power goes off for some time then this system doesn't work. I want to save the data in arduino so that it will retain the data if power comes back.. So that my relay is operated on time..
How to do it guys???

Look up EEPROM. it is a memory that saves content even though power is off.

You can write data in EEPROM and when power comes back read it back.

there are safe ways to write in EEPROM without corrupting it.


Is there a portable timer interrupt library? I have a need for timer interrupt (for the sake of this exercise - say I need to execute something every second)

I found code in many places on the internets that does this using ISR for 328/Uno.  (or specifically for other chips) But of course that does not work on other chipsets.

Is there a portable timer library that works across many/most/all arduino boards/chipsets?

For now it is a simple project - I have no other motors or tones, etc.

In my current project I have conditional compiles for different chipsets, to set up a callback/interrupt but would rather use a library that hides this all.

I think it would be hard, or impossible, to make such a library. Already there are problems with pin-change interrupt libraries, and Software Serial (which uses pin-change interrupts).

Plus, to have a generic "callback" might tempt people to do things which they shouldn't anyway in an ISR, like do serial printing.

Let's say you choose to use a spare timer (eg. Timer 1). You have the issue now that you won't be able to do (some) PWM output because that uses Timer 1.

The closest would be to lever off the existing millis() code and just have a test in loop to see if the time interval is up, and then call a function - however that wouldn't be an ISR.


How to code for cascading multiplexers? I hope I can get some help on how to get this to work.

I have multiple Sensors (32 of these) which values I want to read. I am using a master multiplexer HC4051 connected to 4 slave multiplexers, this is my wiring:
[here][1]

I tested it using one single multiplexer and it works as intended, but when adding the slave I cannot getting it to work, I am not sure how to code for it.

When using this code:

// 74XX4051 ADDRESS PINS :
#define  M_S0 2
#define  M_S1 3
#define  M_S2 4

#define  S_S0 7
#define  S_S1 6
#define  S_S2 5

// 74XX4051 ANALOG PIN :
#define  Z 0

void setup() {
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);

    // CONFIGURE SERIAL
    Serial.begin(57600);
}

void loop() {
    int value;

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for ( byte count = 0; count < 4 ; count++ ) {
         // SET THE ADDRESS
         digitalWrite(M_S0, bitRead(count, 0) );
         digitalWrite(M_S1, bitRead(count, 1) );
         digitalWrite(M_S2, bitRead(count, 2) );

         // LOOP THROUGH ALL THE ADDRESSES OF THE SLAVES
         for ( byte count_1 = 0; count_1 < 32 ; count_1++ ) {
             digitalWrite(S_S0, bitRead(count_1, 0) );
             digitalWrite(S_S1, bitRead(count_1, 1) );
             digitalWrite(S_S2, bitRead(count_1, 2) );

             // READ THE ANALOG VALUE
             value = (bitRead(count_1, 2), bitRead(count_1, 1), bitRead(count_1, 0));
         }

         // READ THE ANALOG FOR THE MASTER ADRESSE
         value = analogRead(Z);

         // SERIAL OUTPUT
         // print : ### value
         Serial.print(bitRead(count, 2));
         Serial.print(bitRead(count, 1));
         Serial.print(bitRead(count, 0));
         Serial.print(' ');
         Serial.println(value);

         delay(100);
     }
}

I am only getting random readings really (the reading LED for the moisture sensor does not switch on when the reading is done).

What I am doing wrong? Any help is appreciated.

UPDATE:

i updated my code as follows :

// Master moisture sensor pins
#define  M_S0 7
#define  M_S1 8
#define  M_S2 9
// Slave moisture sensor pins
#define  S_S0 4
#define  S_S1 5
#define  S_S2 6

// PIN from the transistor to power the sensors only when doing a reading
int sensorVCC = 13;

//  ANALOG PIN :
#define  Z 0

void setup() {
    Serial.begin(9600);
    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(sensorVCC, OUTPUT);

    digitalWrite(sensorVCC, LOW);
}

void loop() {

    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER
    for (int i = 0; i < 32; i++) {
    digitalWrite(sensorVCC, HIGH);
    delay(100); //make sure the sensor is powere

    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int humidityRaw = analogRead(Z); // 1023 to 0 ===> 0 to 100%
    int humidityReal = map(humidityRaw, 975, 523, 0, 100);
    digitalWrite(sensorVCC, LOW);

    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.print(humidityReal);
    Serial.println(" % ");
    delay(1000);
}
}

and this is my output :

    Input 0: 100 %
    Input 1: 0 %
    Input 2: 100 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 0 %
    Input 1: 100 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .
    Input 0: 100 %
    Input 1: 0 %
    Input 2: 0 %
    Input 3: 0 %
    .
    .
    .

ONLY channel 0 is hooked !! .... it seems that it reads with different delays. changing the delay gives me different sequence. what is wrong ?

It becomes much easier if you start thinking in binary.

If you have an 8 bit multiplexer connected to four 8 bit multiplexers that gives you 32 inputs. Four of the inputs on the "master" multiplexer are unused and can be ignored.

You have 32 inputs. That's inputs numbered 0 to 31. In binary that equates to, in full,

0 = 000000   8 = 001000  16 = 010000  24 = 011000
1 = 000001   9 = 001001  17 = 010001  25 = 011001
2 = 000010  10 = 001010  18 = 010010  26 = 011010
3 = 000011  11 = 001011  19 = 010011  27 = 011011
4 = 000100  12 = 001100  20 = 010100  28 = 011100
5 = 000101  13 = 001101  21 = 010101  29 = 011101
6 = 000110  14 = 001110  22 = 010110  30 = 011110
7 = 000111  15 = 001111  23 = 010111  31 = 011111

I have laid it out like that especially so that you see a pattern occurring. Four columns with 8 rows. Four slave multiplexers with 8 inputs. A perfect match. Each column has bits that are distinct to that column. Each row has bits that are unique to that row.  So you could split those bits up and know that the left-hand three bits indicate the column, and the right-hand three bits indicate the row. Between the two it's a unique location in the table.

The same applies to the multiplexers.  The left-hand three bits indicate which slave multiplexer to use, the right-hand three bits which input to use on the selected multiplexer.

So you can loop through each of the 32 inputs with a single loop and examine the individual bits of the input number and apply those bits directly to the select outputs to control the multiplexers - the left-hand bits to the master to select which slave to use, and the right-hand bits to the slaves to select which input to use.

So you have:

for (int i = 0; i < 32; i++) {
    digitalWrite(M_S2, i & 0b100000);
    digitalWrite(M_S1, i & 0b010000);
    digitalWrite(M_S0, i & 0b001000);
    digitalWrite(S_S2, i & 0b000100);
    digitalWrite(S_S1, i & 0b000010);
    digitalWrite(S_S0, i & 0b000001);

    delay(1);

    int reading = analogRead(Z);
    Serial.print("Input ");
    Serial.print(i);
    Serial.print(": ");
    Serial.println(reading);
}

The i & 0b000001 etc performs the same function as bitRead() but is more explicit using a mask that is far more visual as to what it achieves.

I also include a tiny delay after setting the multiplexers up so as to ensure they have settled into their new settings properly before reading. It shouldn't be needed, but it doesn't hurt.


Arduino Pro Micro bricked? I have a Pro Micro board at which tried to upload a sketch with sparkfun's Pro Micro 3.3v processor selected.

After the upload completed successfully the board did not run again and is not even detected from the arduino ide anymore.

When I uploaded sketches with the leonardo 5.5v board selected everything went well and I had no problem. Now I can not burn the bootloader because of the arduino ide not detecting the board.

What can i do?

Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.

Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.

I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board


Can't use Arduino nano as ISP because it can't read the Device signature I programmed the 8mhz internal oscillator Bootloader to a new Arduino Nano with another Arduino nano running the ISP Sketch, wich worked fine the first time(Arduino as ISP selected as programmer).
(I wanted to test it befor i want to burn this Bootloader on an Empty 328p-au uC.)
But now since I received the 328p-au uC's i tried the same thing, to burn the Bootloader to the epty uC's but somehow it can't read the device signature, neither from a fresh arduino Nano or another avr(At least that is what avrdude said). I wired everything exectly like it was written in the ISP Sketch.

Here is one of the error messages i received when I was trining to Burn the standard 16mhz Bootloader:

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

     Fehler beim Brennen des Bootloaders.
     avrdude: AVR device initialized and ready to accept instructions

     Reading | ################################################## | 100%          0.02s

     avrdude: Device signature = 0xff0000
     avrdude: Expected signature for ATmega328P is 1E 95 0F
     Double check chip, or use -F to override this check.

     avrdude done.  Thank you.

So what am I doing wrong?
(Using -F is what I tried but it didn't work, except the first time I programmed the 8Mhz Int. Oscillator Bootloader)

What stand out to me is that there was nothing happening on the MISO line. Here is a screenshot from my Logic Aalyzer software: ibb.co/hWXrpp7

And here is an Image of my setup(the right Arduino is the programmer and the left one has the empty uC soldered onto it): https://ibb.co/zXQFmwR
I am relative new to Arduino, so I hope some of you can help me with that.

It seems that you are using too high programming speed. SCK period al of 0.1 us renders 10 MHz, which is to fast if crystal is working at 8 MHz. Not sure where to change it in Arduino environment, but you should add this key to avrdude.exe run string:

avrdude.exe -B 8

This will set programming speed to 125 kHz. Also I suggest you to buy a cheap USBasp programmer from eBay or AliExpress. It is well documented and have plenty GUI programs, running on top of the avrdude. In newest Arduino IDE you can generate hex files in the sketch directory, and burn it with programmer.


How to connect accelerometer, GPS, microphone and a GSM module to a Arduino? I am a noob in the Arduino world and have only started reading about it. I have zero experience with Arduino some suggestions to increase my level will also be highly appreciated. But I have a lot of ideas, I want to work on.

I want to measure the velocity and noise levels with the GPS coordinates of a moving vehicle and send it to my phone using gsm or wifi.
Should I include a small LCD also? again suggestions will be highly appreciated.

It depends.

If you are a beginner, do it in steps:

Get an Arduino Uno
Get a feeling for MCUs connecting a LED and resistor.
Connect the buzzer and get it working.
Disconnect it, connect the display and get it working.
Same for one sensor.
Than try multiple sensors.
Than play with the WIFI module.
Than combine everything.

The key is to split up your (for a beginner) big project into smaller easier to handle projects.

If you want to add an LCD, depends fully on YOUR requirements; we don't know exactly what you want. If you send all data via WIFI in principle the receiver can display it, but maybe you have a good reason to display it on a display.


Save Leading Zero HEX into String RFID RC522 Arduino I'm using RC522 to read RFID card. All is until if the HEX leading by 0 then i can't save it into String. But if i print it to Serial all is well. Here is my code:

#include <SPI.h>
#include <MFRC522.h>
#include <stdlib.h>

#define RST_PIN         9
#define SS_PIN          10

String inStringHex = "";

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
}

void loop() {
  // Look for new cards
  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial())
  {
    //Serial.print("Card UID:");
    for (byte i = 0; i < 4; i++) {
      Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? "0" : "");
      Serial.print(mfrc522.uid.uidByte[i], HEX);
      inStringHex += String(mfrc522.uid.uidByte[i], HEX);
    }

    Serial.println();
    Serial.println(F("Hex normal"));
    Serial.print(inStringHex);
    Serial.println();
    Serial.println();

    inStringHex = "";
    delay(5000);
  }
}

Here is what displayed in serial monitor:

What i want is the String under "Hex normal" would be "04292e5a" not "4292e5a"

Please anyone help me.
Thank You.

String(mfrc522.uid.uidByte[i], HEX) means you want to convert number into hexadecimal string repesentation, if you pass 4 as input parameter, it will convert it into "4", not "04". You need to apply similar approach as you have used when printing the value through UART. For example:

if (String(mfrc522.uid.uidByte[i] < 0x10)
  inStringHex += " ";
inStringHex += String(mfrc522.uid.uidByte[i], HEX);

Personally, I would recommend switching from Strings into static buffers (because arduino has too small memory to use dynamic allocation and there could be issue with running out of memory due to memory fragmentation):

char id[16];
sprintf(id, "%02x%02x%02x%02x", mfrc522.uid.uidByte[0], mfrc522.uid.uidByte[1], mfrc522.uid.uidByte[2], mfrc522.uid.uidByte[3]);


Powering two L298N motor boards with external supply I have been struggling with this as I'm a complete electronics and arduino beginner. I am trying to power two DVD-drive stepper motors using two L298N motor boards.
For some reason, I can't figure out how to power them using external source.
I can connect one like this straight from the arduino and the motor spins properly:

I know this is bad because it could damage the arduino etc, so I tried to provide a separate power supply to the motor, which in this case is an iphone wall charger which provides 5V, 1A. I also tried with a power bank that supplies 5V, 1A. I wired it up like this but then the motors don't run:

I don't know what I am doing wrong. Any help would be greatly appreciated.

If your second schematic correctly represents your actual wiring, the problem is that you are connecting the arduino 5V pin (instead of the GND pin) to the L298 GND.

I assume you have also connected the control pins of the motor controllers to Arduino pins?


Weird serial behavior on atmega2560 EDIT
This seems to be something to do with the oscillators. Switching to the internal oscillator and writing straight avr-c allows me to run a basic blink program. Writing the same basic blink in arduino and flashing with the IDE (through serial or usbasp) results in a non functional program. I'd like to be able to use the oscillator because it doesn't look like I can get everything done in time at 8MHZ
I have an arduino mega 2560 which a few weeks ago was working fine. Now, I'm trying to output some data from it, and 've broken it down to a very, very basic proof of concept:
void setup() {
// put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
   // put your main code here, to run repeatedly:
   Serial.println("hello");
}

This prints:
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

indefinitely on the screen. If I change the baud to 115200, I get the "hello" and the newline, and slowly start getting garbage afterwards. If I switch to 234500, I get a few prints, and then nothing.
Adding a delay after the print does not change the frequency of the serial prints:
void loop() {
// put your main code here, to run repeatedly:
    Serial.println("hello");
    delay(100000);
}

They still come in immediately.
I have a feeling this has something to do with timing of an interrupt, but I'm not setting anything up. I plan to reflash and fix the fuses, but my usbASP cable is broken right now. Any other input on what might be going on here?
Edit:
This occurs on two different boards. I originally had some i2c devices (mag/gryo/barometer) on board, but those have since been removed. I have tried two different usb cables in two different USB ports. This might be on the host side?
Edit:
Both the TX and Rx lights are solid this whole time. Almost as if there's a loopback. My other laptop won't even boot right now. I'm concerned a surge from a storm last night might have taken out both of these machines
More testing:
Looking at the output on a scope, the board is actually only outputting an "h" character. If I do:
Serial.println('U');
delay(1000);

I get a square wave, so the delay doesn't run at all.
If I do:
Serial.println('U');
Serial.println('U'); //or any other character
delay(1000);
I get a U character over the scope, and then an empty serial frame. The delay still doesn't run, but it looks like the second println is exiting.
Even burning a new bootloader fails on these boards

Answering my own question - a bit of a walk of shame here.
I had disabled the internal TIMER0_OVF_vect in the arduino core code, so that I could write my own (for another project). I wrapped in in an #if 0 so I could go and bring it back when I needed it.
Today, I learned that the atmega interrupts aren't filled with an IRET by default, but instead hit the reset vector, resetting the board. Anything I compiled on this library would reset whenever TIMER0 overflowed, because my ifdefs didn't cover the TIMSK setting in the arduino core either
The "Serial.println isn't exiting" was actually "the board is resetting before it can complete" and explains why faster bauds could print more data.
Not much smarter than hairless apes, sometimes.


HLW8032 UART sends random data ( Registers Overflow often) I designed  my own version of smart socket just like the Sonoff with power metering chip HLW8032. And when I read the data in ESP-12F the data doesn't have a fixed format.
To troubleshoot the issue, I bought HLW8032 Breakout Board and analyzed the data sent by HLW8032, and I found the results are the same as the board I designed.

And that made me think that I may be reading the data from the Serial port the wrong way.

HLW8032 sends 24 Bytes on the serial and the format should be like this:

F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9C 2A 39 61 00 00 79
F2 5A 02 DA 78 07 1A E0 00 3D 3B 03 EC F5 4C C4 58 9D C2 9F 61 00 00 78

The data that I receive is in this format,

F2 5A 2 D3 70 6 BC D4 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FB EC 17 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FD 84 7D 61 0 1 38 F2 5A 2 D3 70 6 AA 59 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 2 D3 70 6 AA 59 0 3D 4F
4 98 B4 4D E1 80 FE FF 1 61 0 1 38 F2 5A 1 61 0 1 38 F2 5A 2 D3
70 6 AA 59 0 3D 4F 4 98 B4 4D E1 80 FE FF F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 0 3D 4F 4 98 B4 4D E1 80
FE FF 1 61 0 1 38 F2 5A 2 D3 70 6 AA 59 38 F2 5A 2 D3 70 6 AA 59
0 3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 FE FF 1 61 0 1 38 4F 4 98 B4 4D E1 80 10 1B
D4 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0 3D F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 13 4E 9E 61 0 1 39 F2 5A 2 D3 70 6 AA 59 0
3D 4F 4 98 B4 4D E1 80 14 E8 3 61 0 1 39 E1 80 16 82 67 61 0 1 39
F2 5A 2 D3 70 6 AA 59 0 3D 4F 4 98 B4 4D F2 5A 2 D3 70 6 AA 59 0

We can see that the registers overflows again and again.
The code that I use to read the data is:

#include <SoftwareSerial.h>
#define BAUD_RATE 4800

SoftwareSerial swSer(13, 12);

void setup()
{
  Serial.begin(BAUD_RATE);
  swSer.begin(BAUD_RATE);
}

byte data[24];
void loop()
{
  if (swSer.available() > 0) {
    int a = swSer.readBytes(data, 24);
    yield();
  }

  // Display
  for (int i=0;i<24;i++)
  {
    Serial.print(data[i],HEX);
    Serial.print(" ");
  }
  Serial.println();
}

Schematic:

I feel that there is no issue in my hardware design, and the issue seems to be in the sketch.

What can be the possible problem with my setup?

How do I make the output of HLW8032 Stable with no overflow of registers?

Is there any library someone can recommend me to read the data from HLW8032 on SoftwareSerial?

Note: After some troubleshooting I found that delay() cause the problem to be more worse. And won't receive a stream of Bytes whose first byte , second nibble is F like F2, F4, as from the datasheet , first four bits are 1s by default.

First of all I swaped UART0 to GPIO15 (TX) and GPIO13 (RX), (Luckily the Tx of HLW8032 is connected to GPIO13 in my hardware design and This is the UART0 RX pin after swap). Then I analyzed the data coming and the results were the same as of that SoftwareSerial i.e the registers overflows.

Then I used an HLW8032 Library (Which I've forked and will make changes for improvements) which only works on HardwareSerial, and the values are perfect. The way the library reads Serial is quite different.

So in short my issue resolved using two things:

I swaped UART0 to GPIO15 and GPIO13 using Serial.swap()
Used a library for the HLW8032

Thanks to @Juraj who provided the useful link about Serial Swap in ESP8266.

  Serial uses UART0, which is mapped to pins GPIO1 (TX) and GPIO3 (RX). Serial may be remapped to GPIO15 (TX) and GPIO13 (RX) by calling Serial.swap() after Serial.begin. Calling swap again maps UART0 back to GPIO1 and GPIO3.

#include "HLW8032.h"

HLW8032 HL;

void setup()
{
    HL.begin(Serial,4);
    Serial.begin(4800);
    Serial.swap();
}

unsigned int V;
void loop()
{
    HL.SerialReadLoop();

    if(HL.SerialRead == 1)
    {
    V = HL.GetVol();
    }
}

With this I can't print and see my debug prints on  GPIO1 (TX) and GPIO3 (RX), but at least without changing a bit in the hardware, my design works fine.


4-digit 7 Segment LED displaying numbers in the wrong order I am a novice Arduino programmer and am currently having trouble with a SH5461AS 4-digit/7-segment LED when using it with an Arduino Uno. I have struggled to find an accurate datasheet/tutorial of any kind for this particular model (It is the LED without the colons in between digits 2 and 3) but I believe I have it figured out.

I currently have it going through a HC595 shift register but when I removed the register and connected the LED directly to the board the problem remained. My code below is with the shift register; I am displaying it this way because it is simpler to view and I thought it would make it easier to debug.

I can display a single digit at a time correctly. However, when I try to display 2+ digits at one time, they are in the incorrect order.
For example, I can count 1-9 on the first digit, then 1-9 on the 2nd digit, and so on and everything displays correctly (other digits are off). But as soon as I try to display multiple digits they are in the wrong order. So if I try to display 12__ with the last 2 digits off, 21__ is displayed with the last two digits off. If I try to display 23, 32 is displayed. If I try to display 1234, 4123 is displayed.

I am at a loss because the code seems like it should be simple.

const int DATA = 0;
const int LATCH = 1;
const int CLOCK = 2;

const int DIGIT_ONE = 3;
const int DIGIT_TWO = 4;
const int DIGIT_THREE = 5;
const int DIGIT_FOUR = 6;

//digits[0-9] corresponds to the patterns for numbers 0 -> 9.
//Add 1 to the digits[X] to turn on the dot.
byte digits[] = {B11111100, B00011000, B01101110, B00111110, B10011010, B10110110, B11110010, B00011100, B11111110, B10111110};

void setup() {
  pinMode(DATA, OUTPUT);
  pinMode(CLOCK, OUTPUT);
  pinMode(LATCH, OUTPUT);

  pinMode(DIGIT_ONE, OUTPUT);
  pinMode(DIGIT_TWO, OUTPUT);
  pinMode(DIGIT_THREE, OUTPUT);
  pinMode(DIGIT_FOUR, OUTPUT);

  digitalWrite(DIGIT_ONE, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);
  digitalWrite(DIGIT_FOUR, HIGH);
}

void loop() {
  writeDigit(DIGIT_TWO, 2);
  writeDigit(DIGIT_THREE, 3);
}

/*
 * Write a digit to the 4-digit 7-segment LED
 * - digitPin corresponding to the pin on the LED to light up the correct digit.
 * - number 0-9 to display on the LED
 */
void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

So in this instance, I am expecting 23 but 32 is displaying instead.

I am also having trouble with some bleeding (I don't know what the correct term is) where some segments are very faintly glowing even though I am not doing it intentionally. This is a much smaller issue, however, than digits randomly in the wrong order.

If it would help, I can try to post the circuit diagram as well.

Here is a datasheet I found that seems a better macth for your display model (that's the datasheet for a display that I use):

http://www.play-zone.ch/en/fileuploader/download/download/?d=1&file=custom%2Fupload%2FFile-1356269320.pdf

This is the datasheet I directly got from my local supplier.

According to what you say, the problem does not seem to be a wiring problem.

It looks more like a timing issue:

void writeDigit(int digitPin, int number) {
  digitalWrite(digitPin, LOW);

  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);

  digitalWrite(digitPin, HIGH);
}

The first issue when you call writeDigit() is that it forces the cathod low BEFORE having set the shift register, so the digit will first show the current register value, i.e. the one from the previous call to writeDigit().

Then it pushes the new value for the segments on the shift register, that will be fast but not as fast as two consecutive calls to loop().

If we try to roll and expand the loop() call in your example that will be:

// First call: writeDigit(DIGIT_TWO, 2)
  digitalWrite(DIGIT_TWO, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_TWO, HIGH);

// Second call: writeDigit(DIGIT_THREE, 3)
  digitalWrite(DIGIT_THREE, LOW);
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(DIGIT_THREE, HIGH);

The calls to loop() and writeDigit() are negligible in terms of timing here.

In the sequence above, most of the time is spent in:

  shiftOut(DATA, CLOCK, LSBFIRST, digits[2]);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[3]);

So that means your function will:

show the previous value on the new digit for t1 us
show the new value of the new digit for t2 us

with t1 >> t2, hence your eyes will see the opposite of your intent!

To fix that issue you definitely need to introduce some delay to reverse what your eyes will see:

void writeDigit(int digitPin, int number) {
  digitalWrite(LATCH, LOW);
  shiftOut(DATA, CLOCK, LSBFIRST, digits[number]);
  digitalWrite(LATCH, HIGH);
  digitalWrite(digitPin, LOW);
  delayMicroseconds(100);
  digitalWrite(digitPin, HIGH);
}

In the code above:

no digit shows while the shift register is set
the requested digit shows immediately after the shift registry has been written and lacthed, and for a duration of 100us, which will be much longer than the rest of the time.

That code should also get rid of the "bleeding" you observed.


LininoIO running "partially" I installed LininoIO (OS dated 02 06 2015).

Everything seems to work fine - but nothing works as expected.

I have a running Linux - but when I try to use GPIO, as described on Lilino.org -GPIO on lininoIO, I run into the first problems.

D13 doesn't exist (this should be the little red LED on board of the Yún).

Next I tested reading the analog inputs.

I can for example use cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw. There are no errors, but I always get the value 0.

Checking with /etc/linino/test_avrdude.sh shows:

Testing AVRDUDE on ATMEL 32U4 ...

avrdude: Version 6.1-20140519, compiled on Jun  2 2015 at 12:34:59
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
Can't export GPIO 11, already exported/busy?: Device or resource busy
avrdude done.  Thank you.

Maybe this is "by design" or another sign of an error.

By the way - when I start a serial console I get the message:

avr-uart: switched to uart mode: mcuio

Further in kernel log I found:

[   42.480000] fuse init (API version 7.18)
[   42.620000] spi_tty_plain spi1.0: spi_tty_probe
[   45.380000] No need to change console settings
[   49.550000] mcuio-hc 0:0.0: unexpected reply
[   49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic
[   49.630000] mcuio adc is 0:1:1
[   49.750000] mcuio-adc 0:1.1: 6 input channels detected
[   49.910000] mcuio-hc 0:0.0: unexpected reply
[   49.970000] mcuio pwm is 0:1:2
[   49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected
[   55.790000] busybox: sending ioctl 5310 to a partition!
[   55.800000] busybox: sending ioctl 5310 to a partition!
[   55.820000] busybox: sending ioctl 5310 to a partition!
[   55.830000] busybox: sending ioctl 5310 to a partition!
[   56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities
[   56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities
[   56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)
[   58.520000] cfg80211: Calling CRDA for country: AT

It seems as if there are problems with mcuio-hc.

Last thing - when I ran run-avrdude /etc/linino/bathos-one.hex
I get an error when comparing the written data (I found information that this can be ignored).

How can I fix this / find out what to fix / what's going wrong?

finally I got it (somehow) working.
After a reset and another run of run-avrdude /etc/linino/bathos-yun.hex (the first was a mistake by copy and past - not bathos-one I already ran bathos-yun before) and a reboot again I was able to read analog IO.

But still the digitals were missing.
Than I found the command gpioexport an ran it.
After that the correct entries (D13, D14...) were present in sys/class...

But an echo out > D13/direction resulted in a timeout error message.
Again reboot - again the Dxxx entries were gone.
Another gpioexport made them appear again.

And this time not timeouts - instead I could turn on / of D13 (for test).

I guess all I have to do to make the things better is include gpioexport in "startup code" so that it runs after a reboot.


Arduino with 2 echo sensors For a project I'm doing I need the Arduino to be connected to two echo sensors (I have the HC-SR04). Currently I have 4 sensors that I can use, but I will need only 2 or 3.

I have almost no knowledge of coding and the Arduino, but I figured out how to connect it to one echo sensor, and that is working, which is great.

But now I need it to connect to two. I found example code with 3 echo sensors, but whenever I connect them my Arduino shuts down. I guess it is because it takes up too much power, my teacher said something like that. All lights turn off all of the sudden, and it doesn't reset. Only when I remove some the wires for the power, it works again.

So 3 isn't going to work. I figured I'd stick to two. Now the problem: Whenever I try to edit the code to two echo sensors (I basically just removed the trigPin3 and echoPin3 in the first part of the code, and the SonarSensor(trigPin3, echoPin3)), it doesn't work anymore. The monitor doesn't show any values anymore, while it did with the first code. It just shows zeroes now.

So my question is, how can I edit the example code so that it works with 2 echo sensors?

This is the code I found for the 3 echo sensors:

#define trigPin1 3
#define echoPin1 2
#define trigPin2 4
#define echoPin2 5
#define trigPin3 7
#define echoPin3 8

long duration, distance, RightSensor,BackSensor,FrontSensor,LeftSensor;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);
  pinMode(trigPin3, OUTPUT);
  pinMode(echoPin3, INPUT);
}

void loop() {
  SonarSensor(trigPin1, echoPin1);
  RightSensor = distance;
  SonarSensor(trigPin2, echoPin2);
  LeftSensor = distance;
  SonarSensor(trigPin3, echoPin3);
  FrontSensor = distance;
  Serial.print(LeftSensor);
  Serial.print(” – “);
  Serial.print(FrontSensor);
  Serial.print(” – “);
  Serial.println(RightSensor);
}

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

And this is the one that IS working, but with 1 echo sensor:

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200;
int minimumRange = 0;
long duration, distance;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  if (distance >= maximumRange || distance <= minimumRange) {
    /* Send a negative number to computer and Turn LED ON
    to indicate "out of range" */
    Serial.println("-1");
    digitalWrite(LEDPin, HIGH);
  } else {
    /* Send the distance to the computer using Serial protocol, and
    turn LED OFF to indicate successful reading. */
    Serial.println(distance);
    digitalWrite(LEDPin, LOW);
  }
  //Delay 50ms before next reading.
  delay(50);
}

I hope someone can help me!

Many thanks, Leah.

In the 1 sensor program all the delays added together account for
62ms between samples.
In the 3 sensor program the sample code contains delays which likely
exceed 12ms (delays plus code execution).  So each sensor will not be
sampled faster than once every 36ms.
After you removed 1 sensor from the 3 sensor program, you increased
the sampling rate to about every 23ms.
It is likely a minimum amount of time is necessary between samples in
order for the HC-SR04 to recover.


Arduino IDE crashes without any warning I'm a beginner in Arduino. I just installed Arduino IDE (arduino-1.0.5-r2-windows) but when I try to run its not responding and crashes after few minutes. I tried re-installing it and removing the temporary files but none of those helped.

Can anyone tell me what causes this problem and how to debug it?

Installing Arduino 1.5.6 solved the issue.


Measure an AA battery? If I'm going to measure an AA battery (about 1.5 v) with a USB-powered Arduino, I will connect the battery's +ve terminal to the A0 pin. Shall I connect the -ve terminal to the gnd pin too?

Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.


Serial communication on Arduino Uno I have a Raspberry Pi 3 connected to the serial of my Arduino Uno (pins 0 and 1), but I also have another device connected to two other serial pins on the Arduino (pins 10 and 11, using the SoftwareSerial library).

What I want to do is send a string from the RPI, then the Arduino gets it and resends that information through the other serial port to my device.

Until now the Arduino can receive the information from the RPI, but I'm not sure how to send that same string through the other serial port, the one going to the device.

Here is the code I'm using:

#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }
  portOne.listen();
  while(portOne.available() > 0){
      Serial.println("Data from port one:");
      Serial.println(b);
    }
  }

I just get the data coming from the RPI, but nothing from portOne.

Any thoughts?

Your code is not reading the SoftwareSerial. b is only populated when the Pi sent data. The loop below sends what it reads from the SoftwareSerial, after that is prints a new line println() (only because that's what your code is doing)

The listen() method of SoftwareSerial is only required if you have more than one SoftwareSerial connection.

#include <SoftwareSerial.h>

String b = "0";
SoftwareSerial portOne(2, 3); //RX= pin 2  TX= pin 3

void setup() {
  Serial.begin(9600, SERIAL_8N1);
  portOne.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    b = Serial.readString();
    Serial.println("Data from RPI:");
  }

 //not required with only one software serial connection
 //portOne.listen();

  if (portOne.available() > 0)
  {
   while(portOne.available() > 0){
      byte byteRead = portOne.read();
      Serial.write(byteRead);
    }
    Serial.println();
   }
  }


Why am I getting "fatal error: SoftwareSerial.h: No such file or directory" I downloaded the Adafruit_GPS library from Adafruit and I'm trying to compile the example code (due_parsing) but I can't seem to get past this silly error:

In file included from due_parsing.ino:15:

/Users/haddad/Documents/Arduino/libraries/Adafruit_GPS/Adafruit_GPS.h:24: fatal error: SoftwareSerial.h: No such file or directory
compilation terminated.

This is the location in the example Arduino Sketch where SoftwareSerial.h is mentioned:

#ifdef __AVR__
  #include <SoftwareSerial.h>
#endif

I noticed it's around an ifdef guard, so shouldn't it not even matter that I don't have this library?

I went into the .h and .cpp files and commented out the where it called SoftwareSerial.h, but I'm still getting that above error.

Does anybody know how to fix this?
I am using Arduino IDE v1.5.5

Update:

I didn't put the library in the library direct on my mac but I'm now getting tons of errors, all the errors are with SoftwareSerial.cpp. Is anybody else having similar issues when you go to compile?

According to your comment:

  after commenting out those ifdef guards, it worked

I would say that is a bug in the Adafruit_GPS library.

As a matter of fact, the DUE is not using the AVR architecture (it uses ARM), that explains why #ifdef __AVR__ in Adafruit_GPS.h never passes; but then something else should be done specifically for the DUE (missing #else or #elif).

After checking on github, there is an issue open for that; unfortunately, as of April 2014, it has not moved for 10 months.

Your best guess would be to go there and try to "reactivate" this issue.


GSM library_ all examples ar working except GPRS? i am using arduino uno and sim808. i connected the sim808 to pins 2,3 on arduino uno and used GSM library. i tested all examples: make and receive a call or messages. the part of GPRS initialization is not working after many tries in changing APN and pin number.
i want to use the arduino as a webserver exactly as the example includded in the library.
any one can help?
thanks,
https://www.arduino.cc/en/Reference/GSM

I had the same problem I solved it by moving the jumper wires on the shield(if you are using one) to SW serial. if that doesn't work try testing it with AT commands


Turn on a LED when an other LED turn off I'm a beginner on arduino.

I have an arduino mega with two LED (like the image with only 2 less and without the buzzer). A red LED and a green LED. When the arduino receive the code 200 I want the red LED turn on and the green LED turn off. But when I test that but any led turn off or turn on..

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

void readSerial(){
  while(Serial.available() > 0){
    car = Serial.read();

    if(car != '+'){
      buff[i] = car;
      buff[i+1] = '\0';
      i++;
    }
    else{
      sscanf(buff, "%d", &received_code);
    }
  }
}

void loop()
{
  readSerial();
  if (received_code == 200){
    LRstate = HIGH;
    digitalWrite(LR, LRstate); // turn the LED on (HIGH is the voltage level)
    digitalWrite(LR,LOW);
    delay(100);
    digitalWrite(LV,LOW);
  }
}

How can I solve my problem?

Thanks a lot.

First, make sure the LEDs are connected correctly: I presume the red LED is connected to whichever pin LR is, and the green LED to LV.

According to your diagram, your LEDs will be on if the output is HIGH, and off if the output is LOW.  Your code sets LR to high, but then immediately to LOW again.

Here's a fixed (I hope) verson of your loop():

void loop()
{
  readSerial();
  if (received_code == 200){
    // Turn the red LED on
    digitalWrite(LR,HIGH);

    // Turn the green LED off
    digitalWrite(LV,LOW);
  }
}

Unrelated to the problem you're having, but worth a mention anyway:

There's nothing in your code to stop you overrunning buf if you get a longer input than you're expecting.  If this happens you'll get unpredictable results as you trash over whatever happens to be in that part of memory.


What killed it? Arduino in resin I made a simple circuit controlled by the ATMEGA IC then tried to encase it in resin. It died. What is the thing that caused it to die? I've had other circuits working fine in resin. I want to try again, what steps can I take to prevent this?

I've looked for obvious shorts but can find none.

Resin heats up when it cures, could that be the issue?

Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.

Common problems are:

Resin entering a spring loaded contact and canceling out contact forces
Resin exsuding corrosive substances ruining contacts
Resin expanding during curing and opening spring contacts or even breaking up solder contacts
Same effect after cool down of resin

Later and often unexpected problems are:

thin gaps around potted objects (i.e. no surface contact) literally sucking in water.
potting material producing water itself during curing.

Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments.
If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.


Getting 3.3v on 5v pin in Arduino Uno When interfacing my Arduino Uno with a relay I was facing reliability issues, and while investigating it with a multimeter, I found something strange.

I noticed that in the 5V power pin (with which I was powering my circuit) is producing only 3.3V when using the power adapter. However, when connected via the USB-A port, the 5V pin was producing the expected 5V voltage.

I tried powering it in many ways - computer-to-USB-A, computer-to-barrel-jack, phone-charger-to-USB-A, phone-charger-to-barrel-jack and an external 5V DC power supply. In all cases, the above observation held true - powering the board through the barrel jack made the 5V power pins produce only 3.3V.

Question: Why is this happening? Does that mean my board is faulty? Is there any way to fix this?

and an external 5V DC power supply

OK, assuming you are putting 5V into the barrel jack this is exactly what you expect to happen.

From the Arduino Uno specifications you are supposed to supply a recommended 7V to 12V. Your supply of 5V is too low.

The barrel jack first goes through a M7 protection diode which would have about a 0.7V forward voltage drop, and then through a NCP1117ST50T3G voltage regulator which has a dropout voltage of (typically) 0.95V at 100 mA.

Thus you have:

5V input - 0.7V - 0.95V = 3.35V

That is what you are finding.

Solutions

If you have a proper, regulated, 5V DC supply you can put that directly onto the 5V pin of the Arduino. Better get the wires around the right way because you are bypassing the protection diode!
Get a DC supply in the range 7V to 12V and put that into the barrel jack.
Another simple idea is to just get a wall-wart that is used for charging phones via USB and run a USB cable into the Arduino USB port.

Empirical test

I put 5V into the barrel jack of my Uno and read 3.33V on the 5V pin, which is pretty-much what you got. I measured a 0.77V drop over the M7 diode.


What sensors can measure 3-axis acceleration? I'm currently measuring vibration, temp and noise using an Arduino and various inexpensive sensors. The acceleration sensor i found was sensors that measured the gravity on 3-axis of the sensor. But i'd like to measure acc, not gravity, as it moves in the direction of the sensor. For example, if an object is moving front-dir in a horizontal location, the x-directional acc is measured.

Could you tell me if you know the acc soensor i want.

The acceleration sensor i found was sensors that measured the gravity on 3-axis of the sensor

Gravity is acceleration.

An accelerometer measures acceleration - or more accurately, it senses the resistance to acceleration (inertia) and equates that to acceleration.

By holding an accelerometer still you are causing it to resist the pull of gravity, and it's that "resistance" that it measures - a constant 9.8m/s²

If you let the accelerometer freefall it won't be resisting gravity any more, and will measure 0 for the Z axis.

So you simply have to "ignore" gravity, by removing that constant 9.8m/s² ("1g") of acceleration from the Z axis.  And you do that by simply subtracting it.

It is normal to calibrate an accelerometer by keeping it at rest and reading the "idle" values. Those values are then subtracted from the readings to give you the actual value.


Ultrasonic Range Sensor won't print distance in Serial Monitor I'm using the red Ultrasonic Range Sensor with

Sig -> Digital Pin 4

VCC -> 5V

GND -> GND

The code uploads fine and i can hear the sensor clicking away, but for some reason it won't print the distance into the Serial Monitor.

//Settings
int echoPin= 4;
int trigPin= 4;
unsigned long pulsetime = 0;
unsigned distance = 0;
unsigned OldDistance = 0;

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

void loop(){

  //Work out the distance
  digitalWrite(trigPin, LOW);
  delayMicroseconds(100);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);
  pulsetime = pulseIn(echoPin, HIGH);
  distance = pulsetime / 58;
  delay(10);

  //Send value if it's changed
  if (OldDistance != distance) {

  Serial.print(distance);

  OldDistance = distance;
  }

  delay(50);  // Wait .1 Seconds
}

You have to manually switch from OUTPUT (for sending the trigger pulse) and INPUT (for reading the distance) mode on the shared IO pin.

//Work out the distance
pinMode(trigPin, OUTPUT);    // << ADD THIS
digitalWrite(trigPin, LOW);
delayMicroseconds(100);
digitalWrite(trigPin, HIGH);
delayMicroseconds(100);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);     // << ADD THIS
pulsetime = pulseIn(echoPin, HIGH);
distance = pulsetime / 58;
delay(10);

To save some confusion you might like to change your code to just use sigPin instead of a pair of pins that are both the same pin.  That way you would avoid confusing bits like:

pinMode (echoPin, INPUT);
pinMode (trigPin, OUTPUT);

Which of course is the equivalent to:

pinMode (4, INPUT);
pinMode (4, OUTPUT);


Cannot compile C++11 code via Makefile I am building my Arduino project with a makefile:

BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyACM0
USER_LIB_PATH = /home/prakhar/dev/alfred/arduino/libraries
CPPFLAGS=-x c++ -std=c++11 -Wall -DUNIX_ENVIRONMENT -DHAVE_NAMESPACES -DHAVE_STD
include /usr/share/arduino/Arduino.mk

I keep getting this error:

cc1plus: error: unrecognized command line option "-std=c++11"

I googled and this says that I need to update g++/gcc. I already have the newset versions:

prakhar@sim74stic ~ $ avr-g++ --version
avr-g++ (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ avr-gcc --version
avr-gcc (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ g++ --version
g++ (GCC) 4.9.1 20140903 (prerelease)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I installed arduino from the AUR (packages aur/arduino 1:1.0.6-1 and aur/arduino-mk 1.3.4-2).
Can anybody point out what I'm doing wrong?

As I turns out, the avr-gcc (GCC) 4.9.1 goodies weren't being used at all! The arduino package was using a decrepit version of gcc,

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ --version
avr-g++ (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-gcc --version
avr-gcc (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

All I had to do was specify:

AVR_TOOLS_DIR = /usr

to exexute with -std=c++11 flag (I also had to add an -fpermissive flag to compile C with g++).


How to save a hex file into Arduino Flash to send it via Serial? I have a text file with hex values formatted in the following style:

A0 3F 55 01 00 C7 55 01 00 C7 AA 29 71 11 00 0B
00 C7 AA 29 71 1F AA 29 71 11 55 01 A0 3F 55 DC
...

How can I save this data into my Arduino's Flash (to save RAM)? What libraries are needed? Is there any tool that can automatically create code for this purpose?

After I save this data into the Arduino's Flash, I want to send the data via Serial. I have to send it as binary.

A solution without saving it into the Flash would be also OK.

I am using an Arduino Due.

If I understand your question correctly, you need to integrate this data into a .ino script.  Probably as a byte array. Then the script can read the array and Serial.write its content.

You could write a small tool in Python or else on your computer, that takes the text file and converts it into a .h header. Include that into your .ino script. Or use your favorite text editor to format the data into C++ code, and copy/paste that into your script.


Atmega 328P U crash on 5V/1A Atmega 328PU crash on 5v/1A. Why? It works on 5V/400ma but when i switch it to 5V/1A power it crash. Any idea or solution for this?

Nothing wong, if your power supply is trustworthy enough, then , if u even provide 100000 Amps of current with 5 volt,
your IC won't burn, in your case , it burnt because your power supply seems to be defective, and please check the voltage of the power supply which is supposed to be defective, so it output more than 5 volts burning or crashing your ic...
Note:
I have personally worked with 5 volt 6 amp power supply which is very well precise and my ic is working full fledged without any problems.


How can I have different routines fire off at different intervals So i'm making an interface that will have a digital clock....once a secondd..
i'd like to do other things at different intervals but if I delay(1000) then I have to wait that second which is now the minimum other things have to run at..

As said in the comments: you should read up on State Machines and have a close look at the Blink Without Delay example.
To get you started with an example closer to what you want to achieve, have a look at the code below; it will count seconds without blocking the loop.
unsigned long int secondsTimerMillis;
int seconds, minutes, hours = 0;
int secondsInterval = 1000; //ms

void setup() {
  Serial.begin(9600);
  // More setup() stuff goes here
  secondsTimerMillis = 0;
}

void loop() {
  if ((millis() - secondsTimerMillis) >= secondsInterval) {
    seconds++;
    secondsTimerMillis = millis();
    Serial.println(seconds);
    // More stuff you want to do every second goes here
  }
  // More loop() stuff goes here
}

This is just the basic mechanism, and it won't be very accurate without some way of adjusting the clock every now and again.
You will also have to add code for checking seconds == 60 and increase minutes / reset seconds when needed; the same goes for hours.
Having/handling other events at other intervals is just more of the same.
Note that using a Real Time Clock as the basis for your timing would make your life programming much easier, and your clock more accurate, but I am assuming you want to do this "by hand".


Arduino Uno with Camera and LCD I would like to ask you if I can display real time view from Camera in Arduino Uno with LCD.

I have that components:

Camera OV7670 VGA 0.3 MPX
LCD TFT 2.4 SPI ILI9341
Arduino Uno R3

On a website: arducam.com there are used another components. I bought that parts because in a documentation in auction was that is compatible with Arduino.
I see that in Arduino UNO is not so much pins.

Could somebody help me to resolve this challenge?

Regards

No, this is not possible.

The camera outputs a JPEG image. To display that on the TFT screen it is necessary to decompress that JPEG image and send the raw 16-bit (RGB565) colour information to the screen.

The Arduino doesn't have enough memory to do the job.

I wrote an absolute minimal JPEG decompressor a while back. It uses the absolute minimum memory possible (it operates on one macroblock at a time), and still requires around 100KB. That's 50x more than the Arduino Uno has.

Also on a 200MHz, 32-bit chip with FPU it takes about a minute to decompress a 320x240 pixel image. I can't even begin to imagine how many days that would take on a little Arduino Uno even if it did have enough memory to do the job...

As has been suggested, you need a more powerful board. And if you're going that route you may as well drop the useless OV7670 and get a Raspberry Pi with a proper Pi Camera module (or at least a USB webcam).


Stopping / starting DC motor with Limit Switches and on/off button I have an Arduino UNO with 3 switches attached (2 limit switches, 1 activation switch). I'm trying to make the activation switch turn the motor forwards once hit, then wait for any of the limit switches to be hit and stop the motor. The next step is to wait for the activation switch to be hit again and turn the motor in the opposite direction and wait for the limit switch to be hit and stop the motor.

But the issue I'm facing right now is when i press the activation switch the arduino board and H bridge board restart. The LED's turn on and off and the code restarts. And nothing happens. I know all the switches and motor is working because i have tested them by simplifying the code with just the functions.

(edit) Here is a picture of the schematic:

Can someone please review my code below to see if my logic is correct.

const byte  frontButtonPin = 2;
const byte  backButtonPin = 4;
const byte  onOffButtonPin = 11;
const int   motorPin =  8;
const int   motorPin2 =  7;

boolean  frontButtonState = 0;
boolean  backButtonState = 0;
boolean  onOffButtonState = 0;

/**
    setup inputs for switches and outs for motor pins
    serial begin to read the switches to test for errors
*/
void setup() {
  // initialize the pin as an inputs:
  pinMode(motorPin, OUTPUT);
  pinMode(motorPin2, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(frontButtonPin, INPUT);
  pinMode(backButtonPin, INPUT);
  pinMode(onOffButtonPin, INPUT);
  Serial.begin(9600);
}

/**
   this function turns motor foward
*/
void drawMovesForward() {
  // turn motor foward:
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}

/**
   this function turns motor backwards
*/
void drawMovesBackward() {
  // turn motor in other direction:
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}

/**
   Stop the motor form moving
*/
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**

*/
void loop() {

  frontButtonState = digitalRead(frontButtonPin);
  backButtonState  = digitalRead(backButtonPin);
  onOffButtonState = digitalRead(onOffButtonPin);

  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();

    }

    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }

  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }

    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }
}

Check your switches have pull-up resistors

It would be helpful if your question included a schematic. Do you have pullup resistors in line with your activation and limit switches? If not, you might find the input is "floating" - that is, it will randomly return either HIGH or LOW. This would possibly cause the motor to go forwards and backwards, but because the loop is possibly occurring hundreds of times per second, you might not see anything moving. You need pull-up or pull-down resistors in the circuit so the Arduino can see a definite LOW or HIGH. See https://www.arduino.cc/en/Tutorial/Button for a tutorial with a resistor, or even better, use https://www.arduino.cc/en/Tutorial/InputPullupSerial and use the existing onboard pullup resistors on the Arduino, as suggested by Juraj below.

Potential Logic Error

There might be a logic error in this part of the code:

  if (onOffButtonState == HIGH) {
    if ( frontButtonState == LOW ) {
      drawMovesForward();
    }
    else if (backButtonState == LOW ) {
      drawMovesBackward();
    }
  }
  else {
    if ( frontButtonState == HIGH ) {
      stopDrawFromMoving();
    }
    else if (backButtonState == HIGH ) {
      stopDrawFromMoving();
    }
  }

Loop #1: Let's say the onOffButtonState is HIGH (someone has pressed the switch to ON). The drawer is closed, so the front limit switch is depressed, so frontButtonState is HIGH. So the program will execute stopDrawFromMoving, and do nothing. Currently you are saying nothing is happening, so this might be your issue.

What you will probably need to do is use flags and while loops. For example:

At the start of the loop() declare this

drawerMovingOutFlag = 1;

Then change the loop to contain:

if (onOffButtonState == HIGH) {
    if ( frontButtonState == HIGH ) {
        while(drawerMovingOutFlag == 1)
            drawMovesForward();
            if ( backButtonState == HIGH ) {
                drawerMovingOutFlag = 0;
                stopDrawFromMoving()
            }
        }
    }
    else ...

I'll let you do the rest!


Arduino Uno: Receive MIDI data from DAW I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)

I would be happy using a Serial>Midi of some sort if it's the only way, but true USB MIDI would be nice.

The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.

On AVRs, you typically use the Lightweight USB Framework for AVRs (LUFA), which has support code for both the basic USB protocol and for USB MIDI.


Where to connect shield in USB power supply for Arduino? I'm making a 5 volt portable regulated power supply (using LM7805 regulator IC) for Arduino UNO. I'm planning to use a USB connector as its output socket, this way I can just plug it into the Arduino to power it.

My problem is where do I connect the USB sockets's shield? (Not an Arduino shield - I am talking about the USB cable's shield).

As far as I know it should be connected to the ground if it is a host device - can we consider the power supply as a host device?

If the supply for the Shield is 5V, then you can use one of the 5V lines on the Arduino to power the Shield, plus a common ground of course.


How do I use a photodiode for arduino? I am doing a project that requires me to program an arduino to sense changes of a steady stream of light due to the scattering of that light. If the phootodiode does change its resistance to the current, then a flap will turn a certain number of degrees. I'm not sure how to operate a photodiode, but know the basics of how it works.

The apparatus is designed to increase the operating life of a solar panel on Mars. When dust from a dust storm collects on its surface, a photodiode will detect the change in light and change its resistance to a current running through it. Then a flap connected to the solar panel will close to cover the solar panel. I'm using Hitec HS-311 Standard servo to rotate  the flap, but I've had some problems operating it.

try to use an opamp to create a voltage output from the diode. you can then adc that voltage output from the mcu.


LED sequence control by button I want to make sequential LED by using arduino that controlled by button.
If I press + button, LED will increase from L1 to (L1 and L2 is HIGH), then I press button again, L1, L2, and L3 will be HIGH. If I press again, all the LED (L1, L2, L3, L4) will be high.
Same case if I press “ – “ button, LED will be lower from the previous state. Which mean that if L1, L2, and L3 is HIGH. There will be L1 and L2 only HIGH if I press ‘ – ‘ button. I dont how to do it. This is code for increase but I dont know how to make it reverse flow.

const int buttonPin = 2; // the pin number of the pushbutton input pin
int ledPins[] = {3, 4, 5,};
 // variables will change:
 int buttonState = 0; // variable for reading the pushbutton status
 int buttonPressCount = 0;
 int numberOfLED = 3;
 void setup() {
  // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
   pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
 }
 void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
   for (int i = 0; i < numberOfLED; i++) {
    if (buttonPressCount % numberOfLED == i) {
     // turn LED on:
     digitalWrite(ledPins[i], HIGH);
    } else {
     // turn LED off:
     digitalWrite(ledPins[i], LOW);
    }
   }
   buttonPressCount++;
   delay(400);
  }
 }

My original answer was probably over-kill....Just keep track of how many leds are lit:

int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
byte num_leds_lit = 0

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
    }
}

Then, on button press, increase the count:

if (num_leds_lit < num_leds) {
    num_leds_lit += 1;
    set_leds();
}

Then to turn the leds off with the other button press:

if (num_leds_lit > 0) {
    num_leds_lit -= 1;
    set_leds();
}

------------------------- Original answer

There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off

// Each bit represents the state of one LED (0 == off, 1 == on)
byte led_bits = 0;
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
// Need a mask to make sure we don't set too many bits
const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        // Turn on/off based on state of bit
        digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
    }
}

Then, on button press, set the mask:

led_bits << = 1;          // Shift left (001 -> 010)
led_bits |= 1;            // Set lsb    (010 -> 011)
led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
set_leds();

Then to turn the leds off with the other button press:

led_bits >>= 1;          // Shift right (011 -> 001)
set_leds();


Do Arduino Nano Every devices short out? I have an Arduino Nano Every device that seems to have shorted out.
I use a lighted USB hub with buttons that turn connections on and off.  Each button has its own LED that indicates power state for its associated port.
Anyway, when I plug my Arduino Nano Every into that USB hub, the lighted buttons turn off for half of the hub, like the Arduino is shorting out the hub.
I use a different Arduino and have no problems, so it's definitely the Arduino.
Any idea what could have caused this?  I was using the Arduino with a TMUX1511 switch chip and using pins  D9-D12 to turn on and off the 4 internal switches in the chip.  It's using very low voltage (5v) and amperage is (25 mA).  I used the 5v and gnd pins on the Arduino to power the TMUX1511 chip, but with such low amperage, I can't see how that could have caused the Arduino to fry.
Any ideas?

this might because of powering issue...try using different source having a good number of current capability. likely up


Arduino: Read frequency of input from audio jack I want to trigger an arduino from a sound from an audio jack from a mobile phone. The audio is a 1 Khz sound that the mobile will play. I want to avoid accidental triggering of the audio by testing for specifically that frequency.

I've found several tutorials using analog read, but the output is not in hertz.

How do i get the output in Hertz?

int incomingAudio;

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

void loop(){
  incomingAudio = analogRead(A0);//read voltage at A0
  incomingAudio = (incomingAudio+1)/4 - 1;//scale from 10 bit (0-1023) to 8 bit (0-255)
  if (incomingAudio<0){//deal with negative numbers
    incomingAudio = 0;
  }
  PORTD = incomingAudio;
  Serial.println(PORTD);

}

You can measure a single "pure" frequency by counting the number of times that the pin changes, by using the inbuilt timers. Here is a sketch from my page about timers that accomplishes that:

// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Feeding in a 1 kHz sine wave (from 0V to 5V) I get this output:

Frequency Counter
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1002 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.
Frequency: 1000 Hz.

There is the occasional mis-reading but it looks accurate enough. You might sample a few times, and if you get something between 990 and 1010, five times, you might consider that a match.

You will need to make sure that the input is in the range for triggering the input circuitry of the Arduino. It should be around 4 to 5V, and not higher than 5V (for a high). It also should not go negative.

Something like this will protect the input pin:

Warning - audio from an audio jack will be AC and it will go negative. Make sure you use a suitable input protection.

Amplification

After looking at Wikipedia - Line level it seems likely that the output from your phone will not be high enough (around 700 mV probably). Therefore a simple transistor amplifier will probably be required to raise it to a level that can be detected.

Inspired by this post on Electronics Stack Exchange, I made up a simple amplifier:

Testing out with around 500mV peak-to-peak input indicates that it successfully amplified it to 0 to 5V DC:

Alternative method with analog comparator

Based on suggestions by Chris Stratton, there is another way of doing this.

You can use the analog comparator to detect an analog signal passing a threshold, like this:

I have set up the voltage divider to trigger at 0.265V, so that a 500 mV signal should provide an acceptable triggering range.

As for the sketch, at these frequencies we can do something simpler than what I posted before:

volatile bool counting;
volatile unsigned long count;

ISR (ANALOG_COMP_vect)
  {
  if (counting)
    count++;
  }

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

unsigned long startTime;

void loop ()
  {

  if (!counting)
    {
    startTime = micros ();
    count = 0;
    counting = true;
    }
  else
    {
    // is a second up? (1000000 microseconds)
    if (micros () - startTime >= 1000000)
      {
      counting = false;
      Serial.print (count);
      Serial.println (F(" Hz."));
      }  // end of a second being up

    }  // end of if

  }  // end of loop


splitable jumper wires question I just received my starter kit from oddwires.com today and it came with a split-able ribbon cable for prototyping. I was curious if it is possible to split each wire off and use only what I need to for the tutorials or is that a bad idea? I am very excited to start playing around and learning this as it has been a interest of mine for many years.

Each wire in the Dupont ribbon cable is is independent, and does not hold onto its neighbors with any real force. You can split them or join multiple wires together using larger connectors as desired.