text:
Arduino MPU6050 not working due to LED PWM
I'm having some problem with the MPU6050 example sketch. I added a few bits of code of my own, so that my LEDs change color based on the yaw-pitch-roll. However when I try to run it, the values of the yaw-pitch-roll get all distorted, like this:
ypr -38.68  -30.05  41.34
ypr -55.42  -35.25  -31.68
ypr -101.02 23.53   -65.01
ypr 101.29  -19.63  12.81
ypr -51.97  -37.49  44.85
ypr 37.89   38.20   -37.95
ypr 72.15   -13.70  22.68
ypr 0.00    0.00    90.00
ypr -45.73  74.52   -11.89
ypr 134.36  31.89   -31.08
ypr -13.86  -21.51  3.54

And when I disable analogWrite on the LED lights the yaw-pitch-roll gives normal output again.
Below is the code for changing the LED colors.
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

Does anyone know what is going wrong here?
EDIT:
The wiring:

The code:
// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT

#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

int redPin = 11;
int bluePin = 9;

int startR = 100;
int startB = 10;

int eindR = 255;
int eindB = 255;

int gyroMin = 0;
int gyroMax = 80;
int gyroRange = 0;
float rangeR = 0;
float rangeB = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false; // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    gyroRange = (gyroMax - 10) - (gyroMin + 10);
    rangeR = (float)(eindR - startR)/gyroRange;
    rangeB = (float)(eindB - startB)/gyroRange;

    Serial.begin(115200);
    while (!Serial);

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    /*while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again*/

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
    pinMode(redPin, OUTPUT);
    pinMode(bluePin, OUTPUT);
    //digitalWrite(redPin, LOW);
    //digitalWrite(bluePin, LOW);
    setColor(100.0,100.0);
}

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));
        } else if (mpuIntStatus & 0x02) {
          // otherwise, check for DMP data ready interrupt (this should happen frequently)
         // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
            int degree = ypr[1] * 180/M_PI;
            if (degree <= (gyroMin + 10)){
              setColor(startR, startB);
            }
            if ((degree > (gyroMin + 10)) && (degree < (gyroMax - 10))){
              float calcR = (startR + ((degree-10) * rangeR));
              float calcB = (startB + ((degree-10) * rangeB));
              setColor(calcR,calcB);
            }
            if (degree >= (gyroMax - 10)){
              setColor(eindR, eindB);
            }
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}
void setColor (float red, float blue){
  int redColor = (int)255 - red;
  int blueColor = (int)255 - blue;
  analogWrite(redPin, redColor);
  analogWrite(bluePin, blueColor);
}

EDIT 2:
After a lot of testing with and without resistors and new cables (I thought there might be some sort of cable damage), it still isn't working fully. The weird thing is that when every component is hooked up via a breadboard it works (without resistors). But as soon as I try to solder everything it works randomly.
Is there a chance that the type of cable (copper vs aluminium) has any effect on this? The breadboard cables are aluminium and the soldered cables are copper.

Not without seeing both the entirety of your code and the wiring of your circuit.

@Majenko thanks for the quick reply, i uploaded a screenshot of the wiring and added the full code

Just a question. Why you pass float variable as colour? Try int. analogWrite change the value to 8bit.

Jimi just quick test. Take off LEDs and try the code if there is any difference. Also try to pass integer instead of float

Yeah did that, then the output is stable.

You have no resistors on your LEDs. The PWM signals are causing huge amounts of noise in the MCU corrupting all your data and communications.
Add resistors (say 330Ω) to each LED cathode pin (so 9 resistors).

but the led are in series, do I still need 9 resistors or just 3?

No, they aren't in series. They are in parallel. Every single LED needs a resistor, and there's 3 resistors per device, and 3 devices, so 9 resistors.

Aah right, my bad. I will try to add the resistor and will let you know if it works. thanks for all the help so far! :D

I added the resistors, but it still isn't working + now the leds are very dim (which is not what I want), what now?

The MPU board you have pictured looks like it should be powered by 5V not 3.3V.

According to the datasheet it supports 2.375V-3.46V range. So not 5v

That's the datasheet for just one of the chips on that board. The board (at least the one pictured) appears to have a 3.3V regulator (the 5-pin SOT-23 chip) that powers the MPU6050.

So if I move the MPU to the 5v will the led still get power? (also sorry for all the questions, this is all still very new to me)

Yes, you can plug in as many things as you like into a single 5V pin. Just like you wired multiple LEDs in parallel to the same IO pin.

I updated the post, after a lot of tests I'm still having issues


text:
LEDs effects changing with a button
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)?

Not if you your functions use the delay() function as part of the animations. We would need to see your entire program in order to recommend improvements.

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 foos 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 foos 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

source: Stack Exchange

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

sort: votes


text:
Arduino MotorShield code running but not motors
I have a motor shield V2 on my Arduino, i compile the codes just fine and i'm trying to just run the example dc motor test. The code compiles the serial is printing out the "tick tock ...." but the motors are not running. They ran once before on my mac though.
Using a 9v battery to power a basic Dc motor.
I'm using the right ports on pc. Same exact port for motor as the code tells. I'm not sure where i am wrong. TYIA

We are not sitting beside you and we can't look at your code over your shoulder... You know that right?
You must post your code using the appropriate formatting and describe or draw a diagram of your wiring: pictures are not helping.
How are you powering the shield?
What type of motor are you trying to drive? You spoke of motors (plural) but I believe you have only one motor connected.

Neither can we see where those wires go. This isn't Bladerunner.

My code has no errors and compiles fine. It also did work before. I'm just wondering if there is something wrong with my set up that i'm not noticing or if there are PC specific differences, since this did run fine on my mac. I Will add photos of what the wires go to.

