body:
- I developed a simple push button project
- I used a wemos D1 mini
- I connected  D3 pin to a pull down 1K resistor.
- I used a multimeter to measure D3 pin voltage.

When I push the button, D3 pin voltage changes from 0.x volt to 4.x volt. But digital read on D3 always return HIGH.

Please help me find the problem.

This in my sketch :
```c++
    int ledPin = D2; // choose the pin for the LED
    int inPin = D3;   // choose the input pin (for a pushbutton)
    int val = 0;     // variable for reading the pin status

    void setup() {

      pinMode(ledPin, OUTPUT);  // declare LED as output
      pinMode(inPin, INPUT);    // declare pushbutton as input
    }

    void loop(){

      val = digitalRead(inPin);  // read input value
      if (val == HIGH) {
        digitalWrite(ledPin, LOW);
      } else {
        digitalWrite(ledPin, HIGH);
      }
    }
```

title: Voltage changes but digitalRead always HIGH

Answers: 2

body:
First of all - read your post before you actually post it. This code is no readable. And if you have problems with electronics add picture of schematics how you connected your board. There can be problem too.

> D3 IO, 10k Pull-up GPIO0

Source: https://www.wemos.cc/product/d1-mini-pro.html

Your D3 pin have internally pull-up so no doubt that it reads HIGH all the time. Connect your board like on picture below or change your reading pin to D0 for example (It has no other function than simple IO).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/yxbFX.png)

<!-- End schematic -->

For this case you can trust internal pull-up but in more complicated projects you should add your own one.

For more information about pull-ups and pull-downs check this article: http://www.electronics-tutorials.ws/logic/pull-up-resistor.html

body:
The problem is that when the button isn't pressed, the voltage at pin D3 is just floating. Since there is nothing attached, the voltage at the pin can be anything. To prevent this, you use a pull-down resistor, so that when the button isn't pressed, the voltage at D3 is pulled to ground, and you will get a LOW using digitalRead.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/0Ztn9.png)

<!-- End schematic -->


body:
I am fully new to Arduino (even don't have one ... yet), however, I'm looking into possibilities to use both MIDI in/out and DMX together. If I understand correctly the MIDI library (re)uses the UART/COM while the DMX does the same.

I am wondering if it can be used together (e.g. use MIDI in to control MIDI out and/or DMX out).

(Also still checking if I would need some simple MIDI/DMX components or 'full' MIDI or DMX shields/boards.)

title: MIDI and DMX together

Answers: 2

body:
Yes you can use multiple UART/Serial devices with a single Arduino.

However, there are some things to consider:

The Arduino Uno supports a single [hardware serial connection](https://www.arduino.cc/en/reference/serial) (which is used for programming and debugging with the Serial Monitor). The Arduino Mega supports 4 hardware serial connections.

The arduino environment has a software Serial library that allows for additional Serial connections. However it is worth noting that software serial is slower than its hardware counterpart.

Also, if you want to use software serial, be sure to verify that any shields you want to use will support using a software serial connection.

body:
The DmxSimple/DmxMaster library does not use serial and will work simultaneously with the MIDI library by 47 Effects.  I have used the Sparkfun MIDI shield with the Tinkerkit DMX shield.  The trick to stacking them is using tall headers on the MIDI shield and not soldering the XLR connectors on the DMX shield.

Or you can use a Teensy which has multiple hardware serials and more RAM at a good price but requires building a couple basic circuits.


body:
I am behind a problem of controling multiple leds with multiple push buttons. Lets say that I have 5 push buttons and 3 leds. Led1 turns on if at least 1 out of the 5 push buttons is pressed. Led2 turns on if at lest 3 push buttons are pressed and Led3 turns on if at least 4 push buttons are pressed.
How can this be solved ? With if else ?arrays?
here is my code that i have

     const int led1 = 2;
     const int led2 = 3;
     const int led3 = 4;
     const int bp1 = 9;
     const int bp2 = 8;
     const int bp3 = 7;
     const int bp4 = 6;
     const int bp5 = 5;
     int state;

    void setup()
     {
     Serial.begin(9600);
     pinMode(led1, OUTPUT);
     pinMode(led2, OUTPUT);
     pinMode(led3, OUTPUT);
     pinMode(bp1, INPUT);
     pinMode(bp2, INPUT);
     pinMode(bp3, INPUT);
     pinMode(bp4, INPUT);
     pinMode(bp5, INPUT);
    }

    void loop()
    {
     state = digitalRead(bp1);
     state = digitalRead(bp2);
     state = digitalRead(bp3);
     state = digitalRead(bp4);
     state = digitalRead(bp5);
    if (state = HIGH)
    { digitalWrite(led1, HIGH); }

    if (state = 3 )
    { digitalWrite(led2, HIGH);
    if (state >= 4);
    { digitalWrite(led3, HIGH); }
    }
    else { digitalWrite(led1, LOW); }
    }

title: Multiple push buttons

Answers: 4

body:
Your code won't work as is. Each time you assign a value to `state` you're overwriting it in the next line. You could, for example have multiple int state variables such as `state1` for the first line in the loop then `state2` in the second etc. Then you need to compare values (don't use `=` on its own in a compare as it will assign the value being tested - use `==` instead). This way you gather all the button states first.

Or you could test the state of a button and if pressed add 1 to `state`:

    if (digitalRead(bp1)) {
        state++};

Then you compare the number of button presses counted in state as you were doing and light the LEDs based on that.

However you will likely have a problem with contact bounce on the switches. This happens when a switch is closing and the voltage is not steady for about 20ms (imaging a switch sparking as it is closing). To get around this you'll need either some additional components or add a time delay in your code for each button press to check it several times until the voltage is stable. Do a Google search for 'Arduino contact bounce' for solutions.

R3.

body:
I would do this:

     state = (state & ~STATE_MASK1) | ((digitalRead(bp1)==HIGH)?STATE_MASK1:0); //assuming buttons are active high
    ...

    if (state & STATE_MASK1)
    { digitalWrite(led1, HIGH); }

it holds up to 8 button states for a uint8_t type.

edit: here is a quick implementation.

 //state = 0;           //reset the state

 //read the buttons - all active high
 state = (digitalRead(bp1)==HIGH)?STATE_BP1:0;
 state|= (digitalRead(bp2)==HIGH)?STATE_BP2:0;
 state|= (digitalRead(bp3)==HIGH)?STATE_BP3:0;
 state|= (digitalRead(bp4)==HIGH)?STATE_BP4:0;
 state|= (digitalRead(bp5)==HIGH)?STATE_BP5:0;

 //process the buttons
 digitalWrite(led1, (state & STATE_BP1)?HIGH:LOW); //active high - led1 is high if bp1 is high
 digitalWrite(led2, (state & (STATE_BP2 | STATE_BP4))?LOW:HIGH); //active low - led2 mimics bp2|bp4 => led2 high if both bp2+bp4 are low
 digitalWrite(led3, ((state & STATE_BP3) && (~state & STATE_BP5))?HIGH:LOW); //active high -> led3 is high if bp3 is high and bp5 low

the code controls 3 leds:

1. led1: it mimics bp1;

2. led2: it goes high if both bp2/bp4 are high;

3. led3: it goes high if bp3 is high and bp5 is low.

I picked the output logic for no particular reason.

here is the output:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/XcWGK.png

you can check the waveform against the logic, :)

again, this is just one particular implementation and you can write your own code / logic to produce your desired outcome. the principle is the same.

body:
To get the functionality you want the code should be:

    void loop()
    {
     state = 0;
     if (digitalRead(bp1) == HIGH)
       state = state + 1;
     if (digitalRead(bp2) == HIGH)
       state = state + 1;
     if (digitalRead(bp3) == HIGH)
       state = state + 1;
     if (digitalRead(bp4) == HIGH)
       state = state + 1;
     if (digitalRead(bp5) == HIGH)
       state = state + 1;

     if (state >= 1)
       digitalWrite(led1, HIGH);
     else
       digitalWrite(led1, LOW);

     if (state >= 3 )
       digitalWrite(led2, HIGH);
     else
       digitalWrite(led2, LOW);

     if (state >= 4) // you had a ; here.
       digitalWrite(led3, HIGH);
     else
       digitalWrite(led3, LOW);
    }

There are more shorthand ways to write this e.g.`if (digitalRead(bp4) == HIGH) state = state + 1;` could be replaced with `digitalRead(bp4)?state++;` but until you are familiar with programming it's often best to use the longer but clearer way of writing things.

If all you are doing is lighting LEDs then de-bouncing the buttons isn't necessary, any LED flicker caused by the contacts bouncing won't be visible to your eye.

If however at a later date you want to trigger other logic in your program to run once per button press then you will need to worry about that. All buttons and switches bounce a little when you close them, without something in the electronics or software to cope with that a single button press can look like a dozen very quick presses to your software.

body:
I solved my problem by myself with if..else structures. I am happy that I got this working and I learned something new. Thank you all for help and inputs.

    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int bp1 = 9;
    int bp2 = 8;
    int bp3 = 7;
    int bp4 = 6;
    int bp5 = 5;

    void setup()
     {
     Serial.begin(9600);
     pinMode(led1, OUTPUT);
     pinMode(led2, OUTPUT);
     pinMode(led3, OUTPUT);
     pinMode(bp1, INPUT);
     pinMode(bp2, INPUT);
     pinMode(bp3, INPUT);
     pinMode(bp4, INPUT);
     pinMode(bp5, INPUT);

    }

    void loop()

    {

    if (digitalRead(bp1)== HIGH or digitalRead(bp2)== HIGH or digitalRead(bp3)== HIGH or digitalRead(bp4)== HIGH or digitalRead(bp5)== HIGH )
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);
     }
    else
    {
      digitalWrite(led1, HIGH);
      digitalWrite(led2, HIGH);
      digitalWrite(led3, HIGH);

     }

    if (digitalRead(bp1)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH)
        {
        digitalWrite(led1, HIGH);
        digitalWrite(led2, LOW);
        digitalWrite(led3, HIGH);
        }
    else
      {
       digitalWrite(led1, HIGH);
       digitalWrite(led2, HIGH);
       digitalWrite(led3, HIGH);
       }

    if (digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp4)== HIGH and digitalRead(bp5)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp4)== HIGH or digitalRead(bp1)== HIGH and digitalRead(bp2)== HIGH and digitalRead(bp3)== HIGH and digitalRead(bp5)== HIGH)
       {digitalWrite(led1, HIGH);
        digitalWrite(led2, HIGH);
        digitalWrite(led3, LOW);
    }

    else
     {  digitalWrite(led1, HIGH);
       digitalWrite(led2, HIGH);
       digitalWrite(led3, HIGH);
       }

    }


