body:
im trying to make a speedometer with arduino Nano Board but when i use interrupt im getting "strange" number on variables `t1` or `t2` going under 0 there is the code:

    volatile int impulsi =  0;
    int impulsiOld = 0;
    volatile int appoggio = 0;
    //static int inizioDiNuovo = 0;
    volatile unsigned int deltaT[3];
    long t1=0;
    long t2=0;

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

      pinMode(2, INPUT_PULLUP);
      attachInterrupt(0, definisciTempi, RISING);

    }

    void loop() {

      Serial.println(impulsi);
      if (impulsi == impulsiOld || impulsi > impulsiOld)
      {
        ;
      }
      //Serial.print("N IMPULSI: ");
      //Serial.println(impulsi);
      if (appoggio == 3) {
        appoggio = 0;
        Serial.print("DELTA T 0 : ");
        Serial.println(deltaT[0]);
        Serial.print("DELTA T 1 : ");
        Serial.println(deltaT[1]);
        Serial.print("DELTA T 2 : ");
        Serial.println(deltaT[2]);

        t1 = (deltaT[1] - deltaT[0]);
        if (t1 == 0) {
          t1 = 1;
        }
        t2 = (deltaT[2] - deltaT[1]);
        if (t2 == 0) {
          t2 = 1;
        }
        int t = t1 + t2;

        Serial.print("TEMPO T1 ");
        Serial.println(t1);
        Serial.print("TEMPO T2 ");
        Serial.println(t2);

      }

    }

    void definisciTempi() {
      impulsi++;
      switch(appoggio){

        case 2:
        //Serial.println("ASSEGNO DELTA T 2");
        deltaT[2] = millis();
        //Serial.println(deltaT[2]);
        appoggio = 3;
        break;

        case 1:
        //Serial.println("ASSEGNO DELTA T 1");
        deltaT[1] = millis();
        appoggio = 2;
        break;

        case 0:
        //Serial.println("ASSEGNO DELTA T 0");
        deltaT[0] = millis();
        appoggio = 1;
        break;

      }
    }

how suggest i changed

    unsigned int t1=0; unsigned int t2=0; into `long t1=0; long t2=0;`

output on Serial now have negative number it's for the interrupt??:

    DELTA T 0 : 8785
    DELTA T 1 : 8666
    DELTA T 2 : 8706
    TEMPO T1 40
    TEMPO T2 -119  <------how 8706-8666= -119 ?

this is my pulse generator code:

    const int pin = 2;
    void setup() {
      pinMode(pin,OUTPUT);

    }

    void loop() {
     digitalWrite(pin,HIGH);
     delay(40);
     digitalWrite(pin,LOW);
     delay(40);
    }

title: Wrong computation Number

Answers: 2

body:
unsigned int t1=0;
    unsigned int t2=0;

Integers on an 8 bit system can only store 16 bits of data. For `unsigned` that is 0 - 216-1, or 0 - 65535.

Make them `unsigned long` and they can store 0 - 232-1, or 0 - 4294967295.

Also, since they are `unsigned`, any negative value will *wrap around* to the maximum again. An `unsigned` can't store a negative value.

body:
The interrupt may be triggering between the Serial.print and the actual calculations, as stated by @Andrew.

Evidence supporting that fact is that your deltas are recorded in order 0, 1, 2 (ie: delta 0 < delta 1 < delta 2), However in the example output delta 0 is larger than delta 2, which suggests that a new round of delta recordings had started but not yet completed.

Updating this section as follows should fix the issue:

    if (appoggio == 3) {

      noInterrupts(); // Disable interrupts while calculating

      appoggio = 0;
      Serial.print("DELTA T 0 : ");
      Serial.println(deltaT[0]);
      Serial.print("DELTA T 1 : ");
      Serial.println(deltaT[1]);
      Serial.print("DELTA T 2 : ");
      Serial.println(deltaT[2]);

      t1 = (deltaT[1] - deltaT[0]);
      if (t1 == 0) {
        t1 = 1;
      }
      t2 = (deltaT[2] - deltaT[1]);
      if (t2 == 0) {
        t2 = 1;
      }
      int t = t1 + t2;

      Serial.print("TEMPO T1 ");
      Serial.println(t1);
      Serial.print("TEMPO T2 ");
      Serial.println(t2);

      interrupts(); // re-enable interrupts

    }


body:
I have a HMC5883L 3-axis magnetometer. I would like to add tilt compensation to my Arduino Uno project.

Since the IC has 3 axis that it measures (X,Y,Z) is it possible to add tilt compensation without an accelerometer? If yes would this how do I find an equation to do the calculation. Is this equation found from http://bluelemonlabs.blogspot.fi/2013/08/arduino-simple-compass-with-hmc5883l.html correct?

title: HMC5883L tilt compensation

Answers: 1

body:
No. You need an accelerometer.

If you read the article you link to you can see this bit:

> There are many margin of improvement. First, we ought compensate the potential tilt of the device using the accelerometer data from the ADXL345, for example using the info on [my previous post](http://bluelemonlabs.blogspot.it/2013/08/arduino-imu-pitch-roll-from-adxl345.html)!

To do tilt compensation you need three axes of both magnetometer data and accelerometer data to scale and merge those three axes.


body:
[![enter image description here][1]][1]I was trying to build a Bluetooth controlled car. I was near completing it but what I did wrong was that I connected the 5 V output of L298 motor driver to 5V pin of Arduino where I was supposed to connect it in Vin. My Arduino got heated for a couple of seconds. Knowing that I immediately disconnected. Now serial port doesn't work in my Arduino. The serial port option turned gray. I even tried replacing the ATmega IC but got the same result. What might have happened?

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

title: Did I damage my Arduino?

Answers: 4

body:
Yes, it sounds like you fried something.

I can't quite make out what it was you did from your description (I'm sure it makes perfect sense to you with the hardware in front of you), but the symptoms do sound somewhat fatal.

What actually happened depends very much on the Arduino you have - if it's a genuine one or a cheap Chinese clone. Either way the USB circuitry seems to not be functioning. Whether that is because the USB chip (varies depending on if it's a real Arduino [ATMega16U2] or a clone [CH340G]) or one of the voltage regulators is unknown.

You should power the board up normally and test the voltages at the 5V and 3.3V pins. Also if a component is still getting hot you should note which component it is, and that will give more of a clue as to what went wrong.

body: You fried it you should ALWAYS double check connections before powering on your arduino but I do suggest doing a normal power up without any connections to see what happens

body:
The ATmega328 on these boards is 5V tolerant on GPIOs so it depends on where exactly you connected the cable.

GND pins, for example, would've been fatal.

body:
it feel sad to hear that you just fried it up. Every mistakes gives opportunity to learn tons of knowledge.
In this case you supplied 5v supply to 5v output pin. If you've seen the datasheet of  **8-bit AVR Micro-controller ATmega328/P** you'll know that it just possess VCC for 5v supply pin (input) neither an output 5v pin. Its the job of voltage regulator attached next to the power jack to supply 5V to provide the necessary juice to the chip. If you supplied 5v to GPIO output pin then you may or may not have burnt the chip but for sure you burnt the arduino board ,technically its power control system. So i think it'll be better buying a new board rather then fixing it.But i salute your attempts.


body:
I have this breadboard, and there is no indication on it about what is positive/negative on it.

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

In comparison, this other breadboard (pic from the internet) DOES have indications:

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

Can anyone give me a hint ?

  [1]: https://i.stack.imgur.com/36SHzl.jpg
  [2]: https://i.stack.imgur.com/CH3KF.jpg

title: How to know positive and negative in breadboard

Answers: 3

body: As gre_gor said. A simple breadboard contains of rows and columns of connections but sometimes for convenience manufacturer marks or prints Positive and Negative symbol along the row as they are usually used to power a circuit

body:
You decide which rails are positive and which are negative when you connect them to the + an - from your power supply or battery.

A breadboard isn't polarised *per se*. It's just a bunch of cross-connections inside a perforated plastic case. No active or passive components inside.

Some manufacturers may choose to paint indications regarding where to connect the positive and negative rails, but those are just a guideline. Ultimately it's your choice, you're free to connect + and - wherever you want in the breadboard rails.

body:
Connections in the two strips along the edge running top to bottom in your image are connected (in the way you have the image placed) top to bottom.  So, all pins are connected to each other in each of those rows.  Within the inner secions, the connections are (in your image) across from one side to the other.

You decide how you want the power supply cable to be connected to your breadboard,  just becasue there's no indicators means that they simply haven't drawn any coloured lines on the breadboard.  You can draw red and black lines on however you wish.


body:
I've been working on I2C and I learned how to initialize, send and receive with I2C communication protocol.

Next, I wanted to run the LCD1602 I2C adapter. But the module has a different bit masking, it turns out that I have to keep a specific bit set so I can control the remaining 7-bits, because otherwise I can't control the upper 4-bits if this bit is 0.

So, I put the 8-bit variable for the bit masking operations in the global section and initialize it with uint8_T bitmasking = 0x08; but it's volatile. I used static keyword, but the bit is not constant.

So what's the solution?

Regards,

title: How to keep a specific bit set all the time for bit masking I2C operations?

Answers: 1

body:
'static' just avoids reinitialization and is used for local vars in timed interrupts for example.

`volatile` is another keyword you should not be using without thinking about it and does not appear to be useful for your case. See https://stackoverflow.com/questions/4592762/difference-between-const-const-volatile for more information

The appropiate keyword would be `const`, which tells the compiler this var mustn't be changed.

But I suspect there is another problem with your code, which will make the compiler throw an error as soon as you use `const` in the declaration.
I assume you are not using the variable correctly. You are meant to use a bitwise OR `|` in order to set the required bit **along** your actual data.

So do it like this:

    data_byte |= bitmasking;
    write8(data_byte);


body:
I have programmed `ESP8266` to make it accessible over the network using below program.