Do i need to provide more descriptions? sorry about earlier =(

Your mac has been blessed by fairy dust and is using its supernatural powers to force your midichlorians spin the motor...
Option 1: battery voltage is not enough to spin the motor
Option 2: battery is wired the other way around
Option 3: one of those taped connections has simply got lose and circuit is open
Option 4: motor is wired the other way around
Option 5: motor is dead
Option 6: shield is dead
Option 7: arduino is dead
Option 8: the universe is playing against you
Option 9: I can keep going, the number of things you could have done wrong is probably endless

lmaooooo so helpful. Nah the motor runs more than fine when connected straight to the battery. So battery and dc motor are not dead. The battery is wired right other wise the LED would just not even go on. The taped connections are also not lose, because again the LED light would not turn on. Motor wired around or not would only change the direction of rotation and i did switch them previously just in case. Arduino is not dead as it runs other stuff just fine. Thanks anyways.

Turns out the pins connecting the shield to the Arduino are quite loose and didn't "touch" the Arduino.

That was option 42 on my list of possible failures

I had that on one Arduino once - the actual header sockets were inferior quality and some contacts didn't have the springiness they should have. I resorted to replacing all the sockets on the board. I think Arduino had a bad batch at one point in their history, since I haven't had the issue since with any other Arduino.

Using a 9v battery to power a basic Dc motor.

Don't do that.  These were designed for early transistorized radios, which needed a moderately high voltage but very low current.
There are very few motors with suitable low-current coil characteristics to be driven by such a battery.  Others might work at best briefly before killing the battery.
If you need around 9 volts for a motor project, you should probably use 6 or so AA cells.

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


text:
WiFiServer Stops After Reconnection to WiFi
In the following code, the Arduino is reconnecting to the WiFi after several loops. The idea is to check and re-establish WiFi connection every 30 minutes or so.
However, the WiFiServer seems to stop working after the reconnecting to the WiFi network. At least I get a timeout, if I try to request data by calling the Arduino's IP address.
#include <SPI.h>
#include <WiFi101.h>

// the IP address for the shield:
IPAddress ip(12,34,56,78);

char ssid[] = "wifinetwork";
char pass[] = "correcthorsebatterystaple";

int status = WL_IDLE_STATUS;
int count = 0;
int retries;

WiFiServer server(80);

void setup()
{
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  connectToWiFi();

  server.begin();
  Serial.println("Server Started");
}

void loop () {
  count++;
  Serial.println(count);
  WiFiClient client = server.available();

  if(client) {
    Serial.print("Connected to a client : ");

    if(client.connected()) {
        Serial.println("Response Sent to Client");
        client.println("Data");
    }

    delay(5);
    client.stop();
    Serial.println("Client is disconnected");
  }

  if (count > 10) {
    Serial.println("Reconnect to WiFi");
    connectToWiFi();
    server.begin();
    count = 0;
  }

  delay(2000); // Wait for 2 seconds before starting to listen again
}

void connectToWiFi(){
  WiFi.config(ip);
  retries = 0;

  // attempt to connect to Wifi network:
  do {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    retries++;
    delay(2000);
  } while(status != WL_CONNECTED && retries < 3);

  if (WiFi.status() == 3) {
    Serial.println("Connected");
  }
}

begin() it again

Already tried that, but unfortunately did not change anything. I edited the code above.

why do you reconnect?

I can't guarantee a stable/continuous WiFi connection. Hence, the Arduino shall search and reconnect to the WiFi network every few minutes, because it may lost connection.

you could try to reinitialize the server object with server = WiFiServer(80) and then begin() it. (the assignment copies the content of the temporary object into the existing instance.)

Unfortunately, this does not solve the issue.

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


text:
What is "tCAN" in codes of CAN bus?
I'm new to Arduino and CAN bus. I'm studying some code examples which contain "tCAN message".
My guess it defines a class for of CAN messages. I did a lot of search but found no information on it except for sample codes. Can anyone help me out.  Thank you!
Some code from the example project:
void activateCAN()
{
 //***PREPARE MESSAGE***//
    tCAN message_act;
    message_act.id = 0x750;
    message_act.header.rtr = 0;
    message_act.header.length = 8;
    message_act.data[0] = 0x00;
    message_act.data[1] = 0x00;
    message_act.data[2] = 0x00;
    message_act.data[3] = 0x00;
    message_act.data[4] = 0x00;
    message_act.data[5] = 0x00;
    message_act.data[6] = 0x00;
    message_act.data[7] = 0x00;

    mcp2515_bit_modify(CANCTRL, (1 << REQOP2) | (1 << REQOP1) | (1 << REQOP0), 0);
    mcp2515_send_message(&message_act); //SEND MESSAGE
}
//******CAN ACTIVATION*****ENDS****//

could you please also state, which .h files are included at the beginning of this sketch?

From Re: Sending multiple messages over CAN with sparkfun can bus shield: #include <Canbus.h> among others.

tCAN will be a struct that defines the structure of the CAN message being sent.  The name tCAN is not a standard and will have been chosen by the author of the library you are using.  At a guess it's using a variant of Hungarian Notation, and the t prefix means type - so it's probably been typedef'd from a struct to a type name.
I am not familiar with CAN, but if there are standard message formats this struct will correspond with one of them.  You can find the actual structure within the header file for your chosen library (or maybe in the example sketch code itself?).

Thank you for the explanation.

tCAN here is a struct that defines a CAN frame to be sent over the network.
https://en.m.wikipedia.org/wiki/CAN_bus#Frames
There are several types of frames, standard, extended, and FD (flexible data).
The tables in the linked Wikipedia article describe the physical protocol. The struct won’t have a corresponding field for every section of the protocol, because the library will take care of setting the constant or calculatable things, like the CRC and End of Frame. You just have to set the relevant details, like ID, (maybe) data length and the data itself.
If you have trouble, check your baud rates and ensure you’re sending the expected kind of frame. Most hobbyist will use standard frames, but many industrial grade pieces of equipment will use Extended or FD frames.

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


text:
What is the right way to query an I2C device from an interrupt service routine?
The ADXL345, for example, requires that interrupts are responded to by querying the INT_SOURCE (interrupt source) register. In example code for the SparkFun ADXL345 Arduino Library, there is code that looks like:
void ADXL_ISR() {
  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){

However, under the covers adxl.getInterruptSource() is sending an I2C message and receiving a response. This seems to be a bad idea in an interrupt service routine (ISR).
A possible option seems to be to turn on interrupts prior to calling adxl.getInterruptSource(), however there is much advice about not doing this (such as, Nick Gammon's informative post). I've managed to get it to work with something of the form:
void setup() {
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
  ...
}
void isr() {
  detachInterrupt(digitalPinToInterrupt(INT_PIN));
  interrupts();
  byte interrupts = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
}

This seems to work but I'm worried I'm missing something. Any suggestions?
EDIT: Thanks for the answers that suggest polling, however I am using a MKR1400 and wish to minimise power consumption by putting the processor into a sleep state - only waking up to process the relatively rare "activity" or "free fall" events. As pointed out by @Majenko, a combination of sleeping and polling might be used. So this really just leaves the question of why is the above a bad idea.

I think your solution is allowed, but it is still totally nuts. Other interrupts might be missed because this one takes so long. To use the adxl.getInterruptSource function in a ISR is probably with a SPI interface in mind. Can you use the sensor with SPI mode ?

@Jot thanks for the response. I don't quite get why another interrupt gets missed (but very happy to be educated). It's not possible for us to change to SPI and presumably it should be able to interface with this sort of device using I2C.

For example Timer0 runs at 1ms interrupt for millis, or when there is serial input with 115200 baud. I think something will go wrong with everything together.

@Jot this would be true if I didn't re-enable interrupts in the second line of the ISR. As it is, interrupts are only disabled during the call to detachInterrupt.

Just because a pin is called "interrupt" doesn't mean that you have to read it using an interrupt input.  The INTx pins of the ADXL345 are simple "level" outputs.  All the time there is an "interrupt" pending (a signal from the ADXL345 that something has happened) the corresponding INT pin is held LOW.  It remains LOW until the interrupt has been handled by your code.
It's not something that is very brief - it's something that persists as long as you need it to.
You can just read the INTx pins with normal digitalRead() from within your loop() function (polling). Unless you really need to respond right now to an event on the ADXL345 there is no need to use an interrupt input.

Although this is true - this doesn't help when you have a low power application. Polling would mean that the main processor is constantly on whereas if I drive from an interrupt, the main processor can be in a low power "sleep" state.

You can still poll and sleep. The two aren't mutually exclusive. Poll an interrupt pin.

OK - it's a bit cumbersome as it means that you need to make sure that you wake up often enough to service the interrupts. Can you help me understand, though, the reason why there is a problem with detaching the interrupt handler, turning on interrupts and then proceeding from there?

What is cumbersome? Wake on the interrupt pin, then sample in your loop. Or set a flag in the interrupt routine and use that to decide whether or not to sample.

ISRs should be short. Nothing else happens while the ISR is running. Things that use interrupts cannot be used inside an ISR. It's best to do as little as possible in an ISR.

The cumbersome part is that the polling time needs to be the shortest time that would ordinarily occur between interrupts to make sure that you don't miss any. This might not be easily discernible. In my case, it's possibly around 10ms, which means that I will still have quite a significant duty cycle. Although, I agree with your general principles - they are just that.

The time taken to poll is negligible compared to the time taken to perform the I2C operations. If you are sleeping and you are woken by the interrupt pin going low, you can just immediately go into a while loop processing any pending events until the interrupt pin goes high. Where's the cumbersome component there? The fact that you have woken up is your "interrupt" to start processing whatever events are available.  Note: I use "events" to indicate things the ADXL wants to tell you about, and "interrupt" for the ISR being triggered to differentiate the two.

If I understand you correctly, you are saying: have an ISR that just detaches the interrupt; in the main loop, sleep_until_interrupt(); when woken check if pin is low and if so, respond to I2C and reattach interrupt. Thank you! Do you want to update your answer?

Majenko's answer is useful — you can simply forego the use of interrupts for this and poll the pin directly in your main loop. Especially on AVR where the external pins are exposed as registers which can be read as fast as main memory this is a reasonable approach. But what if you really want the code to be "interrupt-fast" without writing code that might deadlock an ISR handler? Given the case of a fall or impact sensor, latency might be a genuine issue. Well, there are some things you can do.
First, structure your code so that you never go too long without polling the pin. That means that every bit of code needs to either return to the main loop within an acceptably short period of time, or else needs to take on the job of periodically polling the pin itself. Large compute tasks should have polls sprinkled into them, or be broken into subtasks that can be run by a state machine in the main loop. Long delays should be rewritten in the form
start = micros();
while (micros() - start < howLong) {
  // poll the ADXL interrupt
}

or, again, avoided entirely by queuing up work for the main loop to run later, instead of calling delay.
Second, consider using direct port access for the polling. A check like if (PORTB & (1<<3)) compiles down to a bare couple of instructions, and costs 2 cycles if the interrupt isn't actually asserted (which will be the usual case). Doing if (digitalRead(port)) does a call to a function which takes around 25 times as long. It's still only a few microseconds, but if you've taken the advice of the previous step to poll as frequently as possible to minimize latency, then you don't want all of those microseconds to add up and impact the performance of other code.
Lastly, a technique that doesn't make a lot of sense for this scenario, but could be applicable if you were running on a system other than an AVR-based Arduino, or if you wanted to react to some interrupt other than a level-triggered pin interrupt: you have an ISR that doesn't do any real work, but instead sets a global volatile variable to true and then immediately returns. Then in your main code, instead of polling the port directly, you check the value of that variable. If it's true, you set it to false and then run your "interrupt handler" code. The handler runs shortly after the interrupt triggers, but it's run in an interrupts-on context where it's safe to do slower operations or operations that require timer interrupts to work. This is equivalent to the old Linux concept of "bottom halves".

Nice thorough answer. (Voted) I would suggest adding an imperative "Whatever you do, don't try to read a serial port from an ISR" however.

Thanks for the detailed answer. It might also help if you can describe the failure mode of the code in the question (i.e., why will it fail?). Your second part helped me most.

"What is the right way to query an I2C device from an interrupt service routine?"
The right way is to NOT query an I2C device from in ISR. Interrupt service routines should be very fast to execute. (people advise going as far as avoiding digitalWrite() and digitalRead() function calls and using port registers directly, since those functions are a little slow. Anything done on a serial line is, by definition, not fast. It takes multiple milliseconds to read or write a few characters from a serial port, which is an eternity.)
When the Arduino services an interrupt it stops doing everything else, including handling other interrupts. Your timers will stall, other sensor data will be missed, any other serial communications that are in progress when the interrupt triggers will get errors, etc.
JUST DON'T DO IT.

I am not sure you understood my code - I enable interrupts just after calling detachInterrupt. The period of time when interrupts are disabled won't be very long.


text:
Does anyone know a library that can emulate 3 throttles?
There is this library, but it emulates only one throttle and one rudder. The X Y Z axis don't work because they are addressed from -127 to 127 and I need 0 to 255. I just need one more throttle axis. If it helps, I'm using an ATmega328 and read analog values in the 0 to 1024 range to read Logitech g27 pedals, then dividing by about 4 to fit the read value into the 0 to 255 range.

We really want questions here to be self contained and not depend on external links for their key parts, but conversion from a -127 to 127 range to a 0-255 one should be straightforward - just add an offset.

I agree with Chris the axis ought to work if you modify the value in your code, but if there is a reason you can't use them could you not just create a private version of the library an add in the necessary for an extra throttle, pin, variable and function? (Can't see the code, can't be more specific). Maybe the author would be interested in it for joystick4.


text:
Get hour with ctime (time library with ESP8266)
#include <ESP8266WiFi.h>
#include <time.h>

const char* ssid = "";
const char* password = "";
int timezone = 3;
int dst = 0;

void setup() {
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("\nConnecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
  Serial.println("\nWaiting for time");
  while (!time(nullptr)) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
}

void loop() {
  time_t now = time(nullptr);
  Serial.println(ctime(&now));
  delay(1000);
}

This is my code, but it shows the time like this: Sun Jul 23 15:21:12 2017. But what I want it to do is to only show the current hour, not everything.
Is it possible to do that?

Use gmtime() or localtime() instead of ctime(). Print the hour field tm_hour in the struct tm.

Welcome to the site. Next time for aligning code, select code and press ctrl+k

@MikaelPatel I am a beginner at this, could you please give me an example of how it should look like?

@MikaelPatel Okay i tried this Serial.println(gmtime(tm_hour)); but i get an error "'tm_hour' was not declared in this scope"

Here is an example of gmtime() and the struct tm; http://www.cplusplus.com/reference/ctime/gmtime/

The easiest way is to use the standard function localtime() or gmtime() and the struct tm.
void loop() {
  time_t now;
  struct tm * timeinfo;
  time(&now);
  timeinfo = localtime(&now);
  Serial.println(timeinfo->tm_hour);
  delay(1000);
}

Nice example thank you.


text:
Arduino Pro Micro not recognised by computer or showing up in ports
Around 4 days ago my Arduino Pro Micro arrived. I've been messing around with it, using it to run keyboard commands on a computer. Just recently, whenever I plug it in to the computer it isn't detected by ports or anything. The green light is still on, and the left red light (looking at it from the side of the micro USB input) still works as well, however the right red light no longer works. Can someone tell me what's happening? Have I broken it all ready?

What was the last sketch you uploaded to it?

The arduino pro micro is notoriously difficult to program. I am sure you have figured this out when first installing the drivers but on power up, the micro runs a bootloader for <750ms  so for me at least, it was extremely difficult to install drivers.
However, if you look at this guide by sparkfun, you will see that resetting the board in quick succession will load a longer 8 sec bootloader, which gives your more time to program it. Obviously, this is not normally something you need to worry about as the Arduino IDE automatically resets the board sending it into the bootloader when you upload a sketch to it.
Back to your problem, if it is not popping up as a device when you plug it in to your computer, go into control panel > system > hardware > device manager and look to see if you can find it there. If it still doesn't show up, do what I said above and reset it twice and hopefully you will see the bootloader appear where you can reinstall the drivers for it. You can find the appropriate drivers in the same location where you installed the IDE originally.
Hope this helps!

Sorry to tack onto a 4yr old thread, but hoping this helps others, as it would have me.
Unbeknownst to me,some USB micro cables are power-only and don't have the data lines. I had one of these in my rotation of cables, and while the LEDs lit up nicely, the USB does not appear. I was sure it was not a cable prob as I thought I'd tried multiples. I was unaware I had one of these power only USB cables about - marked with the USB Trident just like the others.
So if you have the 'dead USB' problem with your Pro Micro, do make the effort to be absolutely sure of your cable situation.
I read the debugging posts across the web far and wide, but I yada-yada'd the cable check, as I never saw anyone point out the cable might be undamaged, but just a null-data variant.  My bad obvs - but just FYI for others like me.


text:
How to make two WIR 1186 RF transceivers communicate over serial communication?
I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.
Pin connections are as below:

Arduino :5v,gnd,RX,TX,2,3
WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.
Below is the code:
char ch;
int prog = 2;
int cts = 3;
int stat;
unsigned int output;

void setup() {
  Serial.begin(9600);
  pinMode(prog, OUTPUT);
  digitalWrite(prog, LOW);
  stat = digitalRead(prog);
  Serial.println(stat);
  Serial.write("B=9600\r\n");
  output = Serial.read();
  Serial.println(output);
  digitalWrite(cts, HIGH);
}

void loop() {
  Serial.write('a');
  delay(1000);
}

Here is the datasheet of WIR1186
Please help me out with this.

digitalWrite(cts, HIGH); --- Are you sure about that?

yes,clear to send should be high when we are sending

Err... have you read the datasheet?

yes i referred that and i have downloaded WIR library from GIthub, based on the header file function i have given cts High, Before that the commands in setup are also not sending to WIR module

Is your WIR-1186 on some kind of carrier board with voltage regulator and logic level translation?

Two things are wrong:

You aren't setting PROG to HIGH to enable transmit mode - you are stuck in programming mode.
CTS is an output from the module to an input on the Arduino. You don't set it high - you look to see what level it is to see if it is safe to send more data.

To quote from the datasheet you link to:

The WIR-1186 offers data flow control hardware to allow for zero data over-run and loss when sending large
files and data packets. The internal data buffer on the WIR-1186 module is 128bytes. When the data terminal1
sends a large file for wireless transmission the module2 will except 128bytes and then set the CTS pin LOW to
alert the data terminal to wait for the CTS to back HIGH before sending more data over UART.

(footnotes mine)
Also you cannot use pins 0 and 1 for serial if you are at the same time using them for USB debugging. You will either have to move to another pair of pins and use SoftwareSerial, or invest in a better Arduino with more than one UART.
Another thing of importance: If your WIR-1186 isn't on some kind of carrier board with voltage regulator and logic level translation it's safe to say that you have killed it. Well done.

Warnings

The maximum allowable voltage on any of the interface pins with respect to GND is 3.6V
The maximum input voltage VCC with respect to GND is 3.6V
The baud rate setting in configure mode is fixed 9600bps
Do not leave the UART_TX input pin of the module open. The module will send junk data on thewireless channel. It must be pulled up to VCC if not used.

1 Arduino
2 WIR-1186

but it is not entering into command mode also ,when i send a command in setup as in the program it is not giving any response

Your program isn't looking for a response. It's looking to see if there's a single character in the RX buffer at the moment you send the command. Learn the basics of serial before trying to use it. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

no response is getting, Serial.read() is printing -1

If you use pin 2 and 3 for serial communication you have to use SoftSerial, because Serial is hardwired to pin 0 and 1.

pin 2 and 3 of arduino has connected to prog and cts pins of WIR module


text:
Arduino Esplora
So I'm trying to turn my Arduino Esplora into a controller, and my first step is to understand how the controller works. I've copied and pasted this code into the Arduino 1.8.2 IDE.
Esplora.writeRGB(255, 255, 255); // sets red, green and blue all to full brightness

But I get an error saying,
exit status 1
'Esplora' does not name a type
Please explain why it's doing this.

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just a snippet.   Make sure all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Also make it verifiable, ie so it can be compiled and tested, allowing other people to test their theories about the problem.

Please also take the tour at http://arduino.stackexchange.com/Tour to get the most out of this site.

You probably forgot:

To include Esplora.h in your sketch.
To select "Esplora" for the board.


text:
Access I2C sensor from Arduino Uno as slave
I connected Raspberry Pi 3 to an Arduino Uno through I2C. The Arduino Uno uses the I2C as slave.
When I connect AM2320 sensor (temperature and humidity) to the Arduino Uno, I am getting the response that the sensor is offline.
I tested the sensor on Raspberry Pi 3 and it is working fine. On the Raspberry Pi the address is 0x5c. On most libraries, the address is 0xb8. I have the same result when I tried these 2 addresses.
Do I have problem because Arduino Uno is working as slave?

Two comments and a request. C1) rPI is powered at 3.3V, while the arduino uno is powered at 5V. What pullup voltage are you using on the I2C lines? Remember that 5V is too much for the rPI, and 3.3V should be not enough for the arduino.... C2) 0x5C and 0xB8 are essentially the same address. I2C have 7bit addresses, while the last bit of the first byte is the read/write one. So the proper address is, in binary, 1011100 (saved as 101 1100, or 0x5C), but arduino saves it with the R/W bit too (1011 1000, or 0xB8, for more easiness). R1) remember to choose an answer if it answers your question

I had may be a bad connection but I can read the sensor AM2320 on Arduino-
Uno and send the value back to Raspberry Pi.
Arduino side:
#include am2320
#define SLAVE_ADDRESS 0x04
Wire.begin(SLAVE_ADDRESS);
AM2320 th;
Wire.write( (int)(th.t * 10)); // th.t is for temperature which I send
integer

Raspberry side:
import smbus
bus = smbus.SMBus(1)
address = 0x04
number = bus.read_byte(address)

Raspberry Pi and Arduino Uno seems to work good together with and I2C sensor on Arduino side. Thanks for you time to help me and I will go to the link you propose.

Indeed, I2C slaves cannot communicate with one another.
There are some obscure capabilities for devices to switch role, but that is likely to introduce lots of complications.
You might look at using bit-banged (or "soft") I2C on other digital pins and move the peripheral's I2C lines there instead o the hardware I2C pins connected to the pi.  For example, a web search quickly found something that claims to do this at:
https://github.com/felias-fogg/SoftI2CMaster
No idea if that particular one will work for you, but there are others as well.
Or you can re-design your scheme so that the pi reads the sensor, and if necessary writes the values of interest to the Arduino.


text:
Reading pressure sensor using Arduino analog
I'm using a Arduino Uno to read pressure and I want to know if I have wired/coded the sensor correctly. I'm not sure I'm getting the correct readings (it could be the right readings - I just want to check I have done everything right). The sensor I am using is an OsiSense™ XMLP pressure sensor that reads between 0 and 100 bars and gives out a 0v (zero bars) to 10v (100 bars) charge. Due to the Arduino Uno only being capable of reading up to 5 volts, I've used a voltage divider to reduce the maximum voltage the Arduino receives to 5v.
I've attached a hand-written diagram. Let me know if you need any more information. I've attached the wiring and also the code.

/*
  ReadAnalogVoltage from a OsiSense XMLP presure sensor

  Reads an analog input on pin 0, converts it to voltage and then bar pressure, and prints the result to the Serial Monitor and also MQTT.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).

  Todo
  Static ip. set it to request IP from network
  Work out best way to average readings

*/

#include <SPI.h>  //Serial Peripheral Interface (SPI)
#include <Ethernet.h>  //  These libraries are designed to work with the Arduino Ethernet Shield (Ethernet.h)
#include <PubSubClient.h>  // This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT

// sets the MAC address and IP address for the network
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192,34,98,221);  // IP Address of the client
IPAddress server(192,34,98,201); // The IP address of the MQTT server