body:
Everyone, I am new to this. Currently I am trying to make a Whack-a-mole game for my school project. There will be a total of 6 moles (corresponding to 6 LEDs, which will light up randomly). At each moment, there will only be one LED lit up. The whole game duration is 30 seconds. At the end of the game, the score will be displayed.

I use a piezo electric sensor to detect the knock of the user. I program it in such a way that if the reading of the piezo sensor is greater than 50, it will take it as knock, and if the user knocks it correctly, one point will be awarded.

But unfortunately my code isn't working. The score displayed appears to be random numbers, doesn't work as it is supposed to be.

Here is my code, please hep me to have a look and provide me with some guidance. Thank you.

    unsigned long time_since_reset;
    int previousNum=0;
    int currentNum =0;
    int randomGenerator (void);
    void light(int port);
    int checker(int port);
    int score =0;

    void setup() {
      pinMode(3, OUTPUT);
      pinMode(4, OUTPUT);
      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);
      pinMode(8, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      time_since_reset = millis();
      while((millis()-time_since_reset)<30000) {
        randomSeed(analogRead(0));
        currentNum = randomGenerator();
        light(currentNum);
        checker(currentNum);
      }
      Serial.println("End Game");
      Serial.println(score);
    }

    int randomGenerator(void) {
      int cNum;
      cNum = random(3, 8);
      if(cNum!= previousNum) {
        return cNum;
      }
    }

    void light(int port) {
      digitalWrite(port,HIGH);
      delay(1000);
    }

    int checker(int port) {
      jump:
      int mole1 = analogRead(0);
      int mole2 = analogRead(1);
      int mole3 = analogRead(2);
      int mole4 = analogRead(3);
      int mole5 = analogRead(4);
      int mole6 = analogRead(5);
      while(mole1<10 && mole2<10 && mole3<10 && mole4<10 &&mole5<10 &&mole6<10) {
        goto jump;
      }
      if(mole1>50 && port == 3) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole2>50 && port == 4) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole3>50 && port == 5) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole4>50 && port == 6) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole5>50 && port == 7) {
        score++;
        digitalWrite(port, LOW);
      }
      if(mole6>50 && port == 8) {
        score++;
        digitalWrite(port, LOW);
      }
    }

title: Arduino whack-a-mole game not working

Answers: 2

body:
The code as shown has a bunch of problems; the probably-most-important are as follows.

• `score` is not initialized.  Add `score = 0;` after
 `time_since_reset = millis();`

• As noted in a comment, the `delay(1000)` statement in `light()` prevents checking for whacks during the first second of a light being on.  This probably is undesirable – most people expect to whack a mole much sooner than a second after it appears.  If you want a delay there, make it at most 20 milliseconds. [See edit 2]

• The sequence `randomSeed(analogRead(0)); currentNum = randomGenerator();` has a good chance of generating the same value of `currentNum` several times in a row, which may result in multiple counts for a given whack.

• Instead of saying `randomSeed(analogRead(0));` within the inner loop, say it just after `time_since_reset = millis();` or (probably better) in `setup()`.  If `analogRead(0)` changes slowly, the same random seed may get used over and over, resulting in the same sequence of numbers from the `random(3,8)` expression.

• Your `randomGenerator()` routine has undefined behavior:  It doesn't return a valid result if the current random  number is the same as the previous one.  You could add a loop that calls `random()` again if the value is the same as before; but not returning a value results in  undefined behavior.

*Edit 2:*  When you turn a light on, record the current `millis()` time reading, say in `onTime[i]` for light `i`, and set flag `isOn[i]` true.  Later, when `isOn[i] && (millis()-onTime[i] > targetDelay[i])`, turn the light off and clear the flag (via `isOn[i] = false`).  Within `checker()`, a condition like `port == 6` translates to `isOn[6]`, an expression which is true when light 6 is on, else false.

The approach of using arrays like `onTime[]` and `isOn[]` and `targetDelay[]`, variable subscripts, and recorded on-times has several benefits:  It lets you loop through lights, getting rid of that needlessly repetitious code in `checker()`; it enables other processing in the main game loop (such as whack-testing) to proceed independently of light control; it allows multiple moles to pop up at the same time; and it allows different moles to have different or varying up times.

body:
Others have already mentioned the issues with the timing, score initialization and random number generation.

On your checker function you have 2 errors and one ugly piece of code.

Ugly code first - goto is BAD. About the only time it's acceptable is under an error condition, the rest of the time if you find yourself needing to use a goto then look at how you can improve the code structure.

Errors - You exist after an analog input is > 10 but only count >50 as a hit. As they hit it the value will ramp up so they hit a target you could see a value of 10, exit your loop and not score anything. You need to use the same threshold for both. (Another style point, if you have the same magic number in two places (e.g. 10 or 50) consider making them constants or #defines rather than hard coded numbers. It makes it a lot easier to change them without forgetting one of the locations).

The second error is that you only turn the LED off if they hit the correct target, if they get the wrong one you light the next target but never turn the first LED off.

The code below should solve all of these issues.

    int checker(int port){

      char exit = 0;
      int mole;
      while (!exit) {                // until we get a hit
        for (int i = 0; i<5; i++) {  // check each mole in turn
          mole = analogRead(i);      // read the sensor
          if (mole < 50) {           // if over the threshold
            exit = 1;                // exit the while loop after this check
            if (i + 3 == port)       // see if they got the correct target. i goes 0-5, port goes 3-8
              score++;
            digitalWrite(port,LOW);  // turn the LED off
            break;                   // break out of the for loop
          }                          // end if hit
        }                            // end for loop
      }                              // end while loop
    }


body:
For the last couple of day I've been trying and failed many times just to not use the delay() funtion in Arduino. I have to admitted that my coding skill are extremely bad.

What i trying to do is:
If button is pressed:
Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop.
else:
Motor A and B both stop.

I managed to wrote the code by using delay function for that 1 second. However i got no idea how to do it WITHOUT DELAY() there will be sensor reading as well at the same time, i cant afford that 1 second delay of sensor reading).

Here is my code:

    int dir1PinA = 2;
    int dir2PinA = 3;
    int speedPinA = 9; // Needs to be a PWM pin to be able to control motor speed

    // Motor 2
    int dir1PinB = 4;
    int dir2PinB = 5;
    int speedPinB = 10; // Needs to be a PWM pin to be able to control motor speed

    int button = 6;

    void setup() {  // Setup runs once per reset
    // initialize serial communication @ 9600 baud:
    Serial.begin(9600);

    //Define L298N Dual H-Bridge Motor Controller Pins

    pinMode(dir1PinA,OUTPUT);
    pinMode(dir2PinA,OUTPUT);
    pinMode(speedPinA,OUTPUT);
    pinMode(dir1PinB,OUTPUT);
    pinMode(dir2PinB,OUTPUT);
    pinMode(speedPinB,OUTPUT);

    // Define button pin
    pinMode(button,INPUT);

    }

    void loop() {
      if( button == LOW){           // if button is pressed
        // Motor A (move slow) and B  moving
        analogWrite(speedPinA, 100);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, HIGH);
        analogWrite(speedPinB, 255);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, HIGH);
        delay(1000);

        // After 1 second Motr A (move fast)and B stop every time button pressed
        analogWrite(speedPinA, 255);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, HIGH);
        analogWrite(speedPinB, 0);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, LOW);
      }
      else
      {
        // Both motor not moving
        analogWrite(speedPinA, 0);//Sets speed variable via PWM
        digitalWrite(dir1PinA, LOW);
        digitalWrite(dir2PinA, LOW);
        analogWrite(speedPinB, 0);
        digitalWrite(dir1PinB, LOW);
        digitalWrite(dir2PinB, LOW);
      }
    }

Please point me out the direction or give me an example of code. And I have already try the Blinkwithoutdelay Arduino example but it does not work for this case.

Very much appreciated.

title: Control time without delay() Arduino

Answers: 3

body:
Assuming the button isn't held down for 50 days straight, you can use the [millis()][1] function and basically set a marker of the current time when the user pushes the button down. To do this, you need to detect when the user switches from off to on, not when while the button is pushed or you'll be resetting the marker every time.

Then you record the time every loop while the button is pushed down. If the current time is more than one second after the time recorded by the marker, you switch motor B off and make motor A as fast speed like you said. When the button is off, like you said set both motors to off.

  [1]: https://www.arduino.cc/en/reference/millis

body:
You might want to use a timer. There are some libraries available for Arduino that precisely do that.

You can either use a library that implements a software timer (something similar to comparing `millis()`, but with powerful additional built-in features such as button debouncing, timed pulses, etc.) or use a library that deals with the hardware interrupts of the MCU.

As an example take a look at this particular library: [Timer][1]. I think you'll love it!

  [1]: http://playground.arduino.cc/Code/Timer

body:
>  If button is pressed: Motor A and B move for 1 second at slow speed == > Motor A keep moving but at fast speed and motor B stop. else: Motor A and B both stop.

I would do a quick state machine:

>    STATE / button released: do nothing;
    STATE / button pressed: run motors a+b;
    STATE / run motor a+b: run motor a+b; if 1 second has passed, advance to just run motor a;
    STATE / run motor a: run motor a at fast speed and stop motor b.