**First Program**

 #include <ESP8266WiFi.h>
 #include <WiFiClient.h>
 #include <ESP8266WebServer.h>

 //SSID and Password of your wifi router
 const char* ssid = "Moto";
 const char* password = "reset1234";

 ESP8266WebServer server(80);

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

   WiFi.begin(ssid, password);     //Connect to your WiFi router
   Serial.println("");

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

   //If connection successful show IP address in serial monitor
   Serial.println("");
   Serial.print("Connected to ");
   Serial.println(ssid);
   Serial.print("IP address: ");
   Serial.println(WiFi.localIP());  //IP address assigned to your ESP

   server.begin();                  //Start server
   Serial.println("HTTP server started");
 }

 void loop() {
   server.handleClient();          //Handle client requests
 }

It is working fine, What is the way to reset it to run below program? I wanted to send AT commands on serial monitor using below program which has been uploaded successfully but not responding AT commands on Serial Monitor, as ESP8266 is running above program and showing output of above program on running below program on Serial Monitor.

I want to reset ESP8266 so it responds to below program. What is the way ?

    Connected to Moto
    IP address: 192.168.43.115
    HTTP server started

**SecondProgram**

 #include "SoftwareSerial.h"

 SoftwareSerial esp8266(2, 3); // RX, TX

 void setup()
 {
   Serial.begin(9600); // serial port used for debugging
   esp8266.begin(9600);  // your ESP's baud rate might be different
 }

 void loop()
 {
   if(esp8266.available())  // check if the ESP is sending a message
   {
  while(esp8266.available())
  {
    char c = esp8266.read();  // read the next character.

    Serial.write(c);  // writes data to the serial monitor
  }
   }

   if(Serial.available())
   {
  delay(10);  // wait to let all the input command in the serial buffer
  Serial.write("Hello");
  // read the input command in a string
  String cmd = "";
  while(Serial.available())
  {
    cmd += (char)Serial.read();
  }
  // send to the esp8266
  esp8266.println(cmd);
   }
 }

title: How to reset ESP8266 wifi module

Answers: 2

body:
You need to reinstall the AI Thinker AT firmware.

Here's how you do it: [How to flash ESP8266 firmware update ESP-01 AI thinker][1]