void callback(char* topic, byte* payload, unsigned int length) {
  // handle message arrived
}

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);

void setup() {
  Serial.println("Begin setup");
  Ethernet.begin(mac, ip);
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // connects to MQTT and says hello world.  Probably change this later on to something more appropriate
  if (client.connect("ArdRigTest")) {
    client.publish("outTopic","Ard Rig Test");
    client.subscribe("inTopic");
  }
  // start serial port
  Serial.begin(9600);
}

void loop() {
  // Note - the default maximum packet size is 128 bytes. If the
  // combined length of clientId, username and password exceed this,
  // you will need to increase the value of MQTT_MAX_PACKET_SIZE in
  // PubSubClient.h

  // read the input on analog pin 0:
  int sensorValue1 = analogRead(A0);
  delay(2); // read twice with small delay to get accurate reading.
  int sensorValue2 = analogRead(A0);

  Serial.println(sensorValue2);
  //Test code. using map function
  int MapBarPressure;
  MapBarPressure = map(sensorValue2, 0, 1023, 0, 100);
  if (client.connect("ArdRigTest" )) {
    client.publish("MapBarPressure",String(MapBarPressure).c_str());  //logs the pressure of the RigTest
    client.subscribe("MapBarPressure");
  }
  delay(100); // Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are 1000 milliseconds in a second.)
  client.loop();
}