fairly easy to code as well.


body: I have an Arduino Pro micro and I need to know if it is possible to use an USB device like a camera or things like that Since the processor is a 32U4. the USB Shield is for the Arduino Uno and I don't want to buy more stuff.

title: USB DEVICES WITH THE 32U4?

Answers: 1

body:
Some important facts:

* The 32U4 cannot act as a USB master, only a USB device (it doesn't have a USB OTG interface).
* The USB shield is an SPI based device. It can communicate with any host MCU that can use SPI, as long as you can wire it in properly.
* The Arduino doesn't have the processing power or memory to deal with the sheer onslaught of data a USB camera sends.

So yes, you could use the USB shield with a 32U4 based board if you can work out the right wiring. However you will not be able to use things like cameras with it since you lack the processing power to do it.

For camera work you need something more like a Raspberry Pi.


body:
I am using a Fona 808 shield with an Arduino Uno and the LSM303 accelerometer. The accelerometer is connected via I2C and the Fona uses software serial.

My project requires the accelerometer to be continuously polled and occasionally talk with the fona. I wrote a program that just used the fona, but once I added the accelerometer code the program would hang a few seconds after comms had been opened with the Fona. I have tested both the accelerometer and the fona shield separately, and they work fine. So, I wrote another smaller (test) program (which is attached below) to find the origin of the program, which I identified to be:

    fonaSerial->begin(4800);

    fona.begin(*fonaSerial);

After these lines of code are added, the problem arises. As I said before, this is what I see a few seconds after comms have been opened with the Fona.
http://pasteboard.co/A16708fo3.png

My test program reads the value from the accelerometer, calculates the magnitude of the acceleration and if it's over 20, it prints "Over 20", while also initialising Fona serial.

My question is: Why don't the accelerometer (I2C) and the Fona (Serial) work together and how this be fixed?

This is quite urgent so a quick responses are greatly appreciated!

My Code:

    #include <Adafruit_FONA.h>
    #include <Adafruit_Sensor.h>
    #include <My2_Adafruit_LSM303_U.h>
    #include <Wire.h>

    #define FONA_RX 2
    #define FONA_TX 3
    #define FONA_RST 4

    #include <SoftwareSerial.h>
    SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
    SoftwareSerial *fonaSerial = &fonaSS;

    Adafruit_FONA fona = Adafruit_FONA(FONA_RST);

    volatile byte accelMagnitude;

    Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);

    void setup() {
      // put your setup code here, to run once:

        accel.begin();

        Serial.begin(115200);

        fonaSerial->begin(4800);
        fona.begin(*fonaSerial);

    }

    void ReadAccel(){

    //Get a new accelerometer sensor event
      sensors_event_t event;
     // Serial.println(F("Accel---------"));
      accel.getEvent(&event);

      accelMagnitude = sqrt( sq(event.acceleration.x) + sq(event.acceleration.y) + sq(event.acceleration.z));

    }

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

        ReadAccel();

        if (accelMagnitude > 20){

            while (accelMagnitude > 20){

                Serial.println("waiting");
                ReadAccel();
            }

            Serial.println("Over 20");

        }
    }

title: Accelerometer (I2C) and Fona Shield (software serial) won't work together

Answers: 1

body:
As Gerben suggests, it would not be a good practice to just add a delay and call it a day.

1) Have a large electrolytic capacitor between Vcc and GND as near as you can to the FONA and

2) FONA has `getNetworkStatus();` make a small control loop and query it until you get status 1 or 5, depending on what network are you on.
From FONA's example:

    if (n == 0) Serial.println(F("Not registered"));
    if (n == 1) Serial.println(F("Registered (home)"));
    if (n == 2) Serial.println(F("Not registered (searching)"));
    if (n == 3) Serial.println(F("Denied"));
    if (n == 4) Serial.println(F("Unknown"));
    if (n == 5) Serial.println(F("Registered roaming"));

And then proceed with the rest of your code. You can make additional checks for signal quality with `getRSSI();`


body:
How much time takes to print each sample using `Serial.print` and `analogRead` in each iteration?

    #include <SoftwareSerial.h>
    #define Sensor A0
    void setup() {
      Serial.begin(250000);
      pinMode(Sensor,INPUT);
        }
    void loop() {
      Serial.println(analogRead(Sensor));// RUN TIME??
    }

title: Serialprint and analogRead time

Answers: 2

body:
It is quite complex to work out how "long" it will take to print.  Why?

1. If there is room in the serial buffer then the text just gets placed in that buffer. Takes almost no time at all to print.
2. You are printing a variable length string. The longer the string the longer it will take to print if the buffer is full.

However:

* Each character consists of 10 *symbols* (8 data bits plus 1 start and 1 stop bit).
* Characters are transmitted at 250000 symbols per second
* Thus each character takes 1/(250000 / 10), or 40 microseconds to transfer through the actual wire.

So printing the number 100, which also has `\r\n` appended to it (characters 13 and 10) would need 5 characters. If the buffer is full it will take about 5*0.00004s = 200µs. If the buffer isn't full, it will take a fraction of that to just copy the data into the serial buffer.

body:
1000 rounds of analogRead() takes about 100ms.

sustained serial writes will depend mostly on the baud rate picked.


body:
There is small board with gyroscope. Controller - Atmega 8a, com-usb chip is CH340G. Board is handmade but not by me so I don't sure is it Arduino clone or not. It works with "ch341ser" driver on the computer and is used in small video game writed on java. This game is ran by .bat file where I specify COM port number, game listen this port in code.

I need to do anything to make computer understand gyro tilt as arrow keyboard buttons commands. In other words I need to write a driver or smth else to make computer understand device as USB HID keyboard. Is it possible to do it programmatically and how to do that?

title: Make device based on CH340G working as keyboard

Answers: 1

body:
No, it's not possible. The device enumerates as a USB serial device, and the only way to change that is to change the internal silicon of the device.

The closest you could do is (though I have no clue how on Windows) write (or if you are lucky, find) a program that reads serial data through the COM port and somehow injects keyboard commands into the input subsystem of the operating system.


body:
I am 6 months into my Arduino Uno work and I would like a step by step way to find and download a "library". I work using WINDOWS and WORD and although I was eventually successful in getting a 7 segment display library to download and work, I must say I could not do it again since the path I followed was far from clear due to my lack of understanding about basic computer stores etc. I have enjoyed my work with the Uno but I have been very disappointed at lots of "help" offered on other sites since they assume I know far too much. It is a skill to be able to communicate with we lesser people so I am really hoping a step by step guide is possible.
Thanks

title: Finding and loading "libraries"

Answers: 1

body:
Start with the newest Arduino IDE. At this moment that is version 1.8.1.

Try to find the Library Manager. Via the menu: Sketch / Library...

In the Library Manager there is a input field in the upper-right corner where you can search for libraries.

If you can not find the library, then the next step is to download a zip file from Github. There is probably a green button "Clone or Download" on the right side with that project on Github. Use it to download that library and store it. Do not unzip it. In the Arduino IDE in the menu via: Sketch / Library... there is a option to install a .ZIP file. Use that to install the library from Github.

Your projects are probably at: Documents / Arduino

There is also a folder: Documents / Arduino / libraries

That is where the installed libraries will end up. That means you can also add libraries to that folder. Each library in its own sub-folder.


body:
[![enter image description here][1]][1]I am new to arduino and robotic stuffs and I thought it would be a good idea to test circuits on my breadboard using arduino's R3 5V pin as power supply. The accident happened when I short circuited the things on the breadboard and after a while arduino gave off a nasty smell. The only part overheated on arduino was the left side of the micro-controller. After that I cant upload nor run code on arduino.

After I explained you my situation, can you imagine a potential problem?(e.g I mean is it a voltage regultor problem, a micro-controller faillure, both of them, or something else?)

Can I fix it?

(#1 - I know arduino boards are cheap. I just want to know if I can do anything        with that.

 #2 - No comments about  the accident accepted.)

Thank's in advance.

Regarding the image, my vendor claims the arduino to be an exact copy of "open-source" arduino R3

  [1]: https://i.stack.imgur.com/FcxmE.png

title: Is there any chance of fixing it?

Answers: 2

body:
> Can I fix it?

If your power supply still works, there's a decent chance you can repair the board by replacing its microcontroller which is conveniently socketed.

body:
> Can I fix it?

it depends on your skills and the nature of the problem and how far you are willing to go to fix it.

I would first try to rule out a supply problem - very rarely a mcu will burn to the extent of giving off smells / overheat. So unplug the mcu and use a multimeter to measure its Vcc vs. GND pin voltage, test trace continuity, etc.

after that, plug in a new / known good chip and see if you could upload code to it.


body:
I made a setup which consists of 3 Zigbee's, 2 routers(Zigbee S2C's) and 1 coordinator(Zigbee S2). The routers are each connected to arduino nano which collects data from 2 FSR's and an IMU(frame type: zigbee transmit request and packet size 46 bytes) and sends it to the Coordinator attached to an arduino UNO. All the Xbees are in API mode 2 and working at a baud rate of 115200. I am using a library called "Simple Zigbee Library" to send all the collected data to the Coordinator. The collection and sending of data works fine except that there are packets lost in the way. The nano's sample data at a frequency of around 25Hz independently. The coordinator tries to read the data send from the zigbees(using the library of course) in every loop, but unfortunately, it seems to receive only around 40-45 samples.(Should have been 25*2=50 samples total from the 2 xbees). Can anybody suggest why this is happening. I need as less data loss as possible for my setup to achieve its motive. Any kind of help is appreciated.

P.S: It may be important to mention that the coordinator is reading the data only from one xbee in each loop.