Last time I did it I used the [esptool.py](https://github.com/espressif/esptool) program, and used the [ai-thinker-0.9.5.2.bin](http://wiki.aprbrother.com/wiki/Firmware_For_ESP8266) firmware (there's two versions on there, the default 115200 baud, and a 9600 baud variant).

On Linux I then used the command:

    foo@bar:~$ ./esptool.py --port /dev/ttyUSB0 --baud 57600 write_flash 0 ai-thinker-0.9.5.2.bin
    Connecting....
    Detecting chip type... ESP8266
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 512KB
    Flash params set to 0x0000
    Compressed 520192 bytes to 165297...
    Wrote 520192 bytes (165297 compressed) at 0x00000000 in 29.0 seconds (effective 143.3 kbit/s)...
    Hash of data verified.

    Leaving...
    Hard resetting...

This was, of course, with GPIO0 held LOW for programming mode (I actually use an adaptor with a programming switch that controls GPIO0), and for other operating systems you will need to change the port name to suit (`COM3:`, `/dev/cu.usbmodem4873`, etc).

  [1]: http://www.esp8266.com/viewtopic.php?f=15&t=12440

body:
    //reset settings - in case of trouble just put in your code
    //wifiManager.resetSettings();

That`s all you need


body:
I'm uploading this sketch to try connecting ESP to internet. However, most of the times I've ran it it takes a very long time to connect, a lot of times I've had to break the process because it seems it goes to nowhere. Few times it has connected in less than a minute. Is it any alternative to boost the connection?

Also, when I reset the module, it writes to the terminal 3 strange characters, and freezes without even starting to execute its sketch. Do you mind me asking how to solve that?

Regards!

    #include <ESP8266WiFi.h>

    const char red[] = "CDT10";
    const char pass[] = "G7ZSY74Cs";
    unsigned long muestra = 0;

    void setup() {
      Serial.begin(9600);
      WiFi.mode(WIFI_STA);
      WiFi.begin(red,pass);
      while (WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(1000);
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("IP address: "); Serial.println(WiFi.localIP());
      Serial.print("Chip ID: "); Serial.println(ESP.getChipId());
    }

    void loop() {
      delay(5000);
      muestra = millis();
      Serial.println(muestra);
    }

title: Is it any way to connect ESP8266 to wifi faster?

Answers: 1

body:
I have also experienced the inability to connect sometimes. I wait a certain amount of time for it to connect then do a ESP.reset() if it fails.

As for the boot problem it sounds like you are keeping GPIO0 low so it goes back into programming mode. Hold it high and it will run your program instead.


body:
I doing a small project with 6 display 7 segment (I will call A1, A2, A3, A4, A5, A6) and 3 cd4543B (I will call Da, Db, Dc) with an arduino mega 2560. I also use 6 transistor to control power supply of display.

Da is use for A1, A2

Db is use for A3, A4

Dc is use for A5, A6

The circuit is done, and work if I use only 4 display I have tried different combination (A1, A2, A3, A4, or A1, A2, A5, A6 or A2, A3, A4, A5, or A3, A4, A5, A6) and all work well.

but If I want to use five or six display, nothing work....

[![here a diagram of my circuit][1]][1]

there is resistance for each segment of each display which not appear on the diagram.

my code for 5 display :

    //Da
    const int bit_A=8;
    const int bit_B=9;
    const int bit_C=10;
    const int bit_D=11;
    //Db
    const int bit_E=22;
    const int bit_F=24;
    const int bit_G=26;
    const int bit_H=28;
    //Dc
    const int bit_I=40;
    const int bit_J=42;
    const int bit_K=44;
    const int bit_L=46;

    // transistors
    const int alim_dizainemillier= 3;
    const int alim_millier=4;
    const int alim_centaine=5;
    const int alim_dizaine=6;
    const int alim_unite=7;

    void setup()
    {

    pinMode(bit_A,OUTPUT);
    pinMode(bit_B,OUTPUT);
    pinMode(bit_C,OUTPUT);
    pinMode(bit_D,OUTPUT);
    pinMode(bit_E,OUTPUT);
    pinMode(bit_F,OUTPUT);
    pinMode(bit_G,OUTPUT);
    pinMode(bit_H,OUTPUT);
    pinMode(bit_I,OUTPUT);
    pinMode(bit_J,OUTPUT);
    pinMode(bit_K,OUTPUT);
    pinMode(bit_L,OUTPUT);
    pinMode(alim_dizainemillier,OUTPUT);
    pinMode(alim_millier,OUTPUT);
    pinMode(alim_centaine,OUTPUT);
    pinMode(alim_dizaine,OUTPUT);
    pinMode(alim_unite,OUTPUT);

    digitalWrite(bit_A,LOW);
    digitalWrite(bit_B,LOW);
    digitalWrite(bit_C,LOW);
    digitalWrite(bit_D,LOW);
    digitalWrite(bit_E,LOW);
    digitalWrite(bit_F,LOW);
    digitalWrite(bit_G,LOW);
    digitalWrite(bit_H,LOW);
    digitalWrite(bit_I,LOW);
    digitalWrite(bit_J,LOW);
    digitalWrite(bit_K,LOW);
    digitalWrite(bit_L,LOW);
    digitalWrite(alim_dizainemillier,LOW);
    digitalWrite(alim_millier,LOW);
    digitalWrite(alim_centaine,LOW);
    digitalWrite(alim_dizaine,LOW);
    digitalWrite(alim_unite,LOW);
    }

    void loop()
    {
     for(int i=0;i<100000;i++)
     {
       afficher_nombre(i);

     }
    }

    void afficher_nombre(int nombre)

    {
     long temps;
     int unite=0,dizaine=0,centaine=0, millier=0, dizainemillier=0;
     dizainemillier=nombre/10000;
     millier=(nombre-(10000*dizainemillier))/1000;
     centaine=(nombre-1000*millier)-(10000+dizainemillier)/100;
     dizaine=(nombre-(centaine*100)-(millier*1000)-(dizainemillier*10000))/10;
     unite=nombre-(dizainemillier*10000)-(millier*1000)-(centaine*100)-(dizaine*10);

     temps=millis();
     while((millis()-temps)<500){

        digitalWrite(alim_dizainemillier,HIGH);
        afficher_CD(dizainemillier);
        digitalWrite(alim_millier,LOW);
        digitalWrite(alim_centaine,LOW);
        digitalWrite(alim_dizaine,LOW);
        digitalWrite(alim_unite,LOW);
        delay(5);

        digitalWrite(alim_dizainemillier,LOW);
        digitalWrite(alim_millier,HIGH);
        afficher_CM(millier);
        digitalWrite(alim_centaine,LOW);
        digitalWrite(alim_dizaine,LOW);
        digitalWrite(alim_unite,LOW);
        delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,HIGH);
       afficher_CM(centaine);
       digitalWrite(alim_dizaine,LOW);
       digitalWrite(alim_unite,LOW);
       delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,LOW);
       digitalWrite(alim_dizaine,HIGH);
       afficher_UD(dizaine);
       digitalWrite(alim_unite,LOW);
       delay(5);

       digitalWrite(alim_dizainemillier,LOW);
       digitalWrite(alim_millier,LOW);
       digitalWrite(alim_centaine,LOW);
       digitalWrite(alim_dizaine,LOW);
       digitalWrite(alim_unite,HIGH);
       afficher_UD(unite);
       delay(5);
     }
    }

    void afficher_UD(int chiffre)
    {
      digitalWrite(bit_A,LOW);
      digitalWrite(bit_B,LOW);
      digitalWrite(bit_C,LOW);
      digitalWrite(bit_D,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_D,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_C,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_B,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_A,HIGH);
               chiffre=chiffre-1;
             }
    }

    void afficher_CM(int chiffre)
    {
      digitalWrite(bit_E,LOW);
      digitalWrite(bit_F,LOW);
      digitalWrite(bit_G,LOW);
      digitalWrite(bit_H,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_H,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_G,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_F,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_E,HIGH);
               chiffre=chiffre-1;
             }
    }

    void afficher_CD(int chiffre)
    {
      digitalWrite(bit_I,LOW);
      digitalWrite(bit_J,LOW);
      digitalWrite(bit_K,LOW);
      digitalWrite(bit_L,LOW);

          if(chiffre>=8)
             {
               digitalWrite(bit_L,HIGH);
               chiffre=chiffre-8;
             }
         if(chiffre>=4)
             {
               digitalWrite(bit_K,HIGH);
               chiffre=chiffre-4;
             }
        if(chiffre>=2)
             {
               digitalWrite(bit_J,HIGH);
               chiffre=chiffre-2;
             }
        if(chiffre>=1)
             {
               digitalWrite(bit_I,HIGH);
               chiffre=chiffre-1;
             }
    }

I don't understand why it's not working. Could it be a power supply problem ? even if there is never two display used at the same time (delay between them, see code)

Thanks a lot for any help.

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

title: 7 Segments display with arduino mega2560

Answers: 2

body:
Try this link [Arduino and CD4543][1]

To control a common cathode seven segment display using CD4543

    PH ( Pin 6 ) should be set LOW.
    LD ( Pin 1 ) should be set HIGH.
    BL ( Pin 7 ) should be set LOW.
[![enter image description here][2]][2]

Try this code for each segment, could be faulty segment too :)

    int Ph  = 6;      //arduino pin connected to the Ph pin of 4543
    int BL  = 5;     //arduino pin connected to the BL pin of 4543
    int LD  = 11;   //arduino pin connected to the LD pin of 4543

    int A   = 7;
    int B   = 9;
    int C   = 10;
    int D   = 8;

    void setup()
    {
        // Declare all the pins as OUTPUT pins

      pinMode(Ph,  OUTPUT);
      pinMode(BL,  OUTPUT);
      pinMode(LD, OUTPUT);

      pinMode(A , OUTPUT);
      pinMode(B  , OUTPUT);
      pinMode(C  , OUTPUT);
      pinMode(D, OUTPUT);

    }

    void loop()
    {

        // Display 0

      digitalWrite(Ph,  LOW);
      digitalWrite(BL,  LOW);
      digitalWrite(LD,  HIGH);

      digitalWrite(A , LOW);
      digitalWrite(B , LOW);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 1

      digitalWrite(A , HIGH);
      digitalWrite(B , LOW);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 2

      digitalWrite(A , LOW);
      digitalWrite(B , HIGH);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 3

      digitalWrite(A , HIGH);
      digitalWrite(B , HIGH);
      digitalWrite(C , LOW);
      digitalWrite(D , LOW);

      delay(1000);

        // Display 4

      digitalWrite(A , LOW);
      digitalWrite(B , LOW);
      digitalWrite(C , HIGH);
      digitalWrite(D , LOW);

      delay(1000);
    }

  [1]: http://www.learnerswings.com/2014/04/control-common-cathode-seven-segment.html
  [2]: https://i.stack.imgur.com/JyAoK.png

body:
> The circuit is done,

unnecessarily complex: you can share the data lines among the drivers.


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

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

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

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

title: Arduino Uno: Receive MIDI data from DAW

Answers: 2

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

On AVRs, you typically use the Lightweight USB Framework for AVRs ([LUFA](http://www.fourwalledcubicle.com/LUFA.php)), which has support code for both the basic USB protocol and for USB MIDI.

body:
For USB Midi you could use: Arduino UNO + USB Host Shield + [USBH_MIDI Library](https://github.com/YuuichiAkagawa/USBH_MIDI)

The library is specifically for the USB Host Shield. I've used this to take MIDI over USB from a digital piano and used it to control some LEDs. It's pretty strait forward to get it all working.


body:
So I have a bunch of functions (methods) made and I want to make it so that if the button is clicked (single click) the effects to change... I thought something like:

    buttonState = digitalRead(buttonPin);
    if(buttonState==HIGH) {
      counter++;
      if(counter>2) {
        counter=0;
       }
     }
    if(counter==0) {
      Foo1();
    }
    if(counter==1) {
      Foo2();
    }
    if(counter==2) {
      Foo3();
    }

But I noticed that it will only read the input button(buttonPin) if I click the button in the exact time (when the function has already ended and at digitalRead time)... So is there some way to do it even if the function is in progress to cancel it and go to the other ones (some way that the digitalRead will read it non stop)?

title: LEDs effects changing with a button

Answers: 2

body:
I think you want to look at interrupts.  You are right, unless the button happens to be pressed when you read the state of it you won't see it as pressed.  If you `foo`s take a long time to execute the you will miss button presses.

What you can do is use 'interrupts'.  Certain pins can be configured to stop the main program and run a small bit of code (that can't do certain things).  For instance they can change the value of a global `volatile` variable.  Next time the program reads the variable it will read the new value (volatile prevents the value being cached by the processor).

With you current code, you would remove the digital read line, and the `if (buttonState == HIGH)` block and move those into you ISR.  This would mean every click would be counted.  If you wanted the ISR to stop the current `foo` and move on then you `foo`s would need to check a flag that the ISR also set and when they see it they return.

In the ISR you can't call Serial.print() etc, it takes too long and your ISR won't work.  Keep it fast and small.

https://www.arduino.cc/en/Reference/AttachInterrupt
https://www.arduino.cc/en/Reference/DetachInterrupt

body:
I had been timing single click as part of a minimal button debouncer (wich is part of a larger project).

According to my tests, the duration of button press is as follow:

 - Quick fire press. Average, 40-70 ms per button press.
 - Normal quick. Average, 150 ms per button press.
 - Long press. Over 400 ms (very personal).

Now, if you loop takes less that 40 ms, your sketch still can catch almost any button press. If you restrict to "normal" button presses, your `loop` can take up to 150 ms without trouble.

So, profile your app. Measure your worst case scenario and the take action.

*We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evi*l. Donald Knuth


body:
I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.

**Update:**

Having eliminated *all* code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.

So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.

**Note:** The flash of TX no longer shows up with the empty sketch.

title: Is there a Serial write buffer limit and does the Arduino reset if it is hit?

Answers: 1

body:
It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:

    void setup() {}

    void loop() {}

the board would still periodically reset itself.

I eliminated:

  - flushing the receive buffers,
  - eliminating all receives by disconnecting pins,
  - speeding up/slowing down the serial port/s,
  - speeding up/slowing down the GPS reporting rate,
  - auxiliary hardware,
  - code,
  - includes,
  - defines,
  - laptop power supply noise,
  - board revision in Arduino IDE,
  - Arduino IDE version,
  - USB port on laptop,
  - trying [this hack][1] to prevent the RESET pin from going low,
  - another Mega 2560 and a Due

None of the above influenced the issue.

The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.

Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.

  [1]: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


body:
Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.

What's it for?

title: Arduino/Genuino 101 5 volts pin

Answers: 1

body:
In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.

However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.


body:
I am looking for an example of how to load a program from sd card to SRAM and execute it from there on the SAMD21.

I understand that the given MCU use the Von Neumann architecture and all code is privileged.

title: Run program from SRAM on SAMD21?

Answers: 1

body:
There's two aspects to what you want to do - one (relatively) easy, and one (comparatively) hard.

The first thing you will need is some way of getting your program into RAM. That would mean some software running on the chip that will accept the program and place it into RAM then execute it. You will have to write your own bootloader-like program that runs in Flash that will perform the task.

The second, harder, thing is to compile your program in such a way that it will execute from RAM. And that's no easy task.

Ideally you want to compile the code as *position independent code* (with the command line flag `-fPIC`), but that depends on the compiler being able to do that for this chip. If not, you will have to compile it so that the code expects to reside in RAM with all addresses used for jumps, etc, going to the right location. And that brings me to the second aspect of compiling, the *linker script*.

If you have your code in RAM you can't also have your variables in the same place in RAM. You will have to subdivide the RAM into two sections - the code execution section and the variable storage section. This is done through the construction of a custom *linker script* which is used during the linking phase of compilation. It tells the compiler where in memory to place everything - code, variables, etc. You will need to craft your own linker script to divide the RAM up in a suitable manner to give you enough room for your code while at the same time not starving it of variable storage space. This will also make sure all jumps, etc, in your code use the right addresses in case you can't (or don't want to) use `-fPIC`.

So, given all that, do you still *really* want to execute code from RAM?


body:
Can anybody tell me why these analogWrite() statements are being ignored. The code is entering the "if"statements because the Serial.println() statements are being executed.

        class Pwm
    {
      unsigned long previousMillis = 0;
      unsigned long currentMillis;
      int LED;
      int DELAY;
      int up;
      int down;
      int x;

      public:
      Pwm(int led, int Delay) {

        int LED = led;
        pinMode(LED, OUTPUT);

        DELAY = Delay;
        up = 1;
        down = 0;
        x = 0;

      }

      void Update() {
        currentMillis = millis();
        if (currentMillis - previousMillis >= DELAY && up == 1) {
        analogWrite(LED, x);
        x++;
        previousMillis = currentMillis;
        Serial.println(x);
        if (x == 256) {
          up = 0;
          down = 1;
        }
      }
      if (currentMillis - previousMillis >= DELAY && down == 1) {
        analogWrite(LED, x);
        x--;
        previousMillis = currentMillis;
        Serial.println(x);
        if (x == 0) {
          up = 1;
          down = 0;
        }
       }
      }

    };

    // create Flasher Objects
    Flasher red(12, 1000, 250);
    //Flasher yellow(11, 500, 500);
    //Flasher green(10, 250, 1000);
    //Flasher blue(8, 250, 500);

    // create PWM Objects
    Pwm pin9(9,8);

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

    void loop()
    {
      red.Update();
      //yellow.Update();
      //green.Update();
      //blue.Update();
      pin9.Update();
    }

if I load this code everything works fine. I only have issues with the OOP method.

    int LED = 9;
    int DELAY = 8;
    int up = 1;
    int down = 0;
    int x;
    unsigned long currentMillis;
    unsigned long previousMillis = 0;

    void setup() {
      pinMode(LED, OUTPUT);
    }

    void loop() {
      currentMillis = millis();
      if (currentMillis - previousMillis >= DELAY && up == 1) {
        analogWrite(LED, x);
        x++;
        previousMillis = currentMillis;
        if (x == 256) {
          up = 0;
          down = 1;
        }
      }
      if (currentMillis - previousMillis >= DELAY && down == 1) {
        analogWrite(LED, x);
        x--;
        previousMillis = currentMillis;
        if (x == 0) {
          up = 1;
          down = 0;
        }
      }
    }

title: Why doesn't analogWrite() work

Answers: 1

body:
The constructor in your `Pwm` class declares a local variable `LED` which it sets equal to the parameter `led`. You use the member variable `LED` in other methods, so you probably meant to set the member variable of the same name, not create a local.

Remove the `int` from before `LED = led` in the constructor.


body:
I [read][1] [exist][2] [articles][3] about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:

     SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
     bluetooth.begin(57600);
     while (!bluetooth.available()) {}
     byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!

  [1]: https://arduino.stackexchange.com/questions/21514/how-to-receive-data-via-bluetooth-on-an-arduino-101
  [2]: https://forum.arduino.cc/index.php?topic=370123.0
  [3]: https://www.arduino.cc/en/Tutorial/Genuino101CurieBLECallbackLED

title: CurieBLE receive data without pairing

Answers: 1

body: HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.


body: So I am working on a ground surveillance robot using Arduino for coding the Gps, motors and ultrasonic sensors and coding in raspberry Pi for facial recognition but now what I want to do is when my robot has gotten to its final waypoint and has stopped it should excute the python file that does the facial recognition by calling it in the Arduino  sketch but I don't know how to do it would be nice if someone could please help me out I appreciate your help in advance thank you

title: Communication between Arduino and raspberry Pi

Answers: 1

body:
You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.

The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).

How you arrange those instructions to get it to do things is entirely up to you.


body:
I have a project Im currently busy with that I need a lot of help with.

What I want to do i create a flat 8x12 grid of LEDs and be able to control each individual LED independently from the others. I want to make "animations" for it (for now Im jut gona patch HIGH LOW through to the LEDs, but Im planning on making a full fledged program later on).

I saw guys on youtube creating LED cubes using the "column and row" technique, but Im not sure if that will work for me because I want to control each one independantly. Thats when my search led me to Shift Registers. Which will work best?

How would I manage the current for all the LEDs

Thank for taking the time to listen to a n00b like me :D

title: Controlling a LED array from Arduino NANO

Answers: 2

body:
You can control a grid of 8x12 LEDs using 8+12 (20) GPIO pins if your chosen board has that many. If it doesn't you can use a 3-to-8 decoder (e.g., 74HC138 - active low outputs, ideal for driving a P-channel MOSFET for the anodes of each row) to reduce that to 3+12 (15). You could cascade two of them and rotate the arrangement so it's 8+4 (12), though that's harder to do (although you can get 4-to-16 decoders too which would be simpler).

For multiplexing you don't want to use shift registers, they're too slow for smooth updates. You also don't want to drive each LED individually when you're working with that quantity, it just gets unmanageable and the power consumption would be excessive.

If you wanted to use shift registers you could use one (or multiple cascaded) to clock a single bit along them to select each row in turn. You could then reduce the pin requirement to 8+3 (clock + data + reset) though that gets a little more complex to program.

And yes, before you ask, you can address individual LEDs in the grid with multiplexing. You select one individual row (or column, but I'll just say row from now on) at a time and tell it which LEDs to light on that row, then move to the next row. This is why using a 3-to-8 decoder is good because it can only activate one row at a time which is what you want when multiplexing.

body:
There are a lot of ways to do what you want to do. Wiring them up individually would be one possibility those find a chip with that many pins can be a challenge

You can use shift registers, either statically or dynamically.

You can also use display drivers, like 7219 or the ht variants.

...

End of the day it will depend on your application and constraints it has to live under.


body:
These are my remote server credentials that I want to connect from my local device.

    Server  m12.cloudserver.com
    User  <myname>
    Password  <mypassword>
    Port  19999
    _ or
    api_key 5678909876-009-00d

I want to use the WiFiClient client() API as shown, but where or how do I include the User credentials ? so that I can make a successful connection to the remote server from my device connected over Wifi.

Cut and paste from my Arduino code.

    const int httpPort = 19999;
    if (!client.connect("m12.cloudserver.com", httpPort)) {
     Serial.println("connection failed");
     return;
    }

title: How to include userid, pass to WifiClient connect() api

Answers: 1

body: WifiClient provides low level tcp connection. Your server seems to be implementing a REST API interface. Thus you need to construct HTTP headers (GET, POST, etc.) manually as a string. Then you can add your credentials. Before doing so, try to use your server, I mean call api's with the program named `Postman`. Postman runs on Chrome browser. `Postman` can compose such headers for you. Then you can insert them into your arduino code.


body:
/How Can i Sort this Array with Descending Order? I need Simplest syntax to use in iterative code.

    lt[6]={35,15,80,2,40,110};

title: How to Sort Elements of Array in Arduino Code?

Answers: 1

body:
As mentioned in the comments, `qsort` is a good option:

    // qsort requires you to create a sort function
    int sort_desc(const void *cmp1, const void *cmp2)
    {
      // Need to cast the void * to int *
      int a = *((int *)cmp1);
      int b = *((int *)cmp2);
      // The comparison
      return a > b ? -1 : (a < b ? 1 : 0);
      // A simpler, probably faster way:
      //return b - a;
    }

    void setup() {
      // The array
      int lt[6] = {35, 15, 80, 2, 40, 110};
      // Number of items in the array
      int lt_length = sizeof(lt) / sizeof(lt[0]);
      // qsort - last parameter is a function pointer to the sort function
      qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
      // lt is now sorted
    }

    void loop()
    {
    }


body:
This is my first project using bluetooth module HC-05.i am using two of this module.one is with arduino nano(slave) and another one is with arduino uno(master).I have paired them through AT commands .
for testing,i was giving a pulse in pin 7 on nano.if there is a pulse,then slave will send character "1".if not then it will send "0".

in UNO there is an LED connected with pin 13.if master receives '1',then LED will on and if recieves '0',LED will remain off.
here is my source code ----------

slave code=>
[![enter image description here][1]][1]

master code=>
[![enter image description here][2]][2]

the Arduino IDE isn't showing any bug,but code is not working at all.though,i am giving pulse in pin 7 on NANO, the LED in pin 13 on UNO is remaining off.i am at aloss now.please help me as soon as possible..

  [1]: https://i.stack.imgur.com/Fsxzr.png
  [2]: https://i.stack.imgur.com/lPMSM.png

title: How to work with arduino softwareserial communication using HC-05?

Answers: 1

body:
Don't put pictures of you code in a post again, makes life very difficult!

The problem is the first line of the slaves loop

    loop()
    {
        if (slave.available()>0)  // Here is the bug
    ....

So If the "slave" serial port has data available to read then write data.  The master never writes to the slave so the slave never has any data to write, so your slave never sends any data and your master never reads any data.

In short remove that line and it will work.


body:
I've just bought two of these wifi modules in the hope of setting up some sort of sensor network. Please could somebody recommend a good library for the arduino.

Cheers

[![My ESP module][1]][1]

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

title: ESP 8266-01 Library

Answers: 1

body:
You don't need a library.  At the most basic level you fire AT command to it via a serial connection, but that's like using a Ferrari to go grocery shopping once a week.

It has a 80/160MHz processor 10 digital and one analog port (although you got the version where only one digital port is exposed).  You can program it through the Arduino IDE (You need to go to the board manager to download the BSP for it).  Then like Majenko says, it should be talking to the Arduino (over I2C or SPI) and treating the Arduino is the GPIO expander.


body:
Is it possible to use a name instead of a number to address an array? I was reading about enum lists and thought it might be possible.
ie
int array[3] = {something, somethingElse, somethingMore]

array[second] => somethingElse

I am asking as I have an array looking after flags for several functions and would like to be able to use the function name instead of a number to address the array.

    bool flag[6] = {1, 1, 1, 1, 1, 0}; // Power, Jump 3, Jump 7, Fade 3, Fade 7, Pause active

title: Array Addressing

Answers: 1

body:
No, but you can use a `struct`:

    struct flags {
        uint8_t power;
        uint8_t jump3;
        uint8_t jump7;
        .... etc ....
    };

    struct flags myFlags;

    myFlags.power = 1;
    if (myFlags.jump3) {
        .... stuff ....
    }

Or you can continue to use a simple numeric array and assign names to the numbers, either with `#define`, `const` variables, or an `enum`.

    enum flags {
        power, jump3, jump7, fade, fade7, pause
    };

    bool flag[6] = {1, 1, 1, 1, 1, 0};

    flag[power] = 1;
    if (flag[jump3]) {
        .... whatever ....
    }


body:
I previously created a sound installation using contact mics and computer (ableton+max msp) where sound would be triggered when people touched/tapped on the object/surface. Now I want to do something similar but want to get rid of the computer as it will be at a night club space where people will be walking around so I don't want to leave the computer there.
What I exactly want to do is to be able to load some sounds into arduino and again use contact mic on the object and when people touch it, the sound will be triggered. I know it won't be as creative as doing it with ableton where there is live-editing possibility but I'm happy with one type of sound in this one. I can probably find some codes here and there but I'm not sure what I exactly need to use to be able to do this.
I have few uno boards and lots of other bits that I've collected but haven't used before, so I would be very happy if you could help me as a novice.

Thank you

title: Triggering Sound - Arduino + Contact Mic

Answers: 2

body:
If you're asking what kind of sensor you'll need, look for capacitive sensors or there's even this instructable that could be implemented with a conductive material (see link below).

You can definitely do this project without a computer, you just need to figure out the following things:

1) Power consumption - How much current will your Arduino, speaker, sensors, etc use? Calculate your "mAh" from this and determine what kind of battery (my recommendation) will fit your needs.