Thanks in advance.

Assuming that you are using analogRead() with 0 for 0V and 1023 for 5V it is a question of mapping the range 0-1023 to the pressure range 0-100 bar (map(0, 1023, 0, 100)). See https://www.arduino.cc/en/Reference/Map. Or use float to keep the resolution.

Which pressure sensor is it ? The output voltage is probably not 0.0 to 5.0V, but rather 0.5 to 4.5V. How good and stable is your Arduino 5V which is used to power the sensor ? That is important to know. Is the pressure sensor ratiometric ?

Its a OsiSense™ XMLP.  It kicks out a 10v output so I've built a circuit with a voltage divider so the output to the Arduino is a maximum of 5V.   The power source to the sensor is 24v and is stable.

I'm using analogread.  I don't understand the maths behind map but I guess thats the beauty of the function.  It simplifies the maths so I dont need to.

Using the map function is okay. Just use it. However, you have a problem with the accuracy. What is your voltage divider made of ? Please tell everything, the resistor values and so on. If that sensor was the 0.5-4.5 ratiometric version, then you would have a good accuracy. With the 0-10V sensor you don't. How good and stable is your Arduino 5V ? Do you need the full 100 bar range ? If you only need to measure up to 50 bar, then only a protection resistor would be needed.

2 x 10k resistors. one leads to ground and the other leads to the Arduino analogue in.  i don't think i need the the full 100 bar, i will know more after measuring the pressure.  When you say how stable is the arduino 5v, can you expand on what you mean?

Please update your question. Rewrite it completely, mention the sensor, the resistors, and which Arduino board, and the result that you want (if you want a float value, then you can't use the map function). The sensor you have is not ratiometric and outputs a absolute voltage. When the Arduino reads that, the 5V of the Arduino is default used as a reference. If that 5V changes, so will the resulting measured pressure change, even if the sensor outputs the same voltage. Using the internal reference is better, but it can be 1.0 to 1.2 V and is different for every Arduino board.

Added all the details of the project as requested.  Hope all the information is there for you.  If not, ask away :-)

The Arduino and the sensor need to share a common ground: connect the negative terminals of the power sources together.

If you need to use fractional pressure values, then the formula is
float MapBarPressure;
MapBarPressure = sensorValue2 / 10.24;