[[[As can be seen from the "Source" heading in this image of data received by the coordinator, "19" and "106" are addresses of the routers. Data drop is intermittent]][1]][1]

  [1]: https://i.stack.imgur.com/8Sw9V.png

        void setup()
    {
 // Start the serial ports ...
 Serial.begin( 9600 );
 while( !Serial ){;}  // Wait for serial port (for Leonardo only).
 xbeeSerial.begin( 9600 );
 // ... and set the serial port for the XBee radio.
 xbee.setSerial( xbeeSerial );
 // Set a non-zero frame id to receive Status packets.
 xbee.setAcknowledgement(true);
    }

    void loop()
    {
 // Each SimpleZigBeeRadio instance contains two
 // SimpleZigBeePacket instances, one for storing incoming
 // messages and one for preparing outgoing messages.
 // This example will not send any messages to the network.
 // Rather, the coordinator will receive messages and display
 // the contents to the hardware serial port.

 // While data is waiting in the XBee serial port ...
 while( xbee.available() )
 {
 // ... read the data.
 xbee.read();
 // If a complete message is available, display the contents
 if( xbee.isComplete() ){
 Serial.print("\nIncoming Message: ");
 printPacket( xbee.getIncomingPacketObject() );

 }
 }

 delay(10); // Small delay for stability
 // That's it! The coordinator is ready to go.
    }

     // Function for printing the complete contents of a packet //

    void printPacket(SimpleZigBeePacket & p)
    {
 Serial.print( START, HEX );
 Serial.print(' ');
 Serial.print( p.getLengthMSB(), HEX );
 Serial.print(' ');
 Serial.print( p.getLengthLSB(), HEX );
 Serial.print(' ');
 // Frame Type and Frame ID are stored in Frame Data
 uint8_t checksum = 0;
 for( int i=0; i<p.getFrameLength(); i++){
 Serial.print( p.getFrameData(i), HEX );
 Serial.print(' ');
 checksum += p.getFrameData(i);
 }
 // Calculate checksum based on summation of frame bytes
 checksum = 0xff - checksum;
 Serial.print(checksum, HEX );
 Serial.println();
    }

title: Xbee S2 API Data Packets dropping out

Answers: 0


body:
I am trying to talk to an [LT1257][1] using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.
[![LT1257 timing diagram][2]][2]

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).

    #include<SPI.h>
    #define SCLK 13
    #define MISO 12
    #define MOSI 11
    #define DAC_LOAD 5

    #define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

    void setup()
    {
    Serial.begin(9600);
    init();
    SPI.begin();
    dac_write();
    }

    void init()
    {
    pinMode(SCLK, OUTPUT);
    pinMode(MOSI, OUTPUT);
    pinMode(MISO, INPUT);
    pinMode(DAC_LOAD, OUTPUT);
    digitalWrite(SCLK, HIGH);
    digitalWrite(MOSI, HIGH);
    digitalWrite(DAC_LOAD, HIGH);
    }

    void dac_write()
    {
    SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
    delay(10);
    SPI.transfer(0x0000);
    delay(10);
    digitalWrite(DAC_LOAD, LOW);
    delay(10);
    digitalWrite(DAC_LOAD, HIGH);
    delay(10);
    SPI.endTransaction();
    }

    void loop()
    {
    while(1)
    {
    Serial.println("Ping!");
    delay(1000);
    }
    }

  [1]: http://cds.linear.com/docs/en/datasheet/1257fc.pdf
  [2]: https://i.stack.imgur.com/UWC9q.png

title: Arduino based SPI programming of LT1257 not working

Answers: 2

body: For a master to select an SPI slave to transmit data to it [the slave], the Slave Select pin is held low.

body: I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.


body:
I have some code that relies on the input capture timer value.

I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

If you want code or more detail ask in comments and I will post code.

title: Input Capture Pin Atmel ATmega328P

Answers: 2

body:
> I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

yes, unless your code writes to the registers involved.

body:
The way IC typically works is completely independent from the CPU and what instructions you are running.

The timer runs freely between the start and end input capture events. At the moment of capture the timer value is frozen into another register. The interrupt is then triggered. You then read that frozen value. It doesn't matter how long after the end event the interrupt executes, or what you do in that interrupt, the captured time is still the same.


body:
I am trying to plot my counter vs. time on the serial plotter, but the values on the y axis are so big there is no way that it's displaying the counter values.
I have printed both values:

      Serial.print("counter: ");
      Serial.println(counter);
      time = millis();
      Serial.print("Time: ");
      Serial.println(time);

I expected time to show up in the x-axis, but I think it's displaying on the y-axis and I'm not sure how to change this.
The plot should just be an increasing line as the counter and time get bigger...
what am I missing?
Thanks.

Slashing out the Serial.print("Time:") does not correct anything.

title: X and Y axis on Arduino Serial Plotter?

Answers: 4

body: Comment out the `Serial.print("Time: ");` line. The Arduino serial plotter wants only numbers.

body:
To plot multiple values over time you need to output just the numbers on a single line per iteration, and delimit with a space or tab:

    Serial.print(counter);
    Serial.print("\t"); // delimit with tab
    time = millis();
    Serial.print(time);
    Serial.println();

It's worth noting however, the time (x axis) is implied by each line. In essence each line of output advances "time" by 1 unit. So I suspect you'll want to remove the time variable output and just output the count variable by it self.

body:
Inorder to plot multiple variables or waveforms simultaneously a 'space' is printed between the two print statements.

    Serial.print(counter);
    Serial.print(" ");
    time = millis();
    Serial.println(time);

OR

    Serial.print(counter);
    Serial.print("\t");
    time = millis();
    Serial.println(time);

body: The X-axis is fixed and nothing gets plotted on the X-axis. It has its own divisions and they are automatically set by the Arduino IDE. The Arduino IDE still has to do some improvements to its software so that the X- axis can be adjusted and plotted too! This is my experience so far and corrections are welcome!


body:
[![enter image description here][1]][1]
I'm making an RC car with the Arduino Nano. I'm using RF433 as  wireless communication with 2 motors and L293D as the motor driver. I use 4 1.5V batteries to power the Arduin and another 6V battery pack to power the motors, and a joystick with an Arduino Mega to send commands through the RF433 to the Arduino Nano.

I've written a program that sends specific digits when the joystick is in a certain position, i.e. when the joystick is "bent" to the front it sends a "1", a "2" is sent when the joystick is bent towards the back, and so on.

**My problem is this:**

When I bend the joystick towards a certain direction, the RC car moves accordingly without problem; However, when I bend the joystick towards another direction the RC car doesn't respond.

I took a look at what the RC car was receiving, and I've noticed that after the first command was sent (when I bend the joystick towards a certain direction), no more commands get to the RC car (in other words the Arduino Nano), and this occurs occasionally. I think this means the Arduino Nano "froze" after the first command.

  [1]: https://i.stack.imgur.com/8RwqP.jpg

title: Brownout with Arduino Nano

Answers: 1

body:
You have *at least* three problems here:

1) First and most critically, a nominal 6v pack does not meet the input voltage requirements of the regulator used an Arduino *even before* it gets loaded down by a motor, and it only gets worse under load

2) L293/L297 and similar **bipolar** bridges have absurdly high internal losses, so are unsuited to low voltage systems - effectively one of your cells goes just to feeding the wasteful driver chip.  Use a modern and efficient FET driver like a TB6612FNG, or else add another cell to the pack.

3) The 433 MHz RF modules are notoriously low fidelity, and in many places not permitted for the control of RC models anyway.  You'll have much better results with the sophisticated digital radio modules sold at comparable prices for 2.4 GHz, which are incidentally the functional equivelent of what most RC toys now use (and actually in many cases can be made interoperable with them).

Granted, you may well have other issues as well, such as errors in your software.


body:
I have the following code in loop() to collect values from an electret microphone

    for(int i=0; i<sampleSize; i++){
      analogVal[i]= analogRead(ADC_Pin);
      sumOfSquares= sumOfSquares+sq(analogVal[i]);
    }
    Serial.print("Sum of squares: ");
    Serial.print(sumOfSquares);

where sampleSize is an int variable, I've tried numbers from 3 to 1000, which is my desired value. ADC_Pin is an int variable set to be A1 and has been properly initialized through pinMode. analogVal is an int array of size sampleSize.

My circuit appears to be fine because the output produces a reasonable amount of voltage. I've tried eliminating the line with sumOfSquares and just having the first line in the for loop. However, the Serial Monitor hangs and does not display any values. The serial communication is at 9600 bps.

title: Why does my code or Serial Monitor hang with analogRead?

Answers: 1

body:
Arduino UNO have 2K RAM (many other too). That is 2048 bytes of RAM.

I suppose, that `analogVals[]` is declared as `int` and having 1000 entries it takes 2000 bytes of RAM, leaving wholesome `48 bytes` for all your others variables (including `int i` in the for cycle and `Serial` outside it) and stack for calling functions (like `analogRead` and `sq`) and all theirs variables and functions and arguments.

So `int i` = 2B, `Serial` = 2B, `sumOfSquares` = 2B, `"Sum of squares: "` = 17B of what I see takes anothe `23 bytes` of those `48 bytes` leaving us with only **25 bytes** for all else.

I bet, that you try to use more REAM, than you have and so your `stack overflows` and

 1. destroys some variable content on the vay

 2. is overwriten by assigning to some variables, which then leads to all sort of problems.


body:
I currently have a 50,000 mAH USB power bank powering my Arduino Uno and micro servomotor. Unfortunately, my power bank has an automatic shutoff and shuts off after 2 hrs of runtime (I need 16 hrs for my project). I can restart the power bank by hitting the on button and it will run just fine for another 1-2 hrs at which point it will shut off. In one instance, the power bank ran for the desired 16 hrs straight hours. I believe that my arduino/servo are very close to the current threshold of the bank which could explain some of the variability I am seeing in terms of turn-off time. Would hooking up a resistor in the circuit do the trick and if so where?

Not quite sure about the brand of power bank (just one I found off Ebay). I believe the arduino uno and servo consume about 60 mA for power.

title: Power bank turns off spontaneously

Answers: 4

body:
I can't see this helping.