2) Housing for the arduino+circuitry. If you're doing this in a nightclub you want this to be waterproof/somewhat durable.

3) SD card shield/adapter to store the sounds you want.

I have lots of experience as a hobbyist so please do not hesitate to ask for more questions. Good luck!!

Link to instructable: https://www.instructables.com/id/DIY-Touch-Sensor/

body:
I'm using piezzos too, for making art installations, and I used max-msp too, but I don't like it too much.
It's a whole new world change from the computer to the Arduino. Because it's not only the code, you must deal with electronic components I'm quite a novice too and I don't know how much you know about music and electronic components so maybe I say things wrong or that you already know, but I will say:

 - AC Adapter

I will use an AC Adapter better than batteries, because the batteries will run out in a couple of hours and in a night club almost for sure you will have access to some power extension. Arduino usually works with 9v 1A, but it'll go for 2A.

 - Music Shield

And you need a music shield, you can buy a cheap one, but I recommend the Adafruit ones, because they come with a lot of more information, and more people are working with them, but they're usually more expensive. With the music shield you need a SD card. Arduino don't have enough memory so you need a music shield with a SD card to storage the sounds.

 - Speakers and amps

and finally the speakers, it depends in what kind of speakers are you using, if you're using a big ones like some Yamaha MSP you will need and amplifier,  but if you're using little ones like 8ohm 0.25W with the music shield will be enough

 - some kind of box