This was obtained by seeing that the maximum reading from AnalogRead(A0) is 1024, which corresponds to 5V on A0 (and which also means 10V output from the sensor.) If you read 1024 from A0, it means you are measuring 100bar, so
bar = (A0 / 1024) * 100

Alternatively, you could maintain 1 decimal place of accuracy in bar if you keep with int values:
int MapDeciBarPressure;
MapDeciBarPressure = map(sensorValue2, 0, 1023, 0, 1000);

Then your variable is holding "tenths of bar" (deciBar) and you only convert it to bar by dividing by 10.0 (not 10, which is an int, but 10.0, which is a float and does floating point math and returns a float response.)
One other note: you write:
// read the input on analog pin 0:
int sensorValue1 = analogRead(A0);
delay(2); // read twice with small delay to get accurate reading.
int sensorValue2 = analogRead(A0);

Just reading twice doesn't gain accuracy -- you have to average the values:
int sensorValAvg = (sensorValue1 + sensorValue2) / 2;

Then, use sensorValAvg for your less noisy value.
Edit:
Also, make sure you connect all ground lines together, both from the sensor and the Arduino!

The conversion factor is 1024, not 1023.

Caught me again! Edited.

You can use map, ref. : https://www.arduino.cc/en/Reference/Map

Re-maps a number from one range to another. That is, a value of
  fromLow would get mapped to toLow, a value of fromHigh to toHigh,
  values in-between to values in-between, etc.

With the caveat that "The map() function uses integer math so will not generate fractions, when the math might indicate that it should do so. Fractional remainders are truncated, and are not rounded or averaged."

so sometimes it's worth thinking in decibars internally and only convert to bars when you need to show it to the user.

@josecanuc did the OP ask to get decimals?

Indeed the OP did not specify any requirements in that regard, but if he or she uses map(), I only wished to clarify the limitation.

Please use a more constructive way to explain it then!

Thanks for letting me know about integer, truncates and thanks for the map function :-)  The truncations may cause us a problem, I may need more accuracy.

@resolver101 If you need accuracy I would use an op-amp scaled to 1/2 instead of the voltage divider.  And make sure you use 1% or better resistors.

Everything is just fine.
All you have to do is to provide the common ground (0 potential) to your Arduino and your Sensor.
The problem here is that they might be on a different potential.
So just connect the ground of your 5 volts and 24 volts together and everything will work perfectly.

About accuracy.
I assume you have read @edgar-bonet about connecting the GND's.
I assume you understand the other answer to calculate the pressure. I would write it like this:
// This is for the DEFAULT 5V analog reference.
// v = the voltage at the pin in Volts.
// p = the pressure in bar.
// Note that 'bar' is the pressure relative to the
// normal atmospheric pressure at that moment.
float v = (float) analogRead(A0) / 1024.0 * 5.0;
float p = v / 5.0 * 100.0;

The analogRead uses default the 5V as reference.
That means that if the project is powered by a USB cable, the 5V could vary between 4.5 and 5.0 V. That 10% difference will be seen in the resulting calculated pressure. In that case you can not measure more accurate than 10%.
If the project is powered with a power supply to the power barrel jack, then the resulting accuracy depends on the accuracy of the voltage regulator on the Arduino board.
The analog reference can be set with analogReference.
The internal voltage reference of the Arduino Uno is 1.1V. That is reasonably stable, but it depends a little on the voltage of VCC and the temperature. The main problem is that it is different for each Arduino Uno, and it can be between 1.0 and 1.2 V. Therefor you have to measure it, and use the measured value in the calculation in the sketch.
The input range is between 0V and the analog reference. Therefor you have to adjust the voltage divider to get 0..10V down to 0..1.1V. You could try: R1 = 100k and R2 = 10k.
const int pressureSignalPin = A0;

void setup()
{
  analogReference( INTERNAL);
}

void loop()
{
  // v = the voltage at the pin in Volts.
  // p = the pressure in bar.
  // Note that 'bar' is the pressure relative to the
  // normal atmospheric pressure at that moment.
  // The "(100.0 + 10.0) / 10.0" is the factor by the voltage divider
  // with 100k and 10k.
  // Measure the AREF pin, and fill the value in for "1.10".
  float v = (float) analogRead(A0) / 1024.0 * 1.10;
  float p = v * ((100.0 + 10.0) / 10.0);
}

Thanks. I've connect the grounds between the arduino and the sensor so they are all common.   I've not tried the internal reference yet.. The power in is from a POE converter to the usb cable.  I've attached a USB current/voltage reader and you can see the video hear : https://www.youtube.com/watch?v=Tb7qJXcJl9M&feature=youtu.be


text:
How to work with arduino softwareserial communication using HC-05?
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=>

master code=>

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..

Is copy pasting code really that hard?

sorry,I didn't get you.

sorry...the main code has now been attached.

Does CTRL + C and CTRL + V ring a bell?

bro,would you please give me any solution?

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.

sorry,I'm new to this group.so i didn't know the rules.But ,it still is not working,though i have removed the line.now the indication LED on HC-05 is flashing very quickly.

arduino RX=>TX of hc-05 and arduino TX=>RX of hc-06 ........this connections are same for both master and slave...for your convenience i have added these information.

at last,fixed it

What fixed it?  If it was this please mark this as the answer to help others, if not answer the question yourself.

authors: Егор Русаков


text:
error: 'analogRead' was not declared in this scope
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:
#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.

Did you follow the rest of the process to integrate the Arduino environment into Codeblocks?

@IgnacioVazquez-Abrams Do you have a link to this process?

did you try to include "Arduino.h"?

Did you get this issue fixed? If so, could you post an answer as to how you fixed it?

Also, which version of codeblocks?

// 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?

He is using Codeblocks IDE with Arduino core, not the actual Arduino IDE.


text:
Can removing lines of code destroy a motor driver and make it catch fire?
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 link with specs

You can't have two return statements after each other. So there is already something very wrong here.

@Gerben I suspect he isn't using those returned values, since they are defined as global variables anyway.

@Gerben I dont know why but the program refuses to work without all those return statements. Any idea how it can burn a mosfet by its absence?

Is it possible that i shorted two motor inputs by not calling return in on all the statements? I didnt call the return statement in all the functions once but that didnt make the driver burn, just that the program wasnt behaving as needed. @Majenko

Without seeing your entire program and knowing all your wiring it's impossible for us to know that kind of thing. Yes, it's possible. Is it what happened? Who knows?

Ok I will update my entire setup @Majenko

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

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.

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?

Is it possible that i shorted two motor inputs by not calling return in on all the statements? I didnt call the return statement in all the functions once but that didnt make the driver burn, just that the program wasnt behaving as needed

A function will return if control reaches the end the final '}', even without a return statement.

authors: Андрей Вячеславович