It could only help if your power bank switched off its output when the current  drawn dropped too low - but unless your  circuit's current consumption drops after two hours, which you don't mention, that is unlikely to be the reason it's switching off.

body:
You have a couple of options, depending on how much you want to dive into electronics.

 - Find/buy a new powerbank that does not auto-shutoff
 - Find the current-sense resistor on the internal circuitry of your existing powerbank and change it out so that the device always thinks there is current flowing, or is more sensitive to your low-draw attachment. I was able to find a few websites describing this for specific powerbanks by searching.
 - Add a dummy load in parallel with your circuit, which wastes power, but does trick the powerbank into staying on.

It's also worth noting on the side, that you very likely do not have 50,000 mAh capacity in this powerbank, as others have noted. However, you ought to be able to get 16h of runtime with even a lower-rated powerbank if your claim of 60mA current draw is true.

body: Expanding @jose can u c first suggestion I did a little research and found that Voltaic Systems sells power banks with an option to disable auto-shutoff mode. There may be others. I found two of their power banks offered on Amazon. The blurb in the Amazon listing explicitly mentions using it with Arduino and Raspberry Pi.

body: As the company Voltaic has been mentioned I feel that it would be helpful if I warned you of that company. We are after all trying to offer solutions and if you follow the advice of the person who suggested Voltaic then I know from first hand experience that the thing turns itself off even when the auto shutdown mode is disabled. Though this may not be an end solution I know that by helping you to avoid useless information I can keep you on track and help you towards your solution. In detail : I'm a chauffeur and I bought a Voltaic for this specific reason and guess what? It switches off even when auto shutoff mode is disabled. I wanted my customers to be able to charge their devices as quick as poss and with as little complication as poss. I'm thinkin bout puttin a led fibre optic charging cable in so there is always a tiny power usage from the LED near the big USB jack. At least then also the cable wld be more 'look at me, look at me' I'm thinkin the problem comes either from an auto time out or from the completion of the charging of the power bank which is itself on a dribble charge from the car's electrics.


body: I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do). So I am in need of an Analog-to-Digital Converter(ADC) which has a very high sampling rate (sampling rate has to be constant and known), can be interfaced with Arduino Mega or Raspberry Pi and noise should be neligible to minimum level of voltage magnitude that it can count. Can anyone suggests me with any ADC that follows these characteristics?

title: ADC with better performance

Answers: 2

body:
> I need to sample voltage at a very high rate (say for like 10000 Hz) and with a very good precision(at least 10-12 bit ADC will do).

10Ksps and 12bit-resolution adcs are fairly common for onboard ADC. you should be able to find lots of mcus that have adc modules that can do that.

even for an external adc, that's not difficult at all. because of the speed, you are likely looking at a spi adc module.

precision is another matter.

body:
[ADS7835][1] from Texas Instrument.

> can be interfaced with Arduino Mega or Raspberry Pi

It is interfaced through SPI, 12 bit data, and up to 500kHz throughput rate.

  [1]: http://www.ti.com/lit/ds/symlink/ads7835.pdf


body:
I have bought SIM808 module, everything working fine. All AT commands are giving expected response, i'm accessing it through hyperterminal. My problem is that whenever i make or receive a call or SMS , GSM gets restarting.(I can able to make/receive call, getting ring/alert for small period of time and then interrupt). But there is no Under or Lower voltage power down or warning.
I have tried with DC power supply of 5V/500mA , 5V/1A and 5V/2A.  What might be the reason ? Please help.
extra info : It has one LM2576S voltage regulator in-built.

title: SIM808 module restarting repeatedly

Answers: 2

body:
Check the datasheet and I think you will find you need 3 amps peak.  It requires this peak current when you make a call or send a text/sms.

Use a 5A power supply and that should solve the problem.

I have never tried it but "super capacitors" *might* work, providing the extra power when its needed, it depends how long you need the 3A for.

body:
I too faced the same problem and solved it.

Just use a 3.3V logic converter or a 3.3V interface, as the 5V causes the device to restart.


body:
Can anyone give me the full code of my project because my code is not working?

My aim is that when the Z axis of an accelerometer is below 370 and a pushbutton connected to a pin 2 becomes high, then pin 13 turns high and remains high.  When the Z axis is above 370 and pushbutton is high then the pin 13 goes low and remains low.

P.S I am also a noob to Arduino

Here is my code :

    const int ledPin = 13;
    const int threshold = 370;
    const int pull_up_resistor = 12;
    const int pull_down_resistor = 11;
    const int groundpin = A1;
    const int powerpin = A5;
    const int xpin = A2;
    const int ypin = A3;
    const int zpin = A4;

    int pushButton = 2;

    void setup() {

      pinMode(ledPin, OUTPUT);

      Serial.begin(9600);

      Serial.begin(9600);

      pinMode(pushButton, INPUT);
      digitalWrite(pushButton, HIGH);
      Serial.begin(9600);

      pinMode(groundpin, OUTPUT);
      pinMode(powerpin, OUTPUT);
      digitalWrite(groundpin, LOW);
      digitalWrite(powerpin, HIGH);
    }

    void loop() {

      int buttonState = digitalRead(pushButton);

      Serial.println(buttonState);
      delay(100);        // delay in between reads for stability

      Serial.print(analogRead(xpin));

      Serial.print("\t");
      delay(100);
      Serial.print(analogRead(ypin));

      Serial.print("\t");
      delay(100);
      Serial.print(analogRead(zpin));
      Serial.println();

      delay(100);

      if (buttonState = 0) {
        digitalWrite( ledPin, HIGH);
      }
      if (buttonState = 1) {
        digitalWrite (pushButton, LOW);
      }

    }

title: Need help with my project

Answers: 1

body:
Use some formatter before posting it here. For example here is great one, written by [KrzaQ] edit: didn't noticed that was fixed by Mark

Next thing to do is keep your code clean. Three times you initialized Serial communcation. Why?
You should also first initalize Serial then set pinModes into state and then put digitalWrite. It helps reading the code.

**Example:**

    Serial.begin(value);
    pinMode(x,x);
    pinMode(y,x);
    pinMode(z,x);
    digitalWrite(x,x);
    digitalWrite(y,x);
    digitalWrite(z,x);

More readable, isn't it?

Next step: Pull-up and pull-down resistors... It is not thing you need to set in your code. It is hardware connection of 1 resistor, sometimes capacitor and device. There is no use for it in your device.
Read about them here: [Pull-up/pull-down]

Next thing: You **must not** define your outputs as power pins and treat them like one. AVR's have limited power output from each pin and by doing so you can fry it very quickly.

If I understand your sentence correctly you need to save your angle values into variable like this (pseudo code, you have to adjust it to your case no one will write it for free):

    int xvalue, yvalue, zvalue, button;
    void setup(); // all setup should go here do not skip this like me here
    void loop() {
      xvalue = analogRead(xpin);
      yvalue = analogRead(ypin);
      zvalue = analogRead(zpin);
      if (button == 1) {
        if (zvalue > 370)
          digitalWrite(ledPin, HIGH);
        else
          digitalWrite(ledPin, LOW);
      } else
        actionWhenPushButtonIsZero();
    }

If you think about what I wrote and focus on your task I am sure that everything will work in your device. THINK first then ask next questions.

[KrzaQ]: http://format.krzaq.cc/
[Pull-up/pull-down]: http://www.resistorguide.com/pull-up-resistor_pull-down-resistor/


body:
I'd like to know if there are events worldwide or in Latin America regarding how to introduce Arduino as an extra-curricular activity.
Thanks, Marcelo from Argentina.

title: Worldwide "Arduino in education" events

Answers: 0


body:
I am currently undertaking a project where I am attempting to build a bluetooth thermometer using an arduino.
I have the temperature sensor working and returning temperature readings via a usb connection to the serial monitor in the Arduino IDE using the following code.

<!-- language-all: lang-cpp -->

    #include <OneWire.h>
    #include <DallasTemperature.h>
    #include "Timer.h"

    Timer t;

    // Data wire is plugged into pin 10 on the Arduino
    #define ONE_WIRE_BUS 10

    // Setup a oneWire instance to communicate with any OneWire devices
    OneWire oneWire(ONE_WIRE_BUS);

    DallasTemperature sensors(&oneWire);

    DeviceAddress insideThermometer = { 0x28, 0x94, 0xE2, 0xDF, 0x02, 0x00, 0x00, 0xFE };

    void setup(void)
    {
      // start serial port
      Serial.begin(9600);
      // Start up the library
      sensors.begin();
      // set the resolution to 10 bit (good enough?)
      sensors.setResolution(insideThermometer, 10);
      int tickEvent = t.every(3000,doTempReading);

    }

    void loop()
    {
        t.update();
    }

    void printTemperature(DeviceAddress deviceAddress)
    {
      float tempC = sensors.getTempC(deviceAddress);
      if (tempC == -127.00) {
        Serial.print("Error getting temperature");
      } else {
        Serial.print("C: ");
        Serial.print(tempC);
      }
    }

    void doTempReading()
    {
      delay(2000);
      Serial.print("Getting temperatures...\n\r");
      sensors.requestTemperatures();

      Serial.print("Inside temperature is: ");
      printTemperature(insideThermometer);
      Serial.print("\n\r");
    }

I now want to try and transmit the readings via a bluetooth connection using the HC 05 module to a raspberry pi which will record the data.

I have done a lot of research and tried several different techniques and can't understand how to go about it.

What mode does the HC 05 need to be in? (Command AT/slave/data/etc.)
How should it be wired (I have found several different methods using various resistors and capacitors and unsure which to follow).
How should I pair it with the Raspberry pi?

Thanks in advance for any help.

title: How can I connect an arduino to a raspberry pi via an HC 05 bluetooth module and transmit data?

Answers: 1

body:
I know this is old but to help out newcomers:

Here's a place you can begin https://create.arduino.cc/projecthub/millerman4487/view-serial-monitor-over-bluetooth-fbb0e5