you will need to put the Arduino in some kind of box, and I will secure it in the wall and not in the ground


body:
When I compile this code I get a  error: 'currentState' was not declared in this scope.

The code:

    enum state: int
     {
      NOTREADY,
      WAITSTARTUP,
      WAITSECRET,
      REVEALSECRET
     }

    state currentState; <---- Error

    const int BUTTONPIN = 4;
    const int ROTARYPIN = A0;

    void setup()
    {
      //Open Serial Monitor for debugging purposes
      Serial.begin(9600);

      //Configure the pins
      pinMode(BUTTONPIN, INPUT);
      pinMode(ROTARYPIN, INPUT);

      //Initialise the LCD
      lcd.begin(16, 2);

      //Assume that the current state is wait for start up signal

      currentState=WAITSTARTUP;
    }

title: Variable was not declared in this scope

Answers: 2

body:
You have missing semicolon after the enum:

    enum state: int
     {
      NOTREADY,
      WAITSTARTUP,
      WAITSECRET,
      REVEALSECRET
     };  // <-- here

body:
//go the Tools > Boards and check that you have selected the right option of your hardware? your remaining code is almost ok. But remember to add semicolon ";" sign at end every coding line.

      enum state: int{NOTREADY,WAITSTARTUP,WAITSECRET,REVEALSECRET};
      state currentState; //<---- Error

      const int BUTTONPIN = 4;
      const int ROTARYPIN = A0;

      void setup()
      {
        //Open Serial Monitor for debugging purposes
        Serial.begin(9600);

        //Configure the pins
        pinMode(BUTTONPIN, INPUT);
        pinMode(ROTARYPIN, INPUT);

        //Initialise the LCD
        lcd.begin(16, 2);

        //Assume that the current state is wait for start up signal

        currentState=WAITSTARTUP;
      }


body:
I'm new to the Arduino world and am working on a sketch to run a servo up and down with a spdt switch.
 My code is :

    include #include<Servo.h>
    int pos = 0;

    Servo myservo;
    void setup() {
      pinMode(2, INPUT);
      pinMode(3, INPUT);
      myservo.attach(9);
    }
    void loop() {
      if (digitalRead(2) == HIGH && pos < 180) {
        pos++;
        servo.write(pos);
        delay(15);
      }
      if (digitalRead(3) == HIGH && pos > 0) {
        pos--;
        servo.write(pos);
        delay(15);
      }
    }

 When I compile I get the "unexpected primary-expression before ';' token" error with exit status 1.

What am I doing wrong???

Answers: 1

body:
**1)** You should be using:

    myservo.write(pos);

instead of

    servo.write(pos);

for all of your  methods.

**2)** Change:

    include #include<Servo.h>

to

    #include <Servo.h>

**This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)**

*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

    #include <Servo.h>

    int pos = 0;

    Servo myservo;
    void setup() {
     pinMode(2, INPUT);
     pinMode(3, INPUT);
     myservo.attach(9);
    }
    void loop()
    {
      if ( (digitalRead(2) == HIGH) && (pos < 180)) {
        pos++;
        myservo.write(pos);
        delay(15);
      }
      if ( (digitalRead(3) == HIGH) && (pos > 0)) {
        pos--;
        myservo.write(pos);
        delay(15);
      }
    }


body:
I am using Codeblocks with arduino IDE to simulate the control of a stepper motor, and the errors "'analogRead' was not declared in this scope" and "'A0' was not declared in this scope" keep popping. The code follows:

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

    #include <Stepper.h>

    const int stepsPerRevolution = 200;
    Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
    int stepCount = 0;  // number of steps the motor has taken

    void setup() {
    }

    void loop()
    {
        int sensorReading = analogRead(A0); //ERROR

        int motorSpeed = map(sensorReading, 0, 1023, 0, 100);

        if (motorSpeed > 0)
        {
            myStepper.setSpeed(motorSpeed);
            myStepper.step(stepsPerRevolution / 100);
        }
    }

EDIT: Sorry I forgot to mention it clear, but I do not own a board, that's why I'm trying to simulate it on PC.

title: error: 'analogRead' was not declared in this scope

Answers: 1

body: // yours code looks Ok, but i think problem is with Arduio IDE setting. Go to the "Tool > Boards...." in arduino IDE and make it sure that you have selected the right option of Arduino module. Mean it is same as you are using in hardware?


body:
I'm trying to use an Arduino Uno, to measure the Voltage over a Resistor in a circuit. I guess the usual way would be to connect GND to one side of the Resistor and the AD0 Pin to the other end, and scale the (0..1023) to (0..5V).

The problem is however, that connecting the GND to one side of the Resistor affects the circuit. Since the GND of Arduino is also connected to a Servo Driver (and other stuff), Some of the power that was supposed to be consumed by my Resistor, is now consumed by the parallel circuits.

Is there any way to measure the Voltage over the resistor without using GND?

title: Uno - measure the voltage, NOT connecting GND

Answers: 2

body: If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .

body: Why you are using AD0 pin for analog read? use A0-A7 for Arduino mega and A0- A5 for arduino uno case for reading of analog values. For more detail study the voltage devider and you will understand the problem more easily. As i understand there is no need to use ground.


body:
I have edited the adafruit ST7735 library so that it supports esp-32.I made some edits in Adafruit_ST7735.h file. which are as follows.

[![the definitions for esp32 should be added as in the picture bellow][1]][1]

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

The code works fine but I had expected the screen to work faster with esp-32(due to higher processing power) but it does not do that.

I checked the time for fill screen operation for esp-32 and arduin mega. They come out to be almost the same. (around 0.12 seconds). Can anyone explain why this is happening and can I increase the speed?

title: ST7735 display with esp32

Answers: 1

body:
The ST7735 uses SPI to communicate. It will always be slow compared to parallel connected screens.

The fact that you appear to be using bitbanged SPI (manually toggling IO pins) makes it even slower.

The fastest you will be able to get with that screen will be to use hardware SPI instead (which most likely limits which pins you can use - I am not familiar with the ESP32 though) but that will still be somewhat slow.

If you want really high speed screen updates then you will need a parallel interface screen, ideally a 16-bit parallel interface screen. However, for that you need around 20 IO pins to drive it.


body:
I'm going through problem in Arduino code. I have three Arrays and want to convert them into a matrix. I have tried hard but couldn't solve issue.

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
    float Loadbase,Loadshift;

    void setup() {
        for (int i=0;i<24;i++){
            Loadbase={lb1[i],lb2[i],lb3[i]};
        }
    }

    void main() {
    }

title: Conversion of Arrays into Matrix?

Answers: 2

body:
Two dimensional arrays in C++ (directly):

    float matrix[3][24] = {
        {1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730},
        {1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450},
        {500,500,600,600, 380.3005 ,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250}
    };

Two dimensional array indirectly (array of pointers):

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
    float * matrix[3] = {lb1, lb2, lb3};

If you want two dimensional array with copies of lb1/lb2/lb3:

    float matrix[3][24];
    for (int i = 0; i < 24; ++i) {
        matrix[0][i] = lb1[i];
        matrix[1][i] = lb2[i];
        matrix[2][i] = lb3[i];
    }

Btw: you were saying something about "mistakes" if I split definition on more lines, but guess what:
`float lb3[24]={500,500,600,600,  380.3005  ,3155`. This is a valid float number, but you have only 23 items then.

If you use at least space as a number separator, it can't be even compiled:

    float lb3[24] = { 500, 500, 600, 600, 380. 3005, 3155, 530, 400,  400, 600, 350, 250, 250, 500, 500, 250, 1655, 1655, 3155, 2130, 250, 150, 250};