text:
The current direction for digital output pins
I am new to Arduino. The digital pins can be configured as output (https://www.arduino.cc/en/Tutorial/DigitalPins) for triggering some sensors. I am now setting a digital (output pin), say no. 7,which is connected to the in1 pin of a SRD relay (https://blog.siliconstraits.vn/relay-what-is-it-and-how-to-use-it/):

I am not very clear about the direction of current flowing in the wire connecting the arduino digital pin to in1. To my understanding, when digitalWrite(pin, HIGH), no current flow into the arduino pin, the relay is not triggered, while digitalWrite(pin, LOW), the current flow into the arduino, and the relay is triggered. Please correct me if I am wrong. Thanks.

You are not driving the relay directly, are you?

I updated the post.

In your question, you mention connecting the Arduino to a relay, yet in the figure, you show a relay board. That's not the same! Please clarify. If using a relay board, please link to the datasheet or the supplier's product page.

I consider using a diode in my circuit, so I need to the current flow direction.

what would be the purpose of the diode? ... how would it be connected?

I want to put a diode between the signal pin of the relay and the digital output pin of arduino. So I wonder if the current flows into or from the digital pin.

you did not answer my first question

The relay board in the picture has a transistor on it that turns on the (blue) relay. The Arduino pin only turns on the transistor, which in then turns on the relay. The transistor makes it so that only a small amount of current is needed from the Arduino pin. This is because the coil in the relay requires more current that the Arduino pin can (safely) provide.

When you set a pin to HIGH then that pin will provide 5V.  When you set a pin to LOW then that pin will be set to 0 volts.  Which direction the current flows depends on what is at the other end of the wire.  Current always flows from higher voltage to lower voltage.  If you set a pin to HIGH and the thing it is connected to is at ground then current will flow out of the pin towards ground.  If you set a pin to HIGH but the thing it is connected to is already at 5V then no current flows.  If you set a pin to LOW and the thing it is connected to has some positive voltage then current will flow to the pin.  If you set the pin to HIGH (5V) but the thing it is connected to has more voltage than that (say 10V) then current will flow towards the lower voltage and into the pin, probably damaging the Arduino in the process.


text:
Control relay with both Arduino and DAQ at the same time
I want to control a relay with both Arduino and DAQ. Arduino is used as an embedded  device for the control, while the DAQ is hooked up with a computer and performs the control with a user interface. Here is below a schematic of the circuit wiring for the control:

The two signal pins of the relay are connected with the digital pins of Arduino and DAQ. For some reasons, when Arduino comes into play, the control via DAQ cannot be achieved. If only Arduino or DAQ is connected to the relay, there is no problems with the control.
My plan here is, mstly, to let Arduino to instruct some tasks. In some special cases, I want to have the control with DAQ. Anyone can debug my circuit above? Thanks!

Are the control lines active low or active high? In other words, from the Arduino do you digitalWrite(portnum, HIGH) or LOW? You might be able to solve this with a pair of diodes.

I guess, that you drive the digital pin of the Arduino directly with digitalWrite() for HIGH and LOW and that the DAQ does the same (I didn't researched this).
In that case your circuit is dangerous for the devices. As long, as they both output the same, everything is ok. But take the case, that the Arduino is driving it's pin HIGH, while the DAQ driving it LOW. That would be a short through the pin driving circuit's of both devices and most likely the flowing current will exceed the maximum current rating of the pin. This can fry the involved pins hardware or even the complete devices. You get some kind of race condition here: The device, that can handle drain/source more current will be the winner.
In general you have to implement rules, how the devices should work together. Do you need the actions from the DAQ to be executed no matter what the Arduino does? Or should the Arduino be the master here? Or something inbetween? It is not clear, what do you need here.
I will give you 2 suggestions about possible ways:

You could control the relay only with the Arduino. The DAQ can be connected to a digital input of the Arduino (so that it can sense the DAQ's output state) and in the Arduino code you can implement all the logic you need to drive the relay to your liking.
You could define an idle state of your relay input and set it with a pullup or pulldown resistor. It will ensure, that the relay input is at the defined idle state, as long as no device is driving the line to the opposite state. For this you need the devices outputs to be high impedance (on the Arduino this means the pin is configured as input; for the DAQ you need to know yourself or research it).
Let's say the idle state would be HIGH. We would connect the relay pin with 5V through a high resistor (this is the pullup resistor) (maybe 10k, the value is not critical). Both devices can be connected directly. If one device needs to change the state to LOW, it can drive it's output pin actively low, forcing the relay pin to also go to LOW. If it doesn't need the state to be LOW anymore, it should put it's pin into high impedance mode. The pullup resistor will pull the state to HIGH again. You can also add relatively low resistors between the devices to protect against damages from accidentally driving active HIGH while the other is LOW (These can be calculated from the maximum current rating for the pins; 20mA for the Arduino). This kind of logic is often called open drain logic.

simulate this circuit – Schematic created using CircuitLab
If the DAQ cannot put it's pins to high impedance, you can setup that circuit yourself with a single MOSFET:

simulate this circuit
If you use this circuit on both devices, you don't need the small resistors anymore.

The second possibility already implements a specific logic. You need to decide if this logic is good for you. You can invert it's logic (idle state LOW). Personally I would go with the first option, because it is easier and more flexible.

the signal pin is only TTL logic. almost no current.

Do you mean the pin of the relay module? Then yes, it is. But when you directly connect the 2 output pins of the devices to the same relay module pin, you can get a strong cross current (from one device to another, not through the relay pin). That is the problem that I've described. Is there something wrong with it?

sorry. no problem, you are right.


text:
Arduino Uno + MSD-11-EM stepdriver + NEMA 17
I am working on Arduino code for stepper motor rotations control. I want to rotate a stepper for only 4 rotations.
The code is working fine but that will run only once as I have put that in setup().
I want to know if there will be any reverse current flowing in the circuit that would damage the Arduino or stepper. What if I want to run the stepper in the loop()? I tried but that will force the stepper to run continuously.
How can I run stepper for only 4 rotations and then stop?
I want to run it in loop().

Below is the code I am using:
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(110);
  // initialize the serial port:
  Serial.begin(9600);
  for(int i=0;i<25;i++) {
    Serial.println("Anti-clockwise");
    myStepper.step(stepsPerRevolution);
    delay(50);
  }
}

In loop add flag to change after what you desired plus a statement to check the flag.
Code below (assuming what is in for() being enough to do 4 revolutions):
#include <Stepper.h>

const int stepsPerRevolution = 2100;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
bool flag = true;

void setup() {
 // set the speed at 60 rpm:
 myStepper.setSpeed(110);
 // initialize the serial port:
 Serial.begin(9600);
}

void loop {
 if (flag) {
   for(int i=0;i<25;i++) {
     Serial.println("Anti-clockwise");
     myStepper.step(stepsPerRevolution);
     delay(50);
   }
   flag = false;
 }
}

This solution gives you a flexibility to add a pushbutton to change flag and do another 4 revolutions.

I still wonder how code which I have posted earlier worked but no worries code below is working as expected.
int dirpin_T1 = 7;
int dirH_T1 = 8;
int steppin_T1 = 9;
void setup() {
  pinMode(dirpin_T1, OUTPUT);
  pinMode(dirH_T1, OUTPUT);
  pinMode(steppin_T1, OUTPUT);
}

void loop() {
  static int count = 0;
  if(count < 4) {
    count++;
    digitalWrite(dirpin_T1, LOW); // Set the direction.
    digitalWrite(dirH_T1, LOW);
    delay(1000);
    for (int i = 0; i<3193; i++) {
      // Iterate for 4000 microsteps.(32767)
      digitalWrite(steppin_T1, LOW);
      // This LOW to HIGH change is what creates the
      digitalWrite(steppin_T1, HIGH);
      // "Rising Edge" so the easydriver knows to when to step.
      delayMicroseconds(500);
    }
  }
}

please make sure you reset the arduino everytime you power it on to run the stepper because it won't run the loop again, just four rotations and it will stop.

Learn to properly indent your code. Press cmd/ctrl-T in the Arduino IDE regularly to clean up your code.


text:
Arduino Mega 2560 + BL-TB6560+ Stepper
I am working on an Arduino Mega 2560 and BL-TB6560-V2.0 driver for running a stepper motor. Initially I was able to run the stepper in both direction with code given and a schematic as per this image.
.
int dirpin = 7;
int dirH = 12;
int steppin = 9;

void setup() {
  pinMode(dirpin, OUTPUT);
  pinMode(steppin, OUTPUT);
  pinMode(dirH, OUTPUT);
}

void loop() {
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, LOW);
  delay(1000);
  for (int i = 0; i<32767; i++) {
    // Iterate for 4000 microsteps.(32767)
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
  delay(1000);
  digitalWrite(dirpin, LOW); // Set the direction.
  digitalWrite(dirH, HIGH);
  for (int j = 0; j<32767; j++) {
    // Iterate for 4000 microsteps.
    digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
    digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
    delayMicroseconds(50);
  }
}

But now when I am trying it, the same stepper is not rotating. What could be the reason? I have checked the driver voltage, it's ok, and the code and schematic is the same.

http://idownvotedbecau.se/imageofcode

There is no ground connection to the arduino on the schematic, hope there is one in the real world.

Why do you inverse the polarity on the 24V site ? Is this a mistake in the drawing ?

I just removed the ENE(+) pin of the driver, which was connected to the +5V. Now it's working and the stepper is rotating.
I just got a hint from this video.


text:
Looking for link to Double Pole Single Throw (DPST) relay for Arduino
Need to find a DPST relay that is 'Arduino' friendly and that is capable of 30A at 240VAC. Anyone can share links ?
Not looking for recommendation, just ideas on what you saw or used in the past.
Thanks.

30A is going to be a large relay. Get ready to put down a bit of cash.

cash is not an issue here, finding one that I can couple to an Arduino is...

I am maybe confused... The 240V circuit is composed of 2 live wires, 120V each, phased out by 90 degree to get the full 240Vac.

you could use a solid state relay ... it should work directly on the arduino

I use this: https://www.seeedstudio.com/Grove-SPDT-Relay%2830A%29-p-1473.html

@juraj How would you connect the 2 phase wires on that ?

A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.
High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.
You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.

Indeed and using an other relay to control the main relay is possible.

Do not be scared from other answers. There are relays which hold the coil with 5 V from Arduino. Like the relay on this Grove 30 A Relay Module. It is powered from 5 V pin and the command to close is from the GPIO pin (works with 3.3V IO too).
Use two of these SPDT modules, if you can't find DPST powered with 5 V.
If you will use the Grove module and you do not use other Grove modules, there is no need to buy the Grove base shield. You can connect the module with this cable.

The Grove module mentioned in this answer is only single pole. The question asks for a double pole relay.

You will be hard-pressed to find a mechanical relay that you can directly connect to the Arduino digital pins. Any general purpose relay that fits your specs for the switched side will do, but you will need to pay attention to the datasheet for the coil voltage and current required to activate the relay.
Then, you'll want to use a driver circuit like a transistor (BJT or MOSFET) so that the low-voltage, low-current digital output of the Arduino can control the larger-current needed to trip the relay coil.

Yeah and opto isolation ;-)

A well designed relay driver circuit ought not strictly need opto-isolation. If you put a reverse-biased diode across the relay coils to prevent voltage spikes from damaging the transistor, the relay itself provides sufficient isolation between the switched circuit and the microcontroller.


text:
Problem for control speed of a DC motor with a L298N
(Not native english speaker here, feel free to edit my sentences)
I try to control the speed of a DC motor with a L298N shield but it doesn't work very well. Here is my scheme :

The power comes from a transfo with an adjustable voltage of ~7v 1.0 Amp. I don't care about the sens of rotation, so I set IN1 to 5v and IN2 to the ground, is it right to do it like that ?
Now here is the code I'm using :
#define CONTROL_M   9  // To Enable input

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

void loop ()
{
    test_analog_motor();
}

void test_analog_motor()
{
    for (int i; i < 250; i=i+25)
    {
        Serial.println(i);
        analogWrite(CONTROL_M, i); // Any value between 0 and 255
        delay(500);
    }
}

With that code, the speed of my motor should progressively increase and then goes back to 0. I'm aware that, maybe if the value is too low, the motor will have trouble to start so I "help" it manually.
If I doesn't use the Enable output of my Arduino and just use the jumper instead, the motor turns with a good torque. This prooves at least that my shield isn't damaged.

Now here is the problem I have : With the scheme I've shown above, it simply doesn't work, nothing happens when I set the grounds in common, why ? Then if I remove the cable that goes to the arduino ground, it works but the motor has a very low torque, it seems also that there is a kind of latency in regards to what display the Serial monitor.
I feel a bit stupid with what I did with the grounds, it seems wrong t me  but I don't know what to do instead :/ What can I do ? My goal is to have the best possible control of the speed of that DC motor in term of reactivity, does a L298N is suited for that ?
EDIT
I did tested the PWM with an oscilloscope and a multimeter, the arduino PIN I was using worked correctly. I don't know why but now, the shield works too, I mean : Problem solved. One theory is that I adjusted the tension of my power supply under 5V. In that cas the shield doesn't nothing Arduino is magic sometimes...

Your delay is probably too long - your code will take over 2 minutes to reach full speed.  Also the L298 is an obsolete, antiquated, lossy part.  FET drivers have been the norm for over a decade, but people keep putting these obsolete designs on ecommerce sites for the unsuspecting to buy.

could you cite the names of some good FET drivers example ?

@ChrisStratton  By the way, my code will not take over 2 min to reach its full speed. look, it's i = i + 25 so 10 step of 500 ms period is about 5 secondes

for (int i; i < 250; i=i+25)? You might want to initialize the variable i, like so for (int i=0; i < 250; i=i+25).

Are you sure you don't need to supply 5V to the board?

@Gerben I can use the board without Arduino, if Enable Jumper is set, my motor will turn. the problem comes from PWM

You do need the ground wire. The reason it 'works' without it is that enable input effectively then has an aerial connected and is responding in the same was as if you touch the input jack on an amplifier and hear a buzzing sound.
There is a link behind the blue connectors that enables the onboard 5v regulator. I assume you have this fitted, or it wouldn't work with the jumper as you describe.
There is a tutorial here : http://www.instructables.com/id/How-to-use-the-L298-Motor-Driver-Module-Arduino-Tu/
I can't see anything different from what you're doing that would cause it to fail, but perhaps you have a problem with pin 9 from your board - you might have damaged it by misconnection, as certain ways of wiring that schematic could put 12V on the arduino pin.  You could also try using pin 13 : the arduino LED should then be lit in sympathy with the PWM signal and you'll know it's working.

Yes what you say about buzzing sound makes sence. indeed, I'm wondering if I'm not damaging the pins of my arduino with that assembly. so what's weird is that the board doesn't seems to do anything when grounds are common. I will test the PWM separately to see if they work as expected


text:
I want to make a counter but i don't know what i'm missing or am doing wrong
this is the code i made but it gives me an error about te } and also i need to know how to make delays with this
int ledPin = 4;
int buttonPin=2;
int buttonState = 0;         // variable for reading the pushbutton status

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