The wiring depends on which arduino board you are using and the model of your HC-05 BT module. mine uses 4 pins VCC (5v) GND (ground) TX --> TX and RX --> RX

You should be able to google the wiring for your module, and connect to the raspberry pi after you install bluetooth on raspberry pi

    sudo apt-get install bluetooth bluez blueman

    sudo reboot

Navigate to new bluetooth interface in menu bar through

 - preferences
 - bluetooth

Add new device, turn arduino on with BT module plugged in and make sure your HC-05 module is blinking red, and you should see a pair connection named HC-05 on raspberry pi. Password is 1234


body:
`I have an Arduino Uno A000066 Board R3 that has an Arduino A000079 Motor Shield Rev3 attached to it. Also I have connected two DC Servo Motors to the Motor Shield and wrote the following sequence:

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

          //Setup Channel B
          pinMode(13, OUTPUT);     //Initiates Motor Channel A pin
          pinMode(8, OUTPUT);      //Initiates Brake Channel A pin
        }

        void loop()
        {
          //Phase 1 - going to the wall
          //Motor A forward - Max Speed
          digitalWrite(12, LOW);   //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 max speed

          //Motor B forward - Max Speed
          digitalWrite(13, HIGH);  //Establishes forward direction of Channel B
          digitalWrite(8, LOW);    //Disengage the Brake for Channel B
          analogWrite(11, 255);    //Spins the motor on Channel B at max speed

          delay(4000); // Adjust to correspond the distance

      //Phase 2 - getting back to initial point
      //Motor A backward - max speed
      digitalWrite(12, HIGH);  //Establishes backward direction of Channel A
      digitalWrite(9, LOW);    //Disengage the Brake for Channel A
      analogWrite(3, 255);     //Spins the motor on Channel A at max speed

      //Motor B backward - max speed
      digitalWrite(13, LOW);   //Establishes backward direction of Channel B
      digitalWrite(8, LOW);    //Disengage the Brake for Channel B
      analogWrite(11, 255);    //Spins the motor on Channel B at max speed

      delay(4000);

      //Phase 3 Stop for 7.5 seconds
      // Motor A stop
      digitalWrite(9, HIGH);   //Engage the Brake for Channel A
        //Motor B stop
      digitalWrite(8, HIGH);   //Engage the Brake for Channel B
      delay(7500);

      //Phase 4 Go to second point
      //Motor A forward - max speed
      digitalWrite(12, LOW);  //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

      //Motor B forward - max speed
      digitalWrite(13, HIGH);  //Establishes foward direction of Channel B
      digitalWrite(8, LOW);    //Disengage the Brake for Channel B
      analogWrite(11, 255);    //Spins the motor on Channel B at half speed

      delay(2000); // Adjust to correspond the distance

      //Phase 5 Final Stop
      //Motor A - stop
      digitalWrite(9, HIGH);   //Engage the brake for Channel A
      //Motor B - stop
      digitalWrite(8, HIGH);   //Engage the brake for Channel B

      delay(60000);        // 1 minute stop
    }

While connected to USB, the device executes perfectly the sequence. As soon I run the sequence using the DC Source, the device does not respect any part of the coding. It started simply going forward while reversing the polarity randomly blocking the movement sometimes.

Looking forward to your suggestions.

title: Issue regarding executing sketch code when not connected to USB

Answers: 0


body:
I have two ESP8266's trying to talk to each other, a 'host' and a 'client', if you will. I have the `ESP8266mDNS.h` responder running on the host at `esp8266wifi.local`. On sending an http GET request to  `http://esp8266wifi.local/`, I have the webserver send a simple "Success" message.

When I use my computer to access the host in a web browser, it responds just fine, "Success". But when I use the client ESP8266 to send the GET request, it appears to be redirected to my ISP's search engine. The raw html reads:

    <meta http-equiv="refresh" content="0;url=http://search.frontier.com/search/?q=http://esp8266wifi.local/&t=0"/>

It appears to respond correctly when I connect to the IP address, `http://192.168.0.10/` using `ESP8266WebServer.h` but when I use the mDNS request I get redirected. Is there any way to work around this?

EDIT:

I tested on my phone's internet browser and my Wii U console and I also get the same redirect to my ISP's search engine.

title: Why does my ESP8266 making an HTTP request to an MDNS responder keep getting redirected to my ISP's search engine?

Answers: 0


body:
**Question:**

Can I connect an Arduino's USB port to the USB port of another embedded device that is expecting a USB thumb/flash device?

Or, can I connect a USB module to this embedded device, with the other end connected to GPIO's of the Arduino?

This embedded USB thumb device requires a thumb drive to transfer a file. I need to emulate the connection, disconnection, and thumb drive with the folder and file with a Arduino.

Is it possible to emulate an USB thumb drive between an Arduino and an embedded device's USB port?

**Research:**

I saw a couple other questions that talk about USB being a master/slave configuration and that certain IC are required. Additionally, that there were some cables that can be used for two-way data transfer (mostly for PC to PC data transfers). If that is the case, could one of those cables be used for this configuration? Which cable would work?

**Possible Solution:**

The embedded device I need to emulate a thumb drive on will automatically search for the file in a specific folder of the thumb drive. Would I be able to partition a section of an SD card with the SD card module to appear as a thumb drive, and then connect that partition to the embedded device via USB-A to USB-A cable?

**Diagram:**

Arduino USB Port -> USB Cable -> Embedded Device USB Port
Arduino GPIO -> USB Module -> USB Cable -> Embedded Device USB Port

Requirements:

Connection via USB cable between Arduino and an embedded device's USB port.
Ability to emulate the connection and disconnection of a USB thumb drive on the embedded device.

title: Can an Arduino emulate a USB mass storage device?

Answers: 1

body: The description of this device from Sparkfun appears to match the OP's requirement for integrating an Arduino with other USB devices by enabling the Arduino to acts as a USB host. https://www.sparkfun.com/products/9947


body:
I'm trying to connect to my Sparkfun Redboard (Arduino UNO compatible) on Mac OS X 10.12.3 (Sierra). The board comes with a USB mini to USB A FTDI cable. The board lights up and gets power over USB, but I don't see the right USB serial port in the Arduino IDE (I only see the Bluetooth port).

I've installed the [VCP FTDI drivers][2] v2.3 to no avail. When that didn't work, I also installed the CH340 CH341 drivers (but I doubt I need those). Rebooting the computer didn't help either.

I can only load the FTDI VCP v2.3 drivers using an explicit command `sudo kextload /Library/Extensions/FTDIUSBSerialDriver.kext/`. When I run `kextstat | grep FTDI`, I get:

     155    0 0xffffff7f83892000 0x7000     0x7000     com.FTDI.driver.FTDIUSBSerialDriver (2.3) ECC3AF36-431D-370D-86F2-5237785E9CF8 <127 41 5 4 3 1>

But it still doesn't show up in the Arduino IDE.

I've heard that Apple's own USB FTDI drivers (AppleUSBFTDI) could [cause problems][3], but it seems these are never loaded. If I try to unload the Apple FTDI driver (`sudo kextunload –b com.apple.driver.AppleUSBFTDI`), I get the following:

    (kernel) Kext com.apple.driver.AppleUSBFTDI not found for unload request.
Failed to unload com.apple.driver.AppleUSBFTDI - (libkern/kext) not found.

Any tips are welcome. Thanks!

  [1]: https://i.stack.imgur.com/SNdab.png
  [2]: http://www.ftdichip.com/Drivers/VCP.htm
  [3]: https://learn.sparkfun.com/tutorials/how-to-install-ftdi-drivers/mac

title: Connecting to the Sparkfun Redboard on Mac OS X Sierra

Answers: 1

body:
I'm using MacOS Sierra and an Arduino Pro Mini (from Sparkfun) with a breakout USB-to-UART board that uses an FTDI FT232 chip. I'm using the default Apple FTDI drivers (the ones that are bundled with Sierra) and I'm having no problems whatsoever.

Some people have reported problems using the manufacturer (FTDI) drivers that they had already installed **after** upgrading to Sierra. Some of them solved it by uninstalling the conflicting drivers and relying on the default Apple FTDI drivers [uninstalling the conflicting drivers and relying on the default Apple FTDI drivers][1] instead. It's worth a try.

OTOH, the CG340 driver doesn't currently work under Mac OS Sierra. Fortunately, Adrian Mihalko patched the driver and made it [available at GitHub][2], along with some troubleshooting instructions.

  [1]: https://forum.arduino.cc/index.php?topic=427825.0
  [2]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
  [3]: http://www.wch.cn/download/CH341SER_MAC_ZIP.html


body:
I have:

 1. An Digispark clone (with no Arduino bootloader)
 2. A USB -> TTL serial device
 3. A development breadboard
 4. Avrdude

I want to burn [the micronucleus bootloader](https://github.com/micronucleus/micronucleus) to the chip.

Is this possible, are there instructions?

ISP programmer is in the post but I'm not expecting it for 3 weeks.

title: Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude?

Answers: 3

body: Short answer, no. You can burn a bootloader onto the chip using a programmer, and then the bootloader does the serial communication magic so you can upload your sketches via serial or even low-speed USB (if your bootloader knows how to do USB bit-banging). But you can burn the bootloader only through SPI.

body:
you can't program your hardware with just USB to tty converter you need a programmer for that now instead of buying expensive programmers you can buy an Arduino board and use it as ISP (In System Programmer) here is the link describing the whole process.

  [Adruino as a  ISP][1]

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP

body:
No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.

Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a _qualified yes_.  Another Arduino can do this -- search the web and find many examples.

You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.

Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb


body:
I'm trying to send and receive some data from arduino to another arduino and I'm using arduino UNO and FS1000A / XY-MK-5V 433Mhz TX/RX Modules.
For transmitting I use the library `VirtualWire` and It works very well for this code:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[7] = {'h','e','l','l','o',' ','!'};
      vw_send((uint8_t *)msg, 7);
      vw_wait_tx(); // Wait until the whole message is gone
      delay(1000);
    }