body:
Check this code with slight amendments:

    float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
    float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
    float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};

    void setup() {
    int loadbase[3][24] = {{lb1}, {lb2}, {lb3}};
    void main()
    {}


body:
I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.

    volts = analogRead(A3);    // read the input pin
    Serial.println(volts)

title: How to Read Voltage Level?

Answers: 2

body:
//use this syntax and add ; sign at end of each line and try to read voltage level via voltage divider circuit.

    volts = analogRead(A3);    // read the input pin
    Serial.println(volts);             // debug value

body:
First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.

    float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!


body:
I have 2 Arduinos, mounted with Xbee Shield and Xbee S1 module on each.
One arduino is mounted on car chassis while another is connected with PC. Our AIM is to send signal from the arduino connected on PC and the motor will be controlled by the Arduino connected on car chassis.
Here is the code of the arduino connected with PC:

    char msg= "";
    void setup(){
     Serial.begin(9600);}

    void loop(){
     msg=Serial.read();
     serial.println(msg);
    }

Here is the code of the Arduino on car chassis:

    char msg = ' ';
    int motorA1 = 2;
    int motorA2 = 3;
    int motorB1 = 4;
    int motorB2 =5;

    void setup() {
      pinMode(motorA1, OUTPUT);
      pinMode(motorA2, OUTPUT);
      pinMode(motorB1, OUTPUT);
      pinMode(motorB2, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      while(Serial.available()>0){
      msg=Serial.read();
      switch(msg){
       case 'f':Serial.println("Forward");break;
       case 'b':Serial.println("Backward");break;
       case 'r':Serial.println("Right");break;
       case 'l':Serial.println("Left");break;
       case 's':Serial.println("Stop");break;
     }
    if(msg=='f'){
      digitalWrite(motorA1,HIGH);
      digitalWrite(motorA2, LOW);
      digitalWrite(motorB1,HIGH);
      digitalWrite(motorB2,LOW);
      Serial.println("Running Forward");
      }
    if(msg=='b'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,HIGH);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,HIGH);
      }
    if(msg=='s'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,LOW);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,LOW);
      }
    if(msg=='r'){
      digitalWrite(motorA1,HIGH);
      digitalWrite(motorA2, LOW);
      digitalWrite(motorB1,LOW);
      digitalWrite(motorB2,LOW);
      }
    if(msg=='l'){
      digitalWrite(motorA1,LOW);
      digitalWrite(motorA2,LOW);
      digitalWrite(motorB1,HIGH);
      digitalWrite(motorB2,LOW);
      }
    }
    }
Now our next AIM is to send back a feedback from car to the Arduino terminal of PC, e.g. if we are giving 'f' as a input and we get a reply 'Running Forward' on the next line. What line of code should we incorporate for that?

title: Communicating between two arduino terminal using Xbee

Answers: 1

body:
//your code looks almost ok. The thing that i am feeling wrong is that arduino at the PC end. It should communicate with PC and 2nd arduino at the same time. So use arduino mega or "#include <SoftwareSerial.h>" library to avail extra Serial at this end if you are using arduin uno. Your code will be like this..

    char msg= "";

    void setup(){
    Serial.begin(9600);
    Serial1.begin(9600)//<----error
    }

    void loop(){
     msg=Serial.read();
     serial1.println(msg);//<- - -error
    }


body:
I've written a function that heavily relies on the If / Else statement but I feel it's a very beginner way to achieve functionality. Are there any better ways to achieve the same functionality?

Code:

    void jumpThree() // Update from left then right
    {
      if (effectCounter[0] < tiles) // Right, first tile
      {
        Serial << flag[6] << "\t";
        Serial << newRed[0] << " " << newGreen[0] << " " << newBlue[0] << "\t";

        if (flag[6] == 1)
        {
          oldRed[0]   = (tileBuffer[effectCounter[0]] & 0xff0000) >> 16;
          oldGreen[0] = (tileBuffer[effectCounter[0]] & 0x00ff00) >> 8;
          oldBlue[0]  = (tileBuffer[effectCounter[0]] & 0x0000ff);

          Serial << effectCounter[0] << "\t";
        }

        else if (flag[6] == 0)
        {
          oldRed[0]   = (tileBuffer[6 - effectCounter[0]] & 0xff0000) >> 16;
          oldGreen[0] = (tileBuffer[6 - effectCounter[0]] & 0x00ff00) >> 8;
          oldBlue[0]  = (tileBuffer[6 - effectCounter[0]] & 0x0000ff);

          Serial << (6 - effectCounter[0]) << "\t";
        }

        Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

        if ((newRed[0] - oldRed[0] != 0) || (newGreen[0] - oldGreen[0] != 0) || (newBlue[0] - oldBlue[0] != 0))
        {
          // Red difference
          if (newRed[0] - oldRed[0] > 0) // Positive red change
          {
            oldRed[0] ++;
          }
          else if (newRed[0] - oldRed[0] < 0) // Negative red change
          {
            oldRed[0] --;
          }

          // Green difference
          if (newGreen[0] - oldGreen[0] > 0) // Positive green change
          {
            oldGreen[0] ++;
          }
          else if (newGreen[0] - oldGreen[0] < 0) // Negative green change
          {
            oldGreen[0] --;
          }

          // Blue difference
          if (newBlue[0] - oldBlue[0] > 0) // Positive blue change
          {
            oldBlue[0] ++;
          }
          else if (newBlue[0] - oldBlue[0] < 0) // Negative blue change
          {
            oldBlue[0] --;
          }

          if (flag[6] == 1)
          {
            tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
          }

          else if (flag[6] == 0)
          {
            tileBuffer[6 - effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
          }

          // tileBuffer[effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
        }

        else if (((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0) && ((newRed[0] - oldRed[0]) == 0))
        {
          effectCounter[0] ++;  // Go to next tile
          //flag[1] = false;
        }
      }

      else
      {
        flag[1] = false;
        effectCounter[0] = 0;

        if (flag[6] == 1) // Flip flop between left and right updates
        {
          flag[6] = 0;
        }

        else if (flag[6] == 0)
        {
          flag[6] = 1;
        }
      }
      delay(wait);
    }

title: If Else Alternative

Answers: 4

body:
No, if-else is really the simplest way of dealing with that.

If you wanted to abstract it a little since you have repeated code just with separate variables, you could make a little function

    // Note: set the right parameter variable types here
    // to match your unspecified variables.
    static inline int testUpDown(int a, int b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
    }

    // Inside your flag tests:
    oldRed[0] = testUpDown(newRed[0], oldRed[0]);
    oldGreen[0] = testUpDown(newGreen[0], oldGreen[0]);
    oldBlue[0] = testUpDown(newBlue[0], oldBlue[0]);

If you wanted an inline conditional variant you could do it with this:

    oldRed[0] = ((newRed[0]-oldRed[0]) ? ((newRed[0]-oldRed[0])/abs(newRed[0]-oldRed[0])) : 0);

But who can understand that?  You could always macro it:

    #define UPDOWN(A,B) (((A)-(B)) ? (((A)-(B)) / abs((A)-(B))) : 0

    oldRed[0] = UPDOWN(newRed[0], oldRed[0]);

body:
you can shorten a lot of the vertical space with more compact conditionals, including ternaries to remove double conditionals where one result must follow from another.

For example, you can turn this:

      // Green difference
      if(newGreen[0] - oldGreen[0] > 0)  // Positive green change
      {
        oldGreen[0] ++;
      }
      else if(newGreen[0] - oldGreen[0] < 0) // Negative green change
      {
        oldGreen[0] --;
      }

into just this:

    // Green difference
    int gDiff = newGreen[0] - oldGreen[0];
    if(gDiff) oldGreen[0]+= (gDiff > 0) ?  1 : -1;

body:
For part of this you can use the switch case style
Which looks like

    switch(flag[6]) {
        case 0  //your code here
                 break;       // and exits the switch
        case 1 : cout << '2';
                 break;
        default: //all other cases
    }
There is also the ? syntax that can help

> condition ? result_if_true : result_if_false

If I "refactor" this type of code (really we all get there from time to time) I try to go back to "what I want". From What I understand your code would look like (no code validation this is a educational example)

    int bufferoffset=0;
    int bufferMultiplyer=1;

    if(flag[6] == 0)
    {
       bufferoffset=6;
       bufferMultiplyer=-1;
    }
    oldRed[0]   = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0xff0000) >> 16;
    oldGreen[0] = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x00ff00) >> 8;
    oldBlue[0]  = (tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] & 0x0000ff);

    Serial << (bufferoffset+bufferMultiplyer*effectCounter[0]) << "\t";

    Serial << oldRed[0] << " " << oldGreen[0] << " " << oldBlue[0] << endl;

    int redDiff=newRed[0] - oldRed[0];
    int greenDiff=newGreen[0] - oldGreen[0] ;
    int blueDiff=newBlue[0] - oldBlue[0] ;
    if(redDiff!= 0)
    {
      redDiff > 0?         oldRed[0] ++:   oldRed[0] --;
     }
    if(greenDiff!= 0)
    {
      greenDiff> 0?         oldGreen[0] ++:   oldGreen[0] --;
     }
    if(blueDiff!= 0)
    {
      blueDiff> 0?         oldBlue[0] ++:   oldBlue[0] --;
     }

        tileBuffer[bufferoffset+bufferMultiplyer*effectCounter[0]] = tile.Colour(oldRed[0], oldGreen[0], oldBlue[0]);
    }

for more details on switch case see http://en.cppreference.com/w/cpp/language/switch
for more detail on ? syntax https://stackoverflow.com/questions/795286/what-does-do-in-c

body: //when there are multiple if/if-else/nested if/nested if condition then obviously it creates complexity in the code. I think switch is best option to use in such conditions. plz check switch condition if it is feasible in your program. Moreover i will check it in detail if it still not works. Try.........