void loop()
{
  if (buttonPin=(LOW);
 {
 Serial.println("someone pressed it");
}
  else
  {
    Serial.println("nothing");
  }
}

thanks for helping!

You forgot bracket here
if (buttonPin=(LOW);

Should be
if (digitalRead(buttonPin)==(LOW)){

To make a delay of 0.5 seconds for example:
delay(500);


text:
What is the default setting for a digital output pin
With digitalWrite(pin_number,value), we can set an output pin as HIGH or LOW. But if only coding pinMode (pin_number, OUTPUT), what is the default state for the pin pin_number, LOW or HIGH? It is noted that: Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state. Does that mean the pin will be in the state LOW?

neither, they are HI-Z ... all pins are set as input with pullup resistors disabled ... that means that they are seen as floating (disconnected) ... any pin that has an external pullup or pulldown resistor will be pulled in the direction of the resistor

On the AVR-based Arduinos at least, pins start in the INPUT, i.e. high
impedance state. If you then pinMode(pin, OUTPUT);, the pin turns to
OUTPUT LOW. Note, however, that if you first set the pin to
INPUT_PULLUP, and then to OUTPUT, the pin ends up in the
OPUTPUT HIGH state.
Sometimes you want to control the state the pin will have right when
it's turned to OUTPUT. You may for example simulate an open collector
output by switching between INPUT (or INPUT_PULLUP) and OUTPUT
LOW, while avoiding the OUTPUT HIGH state. In this case, a safe
idiom is to set the output level before switching the pin to OUTPUT,
e.g.
// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);

A side effect of performing a digitalWrite() on a pin that is not set
to OUTPUT is that the pin gets switched to either INPUT (if writing
LOW) or INPUT_PULLUP (if writing HIGH). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.
Reference: the source code of pinMode() in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
Ports as General Digital I/O in the ATmega328P’s datasheet.

I've had a similar issue with an ATTINY85 powered DIGISPARK board.
I was getting a glitch when setting a pin to OUTPUT and the driving it HIGH immediately. Looked something like this:
CH1:
pinMode(ch1, OUTPUT);          // it is at this line that ch1 becomes LOW
digitalWrite(ch1, LOW);        // technically redundant since ch1 pin already driven LOW
CH2:
pinMode(ch2, OUTPUT);          // at this point ch2 goes LOW
digitalWrite(ch2, HIGH);       // and only goes HIGH once this instruction executes

The solution that mitigated the above glitch in my case (ATTiny85 / Digispark Board) was, as Edgar Bonet pointed out above, going through the INPUT_PULLUP phase:
pinMode(ch2, INPUT_PULLUP);
pinMode(ch2, OUTPUT);
digitalWrite(ch2, HIGH);


text:
Refactoring bad design?
Could someone help me how to refactor old very complex code ?
Original used just setup and everything else was in single ISR.
But as it was bigger and bigger, code is quite slow and quite random sometimes, even PC emulator did not helpped much (probably some long operations like printing are sometimes interrupted by next interrupt depending on analog values, buttons, etc.).
Is there any guide how to maintain such a project or is there only way out start again from scratch ?
As there are few important regulations also event queue would be needed, but not sure if there is any pattern or a template to start from in case of restart. A-Star 32U4 Micro has <32kB flash and code is hard to fit in yet (there are also big fonts).
Example of font unpack code, but hope this part is quite ok:
void Adafruit_GFX::drawChar(int16_t x, int16_t y, unsigned char c,
  uint16_t color, uint16_t bg, uint8_t size) {
...
    uint8_t blockSize = 0;
    if(packed) blockSize = pgm_read_byte(&bitmap[bo++]); // for first char pick 1st bit array only
    BitStreamsReader bitStream(&bitmap[bo++], packed?blockSize:0); // ptr, blockSize(if packed)
    BitXorBuffer rowXorBuf(w); // row XOR buffer (each row is XORed with)
    bool chk;
    for(yy=0; yy<h; yy++) {
        rowXorBuf.rewind();
        for(xx=0; xx<w; xx++) {
            chk = bitStream; // read 1b
            if(packed) chk = rowXorBuf.xorMove(chk); // xor with XOR buffer
            if(chk) {
                if(size == 1) {
                    writePixel(x+xo+xx, y+yo+yy, color);
                } else {
                    writeFillRect(x+(xo16+xx)*size, y+(yo16+yy)*size,
                        size, size, color);
                }
            }
        }
    }
...

class BitStreamsReader {
public:
    BitStreamsReader(uint8_t *arr, unsigned int maxSize) {
        blockSize = maxSize;
        bitMask = 0x80;
        bytePtr = arr;
        zerosCount = 0;
        remainingBits = 0;
        markBitInit();
    }
    operator bool() {
        if(!blockSize) { // unpacked stream
            bool retVal = !!(pgm_read_byte(bytePtr) & bitMask);
            next();
            return retVal;
        } else if(remainingBits) {
            bool retVal = !!(pgm_read_byte(bytePtr) & bitMask);
            next();
            if(!--remainingBits) {
                markBitInit();
            }
            return retVal;
        } else if(zerosCount) {
            if(!--zerosCount) {
                markBitInit();
            }
            return 0;
        }
        return 0; //throw "??";
    }
private:
    void markBitInit() {
        if(blockSize) {
            if(pgm_read_byte(bytePtr) & bitMask) {
                remainingBits = blockSize;
            } else {
                zerosCount = blockSize;
            }
            next();
        }
    }
    void next () {
        if(bitMask == 0x01) {
            bitMask = 0x80;
            bytePtr++;
        } else {
            bitMask >>= 1;
        }
    };
    uint8_t *bytePtr, bitMask, zerosCount, remainingBits, blockSize;
};

class BitXorBuffer {
public:
    BitXorBuffer(int bufSize) {
        bufSize = bufSize/8+!!(bufSize&7);
        bitBuf = new uint8_t[bufSize];
        memset(bitBuf, 0, bufSize);
        rewind();
    }
    ~BitXorBuffer() {
        delete[] bitBuf;
    }
    void rewind() {
        bitMask = 128;
        bytePtr = bitBuf;
    }
    bool xorMove(bool by) {
        if(bitMask & *bytePtr) by ^= true;
        *bytePtr |= bitMask;
        if(!by) {
                *bytePtr ^= bitMask;
        }
        nextBit();
        return by;
    }
private:
    void nextBit() {
        if(bitMask > 1) {
            bitMask >>= 1; // move bit in XOR buffer
        } else {
            bitMask = 128;
            bytePtr++;
        }
    }
    uint8_t *bytePtr, *bitBuf, bitMask;
};

Refactor not to use large ISRs. ISRs should be short and quick. "Big ISR" is a fundmental flaw. You want ISRs to take as few cycles as possible (To the point of not using higher-level Arduino functions like digitalRead(). An ISR should be in-and-out in as few instruction cycles as possible.

I have had to do this many times with customers' "code". Step one is to rescue what functionality you can into libraries. Step two is to write a new program using those libraries.

@Majenko you do Arduino development for pay?

I do, though I prefer not to. I usually work with more powerful systems than Arduino.

Set a flag in the interrupt. And make your loop check for this flag to handle the situation. And make sure this loop is as fast as possible by eleminating sleep/delays. This can be done using a state machine.

Looking 4 more constructive answers. Btw things around ISR or security would be nice to have well timed in assembler, but it is not so easy as in Atmel Studio - is it ?

Where is the code to review?

No-one would understand and it is property of inventor I did some maintenance for. Question is are there any "light" design patterns or templates to start with ? Probably only public part is GFX fonts compression (to 1/2 in average), it is on my Github, but probably no need to improve or refactor...

You didn't write anything about security in the question. What do you mean by that. Also: Are you sure the code let's ISRs being interrupted? That would make the program way more difficult to refactor and might be the cause of disfunction. But without posting the code you will only get very vague answers, mostly consisting of "refactor the code to use shorter ISRs"

It is a measuring and regulation project, working even with gas, so security is very important. I think there is some enable interrupt somewhere inside ISR and it does unpredictable things sometimes - printing in random colors / position, etc. And these are very hard or impossible to reproduce out of real environment. Isn't there ready-made "template" or design pattern for something similar to real time OS ;-) ?

I will try to answer your question as good as possible, though it is quite broad.
To my knowing there is no ONE design pattern or template, that fit's all cases. But depending on the actual functions of your code you can go different ways using libraries (which are somewhat like templates in this sense).
You can get easy multitasking by using libraries like FreeRTOS. You might even find a compatible version of SafeRTOS, a sibling of FreeRTOS, which has a bigger focus on security. Though the whole RTOS thing might not be right for you and it needs your code to be mostly rewritten/redesigned.
Depending on what ISRs are used and what they are for, you might really need to use interrupts to let the device react immediately. In that case you basically have not choice, but to refactor the whole code as described in the comments (moving as much code as possible to the main loop, making the ISR drastically smaller). For this here some general advice:

First make a graph of the devices function as it should be. Identify code portions that have a common function, but them into blocks, draw arrows between the blocks to show, how they are connected logically. Then identify which portions are really time critical and what the time contrains are (e.g. Do you need the device to react to an event within a few clock cycles or is it ok, if the reaction comes a few us or ms later?). Mark how often the involved events occur at average and at maximum.
Now look at the code blocks directly. Which of them need interrupts to work and what happens with them, if interrupts are turned of during their operation (since - as you already identified - reactivating interrupts inside an ISR can get very messy). For example with interrupts off, Serial prints will not be send directly (because this relies on interrupts). Instead the libraries buffer will be filled. When the buffer is already full, a print will wait for the buffer to empty a big (which does not happen with interrupts off).
Move all code, that is not really time critical, into an if statement in the main loop function. The if statement should be activated by a flag, that would be set in the ISR (be sure to declare it volatile).
Make sure, that there is nothing blocking in your code (no delay(), no waiting for an event in an infinite loop). That also might require serious refactoring, but it's important if you want a fast reaction also outside of the ISR. You might want to look into Finite State Machines for this (they are quite easy to implement and a very powerful construct).
Keep debug prints small, so that it cannot mess up your timing.
Lastly: Make some documentation. That is mostly reglected, because it is not that rewarding, but it can save many hours for the next programmer, that needs to maintain your code.

That might seem very time consuming, difficult and not like the comprehensive guide you were looking for. That's the reason, why maintaining legacy code is mostly a real pain in the a*** and does cost companies a lot of money.
At one point or another the technical debt has to be paid. The inventor of the code clearly didn't (or he/she would't have written an ISR this big), so now you will most likely have to go the hard way.

Problem is also it has 32kB flash, RTOS would probably not work on or is there some tiny version ;-) ?

The linked site shows this: // Device:   loop() -> FreeRTOS | Additional Program Storage // Uno:         444 ->   7018   |     20%, and the Uno has only 32kB flash. Surely it is questionable, if the rest of your code is fitting on top, but that cannot be said without the actual code.

Sure not - not so long code, but there are 24px GFX & compressed fonts yet, so almost whole is full, suppose fonts consume 1/2 - 3/4 of memory. Uncompressed fonts would fill whole mem, compression makes them 1/2, so 16kB without requested GUI ?

2 compressed GFX fonts used are also in my .Net simulator here https://github.com/eltomjan/ETEhomeTools/blob/master/ArduinoSimulator/Font_big.h and https://github.com/eltomjan/ETEhomeTools/blob/master/ArduinoSimulator/Font_medium.h

So then you are stuck with refactor the ISR to get it smaller