I was wondering if I want to send some `string` or `int` data how I can do that.
I tried to use it for string data but I couldn't because the `Input` of function `vw_send(...)` is char and I couldn't use `int` or `string`.
finally I run this code:

    #include <VirtualWire.h>
    void setup()
    {
    // Initialize the IO and ISR
    vw_setup(2000); // Bits per sec
    }
    void loop()
    {
      char msg[11]="Hello there";
      vw_send((uint8_t *)msg, 11);
      vw_wait_tx(); // Wait until the whole message is gone
    delay(1000);
    }

 and I could send Hello there !, but I'm looking for the correct way for sending `string` and `int`.

title: How can I send integer from arduino to another arduino by FS1000A / XY-MK-5V 433Mhz TX/RX Module (WIFI)?

Answers: 1

body: Have a look at the Easy Transfer library.  I haven't used the particular modules you have, however I did successfully use the EasyTransfer library with Ciseco wireless modules.  In essence the EasyTransfer library transmits the data as a structure with the same format on each module.  The structure can contain any data type.


body:
I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?

I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.

title: 3.3v inductive proximity sensors

Answers: 1

body:
I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the [TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V](http://hackaday.com/2016/12/05/taking-it-to-another-level-making-3-3v-and-5v-logic-communicate-with-level-shifters/) article at hackaday.com for a circuit explanation.  See [gearbest.com](http://www.gearbest.com/other-accessories/pp_241590.html?currency=USD&vip=760186&gclid=CMPxtdWqoNICFUq5wAodEKwP3g) and [sparkfun.com](https://www.sparkfun.com/products/12009) and [Adafruit](https://www.adafruit.com/product/757) for inexpensive modules.

Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.


body:
I tried to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data. While posting the data I'm getting the error response while initializing the server using the command:

    {("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path")}

I don't know what the error is and how to fix it. Please help me to fix this.

    #include<SoftwareSerial.h>

    SoftwareSerial client(2,3);

    String testReading="{  \"testID\" : 1,  \"testLevel\" : 1, }";

    void setup() {
      Serial.begin(9600);
      client.begin(9600);
      delay(1000);
      if(client.available()) {
        Serial.print("Connected");
      } else {
        Serial.print("Not Connected");
      }
      checkSignal();
      connectGPRS();
      postData();
      delay(1000);
    }

    void loop() {
      if(client.available()) {
        checkSignal();
        connectGPRS();
        postData();
        delay(1000);
      }
    }

    void connectGPRS() {
      client.println("AT+CGATT?");
      delay(1000);
      ShowSerialData();
      client.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
      delay(1000);
      ShowSerialData();
      client.println("AT+SAPBR=3,1,\"APN\",\"www\"");
      //Using Indian Standard Vodafone Sim and so APN is www
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=1,1");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=2,1");
      delay(1000);
      ShowSerialData();
    }

    void checkSignal() {
      client.println("AT+CSQ");
      delay(1000);
      ShowSerialData();
    }

    void ShowSerialData() {
      while(client.available()!=0)
        Serial.write(client.read());
    }

    void postData() {
      client.println("AT+HTTPINIT");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CID\",1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"URL\",\"http://test.server/insert-path");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CONTENT\",\"application/json");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPDATA=99,10000");
      delay(1000);
      ShowSerialData;

      client.println(testReading);
      delay(1000);
      ShowSerialData;

      client.println("AT+HTTPACTION=1");
      delay(10000);
      while(!client.available());
      ShowSerialData();
    }

title: HTTP post request in JSON Format using SIM900 module

Answers: 2

body:
Hi all use this code below for establishing HTTP connection with the server. And to neglect the 601 or 504 error use proper posting format. Here I'm using JSON format. I just gave manual data. Ignore those errors in HTTPINIT, AT+SAPBR=2,1. The data will be posted to the server

     #include<SoftwareSerial.h>

    SoftwareSerial client(2,3);

    String reading="{  \" : 1,  \"latitude\" : 12.983027,  \"longitude\" : 80.2594,  \"timestamp\" : 100,  }";

    void setup()
    {
      Serial.begin(9600);
      client.begin(9600);
      delay(500);

      if(client.available())
      {
        Serial.print("Connected");
      }
      else
      {
        Serial.print("NotConnected");
      }

      //initSIM();
      connectGPRS();
      connectHTTP();
    }

    void loop()
    {

    }

    void connectGPRS()
    {
      client.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=3,1,\"APN\",\"www\"");//APN
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=1,1");
      delay(1000);
      ShowSerialData();

      client.println("AT+SAPBR=2,1");
      delay(1000);
      ShowSerialData();
    }

    void connectHTTP()
    {
      client.println("AT+HTTPINIT");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CID\",1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"URL\",\"http://xxx.xxx.xx/Listener/\"");//Public server IP address
      client.println("AT+HTTPPARA=\"URL\",\"http://testServer/Listener/\"");//Public server address
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
      delay(1000);
      ShowSerialData();

      client.println(reading);
      delay(1000);
      ShowSerialData;

      client.println("AT+HTTPACTION=1");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPREAD");
      delay(1000);
      ShowSerialData();

      client.println("AT+HTTPTERM");
      delay(1000);
      ShowSerialData;
    }

    void ShowSerialData()
    {
      while(client.available()!=0)
      {
      Serial.write(client.read());
      delay(100);
      }
    }

body:
    client.println(reading);
    delay(1000);
    ShowSerialData;

The above line of code would result in an error.


body: What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

title: DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface

Answers: 1

body:
Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.

https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)

Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.

There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.


body:
I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.

In the [datasheet][1], page 262, 24.9.2, bit 0, I can read that I have to set the `TWIE` flag to one to be able to catch the interruption.

So, I started to write this code :

<!-- language: c++ -->

    //https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

    #include <avr/interrupt.h>

    #define ADDRSHIELD 0xC0//adresse sur 8 bits

    #define TWI_FREQ 100000L
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

    #define START       0x08  //TWI start
    #define MT_SLA_ACK  0x18   //slave ACK has been received
    #define MT_DATA_ACK 0x28   //master ACK has been received

    #define LED0_ON_L 0x6

    #define TWI_STATUS      (TWSR & 0xF8)

    int etat = 0;
    uint8_t currentstep = 0;
    uint8_t _addr;
    uint8_t _data;

    ISR(TWI_vect)
    {
      //I remove the TWINT flag
      TWCR |= (1<<TWINT);

      switch(etat)
      {
        case 0:
          //start has been send, let's check if it's ok
          if(TWI_STATUS == START)
          {
            //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
            TWDR = _addr;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 1;
            //Serial.println(etat);
          }
          else
          {
            etat = -1;
          }
          break;
        //addr has been send
        case 1:
          if(TWI_STATUS == MT_SLA_ACK)
          {
            TWDR = _data;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 2;
            //Serial.println(etat);
          }
          else
          {
            etat = -2;
          }
          break;
        //data have been send
        case 2:
          if(TWI_STATUS == MT_DATA_ACK)
          {
            // disable twi module, acks, and twi interrupt
            TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
            etat = 3;
            //Serial.println(etat);
          }
          else
          {
            etat = -3;
          }
          break;
        //stop condition
        case 3:
          // desactivate internal pullups for twi.
          digitalWrite(SDA, 0);
          digitalWrite(SCL, 0);
          etat = 0;
          //Serial.println(etat);
          //Serial.println("Next");
          break;
      }
    }

    void sendData(uint8_t addr, uint8_t data)
    {
      _addr = addr;
      _data = data;

      i2cSetup();
      //start condition
      TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
    }

    void i2cSetup(void)
    {
      // activate internal pull-ups for twi
      sbi(PORTD, 0);
      sbi(PORTD, 1);

      // initialize twi prescaler and bit rate
      cbi(TWSR, TWPS0);
      cbi(TWSR, TWPS1);

      TWBR = ((F_CPU / 100000) - 16) / 2;
    }

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

    void loop()
    {
      if(etat == 0)
      {
        sendData(0xC0, 0b1010101);
      }
      if(etat == 3)
      {
          Serial.println("Next");
      }
      if(etat == -1)
      {
        Serial.println("Error from start");
        delay(100);
        exit(-1);
      }
      if(etat == -2)
      {
        Serial.println("NACK");
        delay(100);
        exit(-1);
      }
      if(etat == -3)
      {
        Serial.println("DATA NACK");
        delay(100);
        exit(-1);
      }
    }

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.

EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the [datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf), p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).

Thanks for your help,
julien

  [1]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf

title: How to properly use interruptions with twi (I2C)

Answers: 3

body:
After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.

This is my code working :