body:
I'm currently trying to create my own Attiny85 usb thumb(to mimic an joystick). I understand that I have to limit the voltage on the attiny's pins that are connected to the D+/- pins from the usb. In various schematics there are some pull-up resistors used with some zener diodes(that will drop the voltage that exceeds 3.3 V).[![enter image description here][1]][1](taken from [insidegadgets][2])

# Question:
# \#1
I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid an regulator?(as other schematics incorporate in them)

# \#2
Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

# \#3
An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.007=171 ohms.That resistor attached to the attiny **would** produce a 1.2 drop).

# \#4
There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

  [1]: https://i.stack.imgur.com/7h7Td.png
  [2]: https://www.insidegadgets.com/2011/05/08/playing-around-with-v-usb-for-avr/

title: Understanding schematics: resistors attached to Attiny85 pins V-USB

Answers: 1

body:
> I am sure most computers these days have a voltage regulator built-in them(everyone can just plug the usb into the 220v socket...).Can then I just avoid the regulator?

If you have a 5v supply, as in a USB connection, and you want to run off 5v, then you do not need any regulator.

> Why is there one pull-up resistor on pin2 only(pin2 from usb)? That is D- pin.

Because only that pin needs pulling up to indicate the presence of a device on the USB bus.

> An resistor can already limit the voltage.Why need zener diodes?(eg.: attiny85 draws ~7mA at 16.5 MH and 5v. And we need a resistance that would drop the 5v from one pin-considered in HIGH state- to 3.3v...that is a 1.2v drop.So R=1.2/0.7=1.71 ohms).

You can only use a resistor to drop a fixed voltage of you have a fixed current. The current you quote is the chip's supply current, not the GPIO current, which you cannot know or predict. Also, if you did use a resistor it would operate both ways and the 3.3V coming in would also be reduced so the MCU will not be able to read the data.

Even if you did know the current you would find it was very small so a huge resistor would be needed, which would induce intolerable amounts of noise. It would also violate the USB specifications.

> There are two zener diodes attached to D+/- pins. What's with the resistors?(R2/R1) They limit..the current(didn't know the pc is so sensitive..)?

They are to protect the ATTiny's IO pins. Without those the zener diodes will sink way too much current from the IO pins and damage them. They also act partially as termination resistors for the USB bus (which should be 20Ω).


body:
I've connected to RS232 device with arduino. When showing data in arduino its showing as:

    235
    157
    191
    157
    159
    153
    157
    0

While in Hyperterminal it's showing as:

     101 102 103 104

How to get the same data as hyperterminal in arduino too?

My Arduino code:

       if (RS232.available()) {
        int incomingByte = RS232.read();

        Serial.println(incomingByte);

        //Sending to bluetooth
        BTserial.println(incomingByte);
      }

title: Different data showing in arduino serial and hyperterminal

Answers: 0


body:
*EDIT*: Here are the links to the sensor spec sheet (http://www.omega.com/temperature/pdf/HX71.pdf) and manual (http://www.omega.com/Manuals/manualpdf/M4543.pdf) for your reference.

I'm using a relative humidity (RH) sensor with an Arduino Mega. The RH sensor runs off of +/- 24V  (which is being sourced by a power supply), and outputs a signal from 0-5VDC. Naturally, I am plugging this output signal into my A0 channel. There is a bare Earth Ground wire that is wired to the power supply's earth ground (possible error?) **Arduino's GND is connected to the power supply's EARTH GND, fyi**.

I compared the voltage reading in my Arduino Serial Monitor to a reliable Fluke multimeter, and **the analog input channel is adding ~.2 Volts!**

From some research, I have read about "high impedance" "source impedance" "internal wiring of Arduino" etc, but unfortunately I am failing to grasp the reason *why* this is happening. I'd like to know so then I could figure out a solution on my own.

Below is a schematic of what I'm dealing with so that it may better illustrate my issue (also my code). Thank you for your time, and I appreciate your help!

[![Error drawn out.][1]][1])

    void setup()
    {

    Serial.begin(9600);

    }

    void loop()
     {

      float hs1 = ((( analogRead(A0) * ( 5.0 / 1024.0) ) )* 20.0 );

      Serial.print("RH%");
      Serial.print(":");
      Serial.print(hs1);
      Serial.print(";");
      Serial.println();
      delay(1000);

    }

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

title: Why is my Analog Input channel adding voltage to my signal?

Answers: 1

body:
Wow, you guys are gonna get a KICK out of this!

The analog input channel was **not** adding millivolts to my Analog Input signal. I stupidly was not supplying my Arduino Mega with 9V!! I had it running off of the USB port, which was affecting my 5V reference (thank you @majenko for pointing that out!).

I measured the 5V pin and it was fluctuating between 4.41-4.21 volts. My colleague made a comment and I reviewed the Arduino Mega datasheet. It must be supplied with 7-12 volts in order for the 5V to output correctly.

Once I hooked my Power Vin + GND to my power supply, set that at 9V/.08amps my analog input readings were accurate.

**Thank you everyone for your help!**


body:
I am making a pid line follower robot. So I was tinkering with code to optimize my line follower when i removed two lines of code unknowingly. As soon as I uploaded my code and started the line follower, 4 mosfets on my motor driver smoked and burst into blue flames. Bought a new one and same outcome. Interestingly, The ones corresponding to the left motor alone had this outcome as I removed " return Motorspeed1" and " return MotorSpeed2" from the function corresponding to the left motor. Heres the code :

    signed int MotorSpeed = 70;
    int MotorSpeed1, MotorSpeed2;
    int MotorFunc(signed int a, signed int b){
       if(a >= -10 && a < 0)
       {
          b = -b;
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_dir_m1, HIGH);
          digitalWrite(_dir_m2, LOW);
          MotorSpeed1 = MotorSpeed + b;
          MotorSpeed2 = MotorSpeed + b;
          MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
          MotorSpeed2 = constrain(MotorSpeed2, 0, 255);
          analogWrite(_pwm_m1, MotorSpeed1);
          analogWrite(_pwm_m1, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }
       if (a < 10 && a > 0)
       {
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m2, LOW);
          digitalWrite(_dir_m1, LOW);
          digitalWrite(_dir_m2, HIGH);
          MotorSpeed1 = MotorSpeed+ b;
          MotorSpeed2= MotorSpeed+ b;
          MotorSpeed1 = constrain( MotorSpeed1, 0, 255);
          MotorSpeed2= constrain( MotorSpeed2, 0, 255);
          analogWrite( _pwm_m1,  MotorSpeed1);
          analogWrite( _pwm_m2, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }

       else
       {
          digitalWrite(_brk_m1, LOW);
          digitalWrite(_brk_m2, LOW);
          digitalWrite(_dir_m1, HIGH);
          digitalWrite(_dir_m2, HIGH);
          MotorSpeed1 = MotorSpeed+ b;
          MotorSpeed2 = MotorSpeed - b;
          MotorSpeed1 = constrain(MotorSpeed1, 0, 255);
          MotorSpeed1 = constrain(MotorSpeed2, 0, 255);
          analogWrite( _pwm_m1, MotorSpeed1);
          analogWrite( _pwm_m2, MotorSpeed2);
          return MotorSpeed1;
          return MotorSpeed2;
       }

    }

And i called this function in the code using :

        MotorFunc(a,b)

This code ran just fine, But when i removed the return functions from the first if condition, I destroyed 2 motordrivers,
Is this possible?
Edit:
I am updating the whole code:

The main code tab :

         int _dir_m1 = 2;
         int _pwm_m1 = 3;
         int _brk_m1 = 4;
         int _brk_m2 = 5;
         int _pwm_m2 = 6;
         int _dir_m2 = 7;

         int sen1 = A4;
         int sen2 = A3;
         int sen3 = A2;
         int sen4 = A1;
         int sen5 = A0;
         signed int Error = 0;

         int Kp = 20;
         int Ki = 0;
         int Kd = 0;

         void setup() {
         pinMode(_dir_m1, OUTPUT);
         pinMode(_pwm_m1, OUTPUT);
         pinMode(_brk_m1, OUTPUT);
         pinMode(_dir_m2, OUTPUT);
         pinMode(_pwm_m2, OUTPUT);
         pinMode(_brk_m2, OUTPUT);

         pinMode(sen1, INPUT);
         pinMode(sen2, INPUT);
         pinMode(sen3, INPUT);
         pinMode(sen4, INPUT);
         pinMode(sen5, INPUT);

         }

         void loop(){

         signed int a = Sensors();
         signed int b = PID(a);
         MotorFunc(a,b);
           }

And pretty much it. I am leaving out PID as Its not required along with error selection.

The setup is -
Arduino mega connected to 5 ir sensors
12v 9ah battery
500rpm 12v motors johnsons
and the motor driver 20 amp 20v-30v
[![Motor Driver which burst into flames][1]][1]

[Motor driver link with specs][2]

  [1]: https://i.stack.imgur.com/ZFDYr.jpg
  [2]: http://robokits.co.in/motor-drives/dual-dc-motor-driver-20a

title: Can removing lines of code destroy a motor driver and make it catch fire?

Answers: 2

body:
It all depends on how the circuit works and how it is controlled.  A basic H-bridge looks like this:

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

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".

However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.

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

body: It isn't possible to say arbitrarily that removing the statements could or could not cause the drivers to burn out. What does the caller do with the value returned by your function? With the return statement removed, the value returned to the caller is unknown. Is there any value which, if returned to the caller, could set the conditions for driver burn-out?


body:
I have been using a HC-SR501 PIR module with my Arduino Mega and it was tracking presence pretty well.

Because of cost constraints, I decided to go with the low cost HC-SR505 sensor - bought a bunch of them. The performance is very bad. It almost seems like it is giving random HIGH and LOW values. Out of the 20 odd sensors I bought, may be one or two are fairly ok - others are all behaving weird. Have someone experienced this kind of behavior with HC-SR505 sensor?

Are they highly sensitive to noise in the power supply - is there any workaround to mitigate the effect? Would an RC filter across the input help?

title: Issue with PIR sensor

Answers: 0


body:
    byte RSV_Resp_test[3] = {'a', 'b', 0};
    Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));

produces the error

    error: invalid cast from type 'byte {aka unsigned char}' to type 'char'
    Serial.println(reinterpret_cast<char>(RSV_Resp_test[1]));
                                                          ^
How can this be an ill-formed cast?  I just need to print the value as a ascii character, not as a number.

title: Can't cast char to unsigned char?

Answers: 1

body:
    Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.


body:
I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?

The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

title: More speed from ATMEGA328 Internal Clock

Answers: 3

body:
It is 8MHz and not faster.
The only way to make it faster is to add an external crystal with two capacitors and change a fuse for external clock.

Many ATtiny chips can run at higher frequencies with the internal clock. Do you use a DIP package of the ATmega328(p) ?

Did you optimize the code ? The ATmega328(p) has highly optimized code to change an output pin. At what rate do you want to shift out data ?

body:
`shiftOut()` relies on `digitalWrite()`, which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing `shiftOut()` using [direct port
access](https://www.arduino.cc/en/Reference/PortManipulation) instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.

**Edit**: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being _too fast_. You may try to play with the delay value.

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

    #include <util/delay.h>

    /*
     * Especialized and faster shiftOut().
     * This assumes no one is touching PORTB at the same time.
     *
     * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
     */
    void myShiftOut(uint8_t val)
    {
        for (uint8_t i = 0; i < 8; i++)  {
            // Send data bit.
            if (val & 0x80)
                PORTB |= _BV(PB3);
            else
                PORTB &= ~_BV(PB3);
            val <<= 1;

            // Toggle clock twice.
            PORTB |= _BV(PB4);
            _delay_us(0.5);
            PORTB &= ~_BV(PB4);
        }
    }

body:
I wrote the following earlier but the moderator deleted:

"
A few things to try.

An external oscillator.

An external rc oscillator.

Optimized code: the code left a lot to be desired.

Optimized hardware: there is no reason you shift out the same value so many times. That's a waste of time.
"

edit: just give you some sense on a 16MIPS ATmega:

1) your code executed in 2.54ms -> a refresh rate of 400Hz;

2) your code software-optimized can be executed in 0.103ms -> a refresh rate of 1Khz;

3) your code both software and hardware optimized can be executed in 0.054ms -> a refresh rate of 2Khz.

what it tells you is that:

1) raising the clock isn't the only way to speed up execution;

2) there is a fundamental limit for this topology on how many shift registers you can drive before it starts to flicker;

3) to drive the most out of your design, you have to pay attention to both software and hardware. that's why embedded engineers get paid a lot of money to do;

BTW, the higher clock rate, the more likely you will run into timing issues in a long chain of shift registers. 20 - 25 shift registers are likely the limit in real life applications.


body:
I followed [the guide from the Arduino website][1], by placing a 10uF capacitor between GND and Reset. However, now the voltage regulator only provides 4v (Vin=13V). It correctly has 5V when being powered via USB.

What happened? Isn't there a 10k resistor between +5V and Reset that should prevent the chip from being overloaded? Or did the Reset pin sink the entire energy of the capacitor?

  [1]: http://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

title: Attempted to disable autoreset - now the voltage regulator only outputs 4.0v

Answers: 0


body:
    //simple alarm system
    int RipSensor1 = 12;
    int RmkeyA = 3;
    int RmkeyB = 5;
    int RmkeyC = 6;
    //--------------------------------------------------------------------------

    void setup()
     {
      Serial.begin(9600);
      pinMode(RipSensor1,INPUT);
      pinMode(RmkeyA,INPUT);
      pinMode(RmkeyB,INPUT);
      pinMode(RmkeyC,INPUT);
      pinMode(13,OUTPUT);
      Serial.println(F("System Is Up & Running")); }
      //----------------------------------------------------------------------

    void loop()
     {
      Serial.println(F("Main Loop Start"));
      digitalWrite(13,LOW);   //for debugging
      if (digitalRead(RmkeyA) == HIGH)
       {
        Rip1Status();
       }
     }
    //----------------------------------------------------------------------

    void AlarmSMS1()
     {
      //send sms to admin1
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Serial.println(F("SMS Sending to 1st ADMIN --->"));
      Rip1Status();   // return to this void (monitoring)
     }
    //----------------------------------------------------------------------

    void Rip1Status()
     {
      Serial.println(F("VOID Rip1 Start..."));
      while (digitalRead(RmkeyB) == LOW) //Arm mode
       {
        digitalWrite(13,HIGH);
        if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
         {
          Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
          long RipTimer1 = 0;
          long Rip01 = 0;
          int z = 0;
          int x = 0;
          while (digitalRead(RmkeyC) == LOW)
           {
            RipTimer1++;
            Serial.println(RipTimer1);   //for debugging
            if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
             {
              z = 1;
              Serial.println(F("1st CheckPoint OK"));
             }
            else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
             {
              x = 1;
              AlarmSMS1();
             }
           }
          Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
          RipTimer1 = 0;
          z = 0;
          x = 0;
          Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
          break;
         }
        else Serial.println(F("Monitoring"));  //for debugging
       }
      Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      loop();
     }
I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...

    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    Monitoring
    B Key Pressed --> Disarming
    Monitoring Loop ends --> GoTo Main Loop
    Main Loop Start
    3002
    3003
    3004
    3005
    3006
    3007
    3008
    3009
    3010
    3011
    3012.............
Why this happen?
What i am doing wrong?

title: Program jumps alone from void loop() to another void

Answers: 1

body:
`loop()` calls `Rip1Status()`, which calls `loop()`, which calls `Rip1Status()`, which calls `loop`(), which calls ....

That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for `Rip1Status()` to return to the main loop, delete the `loop()` call at the end of the function. When Rip1Status()` exits, control will automatically return to `loop()` at the statement following the `Rip1Status()` call.


body:
What is the simplest way to switch ON/OFF a 60v and 5 mA of current ?
I don't want the common relays for arduinos as they make click noise.

title: Switching low current AC

Answers: 1

body:
// Following devices could be helpful in you case.

1. Power BJT as a switch (check datasheets if it comes on your required range).
2. Solid state relay is obviously, but cast is little high in this case.


body: I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

title: Arduino DUE samples per second with the DAC

Answers: 2

body:
According to the datasheet:

> * 2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.

Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.

Or, if you don't *need* a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.

body:
With this code, the Arduino DUE was able to generate 250 samples per second approx. I tested it with a signal generator and an oscilloscope. I have found it on this web page http://www.electrosmash.com/pedalshield. All credit is for them.

Here is the code:

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

    // Licensed under a Creative Commons Attribution 3.0 Unported License.
    // Based on rcarduino.blogspot.com previous work.
    // www.electrosmash.com/pedalshield

    int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
    int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
    int LED = 3;
    int FOOTSWITCH = 7;
    int TOGGLE = 2;

    void setup()
    {
      //ADC Configuration
      ADC->ADC_MR |= 0x80;   // DAC in free running mode.
      ADC->ADC_CR=2;         // Starts ADC conversion.
      ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

      //DAC Configuration
      analogWrite(DAC0,0);  // Enables DAC0
      //analogWrite(DAC1,0);  // Enables DAC0
    }

    void loop()
    {
      //Read the ADCs
      while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
      in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
      //in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
      //POT0=ADC->ADC_CDR[10];                 // read data from ADC8
      //POT1=ADC->ADC_CDR[11];                 // read data from ADC9
      //POT2=ADC->ADC_CDR[12];                 // read data from ADC10

      //Add volume feature with POT2
      //out_DAC0=map(in_ADC0,0,4095,1,POT2);
      //out_DAC1=map(in_ADC1,0,4095,1,POT2);

      //Write the DACs
      dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
      dacc_write_conversion_data(DACC_INTERFACE, in_ADC0); //write on DAC
      //dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
      //dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
    }


body:
Since this is this the first time im doing Arduino, im really confused what the code is to:

write a code which reads the value(nae the value 'flexValue') of a flex sensor connected to analog input AN0.

The value should be a 10-bit integer number having value between 0-1023, inclusive.

title: How to write arduino code which reads the value of a flex sensor?

Answers: 1

body:
You should call the function `analogRead()`, and pass the value of `A0` into it because you want to read pin A0. For example:

    flexVal = analogRead(A0);
The function `analogRead()` will return a value from 0-1023, just as you require.

When you call this function, the CPU configures the on-board ADC (analog-to-digital converter) to take a reading from pin A0. The ADC on the Arduino has 10-bit resolution, so it will return a value from 0-1023.


body:
I am a newbie to the world of IoT, I want to ask...

Is it possible to connect two Ethernet shields with SPI? And if yes, how can I codes them?

I have reference from http://www.gammon.com.au/spi and I've tried SPI communication between two Arduino Unos send & receive any data type..

Now.. I want to put Ethernet Shields to each Arduino Unos, and I want to make them can communicate via SPI, It's like they can send & receive data type (ping IP address each other). If that scenario can running well, is it possible I can ping Shield one and Shield two?
(without router/switch, for this IoT research I still used local network, each Arduino w/ Shield plug to each laptop via RJ45 & USB port of course)

Topology:

    Laptop A <===> Arduino Uno w/ Ethernet Shield <---> Arduino Uno w/ Ethernet Shield <===> Laptop B.

Note:

>     <===> = RJ45
>     <---> = Wire jumper (SPI or Pin 13 12 11 10, GND)

Sorry for my bad language, I didn't speak English well..

Can anyone help me?
Thank you,

H.

title: SPI communication between two Ethernet Shields (W5100)

Answers: 0


body:
I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that?
Thank  you...

title: Is it possible to connect NRF24L01 to localhost in laptop without wifi router?

Answers: 1

body:
It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.

However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.

You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.

(By the way you won't be able to call you laptop localhost)