<!-- language: c++ -->

    //https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

    #include <avr/interrupt.h>

    #define ADDRSHIELD 0xC0//adresse sur 8 bits

    #define TWI_FREQ 100000L
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

    #define START       0x08  //TWI start
    #define MT_SLA_ACK  0x18   //slave ACK has been received
    #define MT_DATA_ACK 0x28   //master ACK has been received

    #define LED0_ON_L 0x6

    #define TWI_STATUS      (TWSR & 0xF8)

    volatile int8_t etat = 0;
    volatile uint8_t _addr;
    volatile uint8_t _data;

    ISR(TWI_vect)
    {
      switch(etat)
      {
        case 0:
          //start has been send, let's check if it's ok
          if(TWI_STATUS == START)
          {
            //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
            TWDR = _addr;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 1;
          }
          else
            etat = -1;
          break;
        //addr has been send
        case 1:
          if(TWI_STATUS == MT_SLA_ACK)
          {
            TWDR = _data;
            TWCR = _BV(TWIE) | _BV(TWEN);
            etat = 2;
          }
          else
            etat = -2;
          break;
        //data have been send
        case 2:
          if(TWI_STATUS == MT_DATA_ACK)
          {
            // disable twi module, acks, and twi interrupt
            TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
            etat = 3;
          }
          else
            etat = -3;
          break;
        //stop condition
        case 3:
          // desactivate internal pullups for twi.
          digitalWrite(SDA, 0);
          digitalWrite(SCL, 0);
          etat = 0;
          break;
      }
      //I remove the TWINT flag
      TWCR |= (1<<TWINT);
    }

    void sendData(uint8_t addr, uint8_t data)
    {
      _addr = addr;
      _data = data;

      i2cSetup();
      //start condition
      TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
    }

    void i2cSetup(void)
    {
      // activate internal pull-ups for twi
      sbi(PORTD, 0);
      sbi(PORTD, 1);

      // initialize twi prescaler and bit rate
      cbi(TWSR, TWPS0);
      cbi(TWSR, TWPS1);

      TWBR = ((F_CPU / 100000) - 16) / 2;
    }

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

    void loop()
    {
      if(etat == 0)
      {
        sendData(0xC0, 0b0010101);
      }
      if(etat == 3)
      {
          Serial.println("Next");
      }

      if(etat == -1)
      {
        Serial.println("Error from start");
        delay(100);
        exit(-1);
      }
      if(etat == -2)
      {
        Serial.println("NACK");
        delay(100);
        exit(-1);
      }
      if(etat == -3)
      {
        Serial.println("DATA NACK");
        delay(100);
        exit(-1);
      }
    }

Thanks a lot to jfpoilpret !

body:
Two observations.

1. The datasheetss does a fairly good job of Laying out the states and required conditions to move forward. Your code simply needs to mimic that. A short cut is to take a look at lpc210x datasheetss as it has fairly simple c code for the state machine implementation in the Isr.

2. What I typically do for slow multi byte transmission, i2c or UART, is to point a pointer to a string to be transmission, load up the datasheetss register and enable the interrupt. In the Isr, test if all the data has been transmission. If yes, turn off the Isr. Otherwise, load up thee next char. The data received can be processed via a callback function.

This approach minimizes user involvement. On a SPI with buffer, it can transmit without interruption.

body:
**Why ?**

The Arduino Mega 2560 is not very fast. The gain by using interrupts is not a lot.

The Wire.endTransmission and Wire.requestFrom wait until the I2C transaction has finished. That might seem a waste of time, but for the slow ATmega microcontrollers, not a lot of time is wasted.

The overhead by more code might even slow it down. A I2C library that is completely in software might even be faster than the original Arduino Wire library. Although the Arduino Wire library uses interrupts, the overhead by the Wire library creates a few extra delays during the I2C transaction.

It took years (it really did) to have a normal working Wire library for ATmega microcontrollers and it still is not very good. For example a hardware problem on the I2C bus could halt a sketch. I have seen a number of custom I2C libraries that run into problems one way or the other.

You can waste less time with:

 1. Make a well designed sketch, using millis instead of delay.
 2. Write a good interface to the sensor. I see a lot bad usage of the Wire library with unnecessary I2C transactions.
 3. Increase the I2C speed to 200kHz or 400kHz with Wire.setClock.
 4. Try to use the SPI bus if possible. For a 3.3V sensor with a SPI interface, a 3.3V Arduino board is the best choice. For example the Arduino Due with ARM M4 or a small board with ARM M0+ processor.
 5. When using the SPI bus with a Ethernet shield, try setting the SPI bus faster.
 6. When using a SD card, try full speed, instead of half speed.
 7. Use the newest Arduino IDE, because the 'lto' optimization was enabled which helps a lot.

Really serious work for better I2C functions has been done for the Teensy. It is still compatible with the Arduino Wire functions, but extra functions have been added that do not wait.


body:
I have a MIDI project I put together using an Arduino UNO R3 and the [Olimex Shield-MIDI][1].

[![Omilex Shield MIDI][2]][2]

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.

Has anyone come up with a good solution for Arduino + MIDI projects?  A metal enclosure would be a plus.

  [1]: https://www.olimex.com/Products/Duino/Shields/SHIELD-MIDI/open-source-hardware
  [2]: https://i.stack.imgur.com/DMn6u.jpg

title: Is there a good Arduino enclosure for that works with the Olimex MIDI shield

Answers: 1

body:
**Your best bet is to 3D print the enclosure.**

There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend [Shapeways][1] as they are fairly reasonable in price and ship worldwide.

If you are a handy DIY person you could use [SketchUp][2] or [Tinkercad][3] to design your enclosure. Also there are many Arduino enclosures on [Thingiverse][4] that you could use as a starting point.

Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.

  [1]: https://www.shapeways.com/
  [2]: https://www.sketchup.com/
  [3]: https://www.tinkercad.com/
  [4]: https://www.thingiverse.com/search/page:1?q=arduino&dwh=475a3e5064c9ae8


body:
I am using `Atmega328p` in my circuit. I will be programming this IC using Arduino. But because this is a PCB, so I will programming using `USBasp` programmer. So before uploading code as `upload using programmer`, I will select my arduino board in board select menu and then I will select `USBasp` as my programmer. But I want to know that is it really necessary to burn bootloader on a new `Atmega328p` IC. On some page, they say you do not require it. But some say, its necessary because you will be using Arduino functions like `Serial.Begin()` etc.

So I want to know what does this bootloader contains. Do I really need it. Can I directly upload my code using programmer. Can anyone please explain this to me.?

title: Do we really need to upload Arduino bootloader for new Atmega IC

Answers: 1

body:
No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.

If you are programming through USBasp you don't even need it on a "normal" Arduino board.

All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.

If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


body:
I'm trying to make a 10Hz pulse wave output at Arduino's pin 9 by using the following code I wrote:

    #define F_CPU 16000000UL
    #include <avr/io.h> //Defines pins, ports, etc.
    #include <util/delay.h>

    int main(void)
    {

     DDRB |= (1<<DDD1); //Does this set port B pin 1 and is this pin 9 in UNO board?
     PORTB |= (1<<PORTB1);

     while(1){

      PORTB |= ~(1<<PORTB1);
      _delay_ms(100);
      PORTB |= (1<<PORTB1);

     }

    }

I use Atmel Studio to uplaad the code and it works fine with other codes. But for some reason this code doesn't work. What can be the problem here?

Still doesnt work
**edit:**

    #define F_CPU 16000000UL
    #include <avr/io.h> //Defines pins, ports, etc.
    #include <util/delay.h>

    int main(void)
    {

     DDRB |= (1<<DDD1);
     PORTB |= (1<<PORTB1);

     while(1){

            PORTB &= ~(1<<PORTB1);
      _delay_ms(100);
      PORTB |= (1<<PORTB1);

     }

    }

title: Problems creating 10Hz pulse wave

Answers: 3

body:
Your code doesn't clear anything.
<!-- language: c++ -->

        PORTB |= ~(1<<PORTB1); // set everything except PORTB1 pin
        _delay_ms(100);
        PORTB |= (1<<PORTB1);  // set PORTB1 pin

And recommended tutorial: [Bit manipulation (AKA "Programming 101")][1] from the AVRFreaks.net

BTW: next issue might be "the pulse is way too fast so it seems there is none"

Try this:

    while(1) {
        PINB = _BV(PINB1); // toggle pin
        _delay_ms(50);
    }

  [1]: http://www.avrfreaks.net/forum/tut-c-bit-manipulation-aka-programming-101?page=all

body:
       PORTB |= ~(1<<PORTB1);

change it to:

       PORTB &= ~(1<<PORTB1);

if you want to clear PB1.

body:
You have your whole 100ms wait time while the pin is low.
You need half of it while low, half while high.

    while(1){

        PORTB &= ~(1<<PORTB1);
        _delay_ms(50);
        PORTB |= (1<<PORTB1);
        _delay_ms(50); // You need a delay here too.
    }


body:
I would like to interface an ADC (in particular this one: http://www.linear.com/product/LTC1400) with an Arduino Nano via SPI. The specified max clock speed for the ADC is 6.4 MHz. The Nano can do up to 8 MHz clock speed, but I'm not able to set 6.4 MHz. If I try this

    SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE0));

I get 4 MHz at the clock pin, which means the achievable acquisition rate of the ADC is reduced. Is there a way to get the 6.4 MHz going for maximum acquisition rate with the ADC? Or is there a different approach to get fast data transfer with the ADC (e.g. external clock)?

title: Can I set arbitrary SPI clock speeds?

Answers: 2

body:
You are limited to what your microcontroller supports. You could use a 12MHz oscillator to clock your Arduino and set the SCK divider to fOSC/2 = 6MHz (even if it was possible, I wouldn't go higher. Having some margin just to be on the safe side is generally a good advice).

Drawback of this solution is that you lose CPU performance. Please consider also that just collecting ADC data is not enough. You also have to do something with it. Therefore the question should rather be:

"What minimum ADC acquisition rate do I need for my application?"

body:
No, you cannot set 6.4MHz on SPI with a default hardware arrangement.

On the ATMega series of chips the SPI clock is generated by dividing the system clock (8 or 16MHz depending on if you have a 3.3 or 5V board) by one of: 2, 4, 8, 16, 32, 64 or 128.

Looking at [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) (section 25) it may be possible to configure the USART to run in SPI mode which allows a flexible clock speed, though this is not supported by the Arduino API.


body: does the code clean from arduino if i touch reset button?

title: Does the reset button clean a programe that you programmed?

Answers: 1

body: No, it only causes the microcontroller to start over the existing program/code.


body:
is it possible to power esp8266 wifi module with button cell for long period(1 year ) real time applications??
 Needs only wifi features (no need of gpio)

what will be voltage and current of the cell??

title: is it possible to power esp8266 with button cell

Answers: 1

body:
No. It has to wake up to do something and turn on the wifi. At that moment it requires too much power for a button cell. It needs about 150mA, mostly for wifi.

The BLE (Bluetooth Low Energy) is specifically designed for low power usage. Also some RF modules (433MHz, 868MHz, 915MHz) can be used with a small battery.