body:
I'm trying to solve a nagging issue with external interrupts - this is for a slot car track lap count controller. It uses the Mega's 6 external interrupt lines connected to photo diodes. The HW itself works fine - yes, trust me, it's fantastic.

I have observed the following. The code in the loop() is surrounded with:

    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();

If I omit or reduce the delay amount the random firing gets worse.

The ISR is lean and mean:

    void lapDetected1() {
      lane1.lapDetected();
    }

calling the method of class Lane:

        void lapDetected() { // called by ISR, short and sweet
          now = millis();
          if ((now - finish) < laneProtectionTime) {
            return;
          }
          start = finish;
          finish = now;
          count++;
          reported = false;
        }

all the variables used are declared *volatile*.

I don't *like* to use delay and I'm seeking advice on how to correctly implement ISRs and their handling.

here's the link to the entire code on GitHub: https://github.com/gabe2001/PCLapCounterWithArduino/

Thanks for any advice I can get here!
-gabe

title: Arduino Mega external interrupts fire randomly

Answers: 2

body:
Now, you write the following:

    detachAllInterrupts();
    delay(10);
    ...
    ... process any interrupts and/or button presses
    ...
    delay(10);
    attachAllInterrupts();

I understand that you put this stuff into the loop, such that the loop in effect looks like this:

    void loop() {
        detachAllInterrupts();
        delay(10);
        ...
        ... process any interrupts and/or button presses
        ...
        delay(10);
        attachAllInterrupts();
    }

Assuming that the above is correct, then you will be enabling and disabling your interrupts in one long stream. You would often NOT disable your interrupts, because you don't know when the are available or not, then.

You should typically ENABLE the interrupts in the startup code, and then in the `loop()` you can have any Other processing you want, but not any processing referring to the interrupt processing.

The interrupt processing would take care of the button pressed etc. So - in the `lane.lapdetected1()` algorithm, you would take care of reading buttons pressed etc., and, you would have to attach the interrupt itself directly to your algorithm. I cannot see that you have told that when an interrupt has been happening, then the code execution goes to the ISR `lane.lapdetected1()` algorithm?

What you would want to do, is to setup an interrupt in the `setup()`, which is run once upon start of the program in the arduino, and then, providing that you want the interrupt on pin 2 (external pin), and the algorithm to run while you receive falling signals on the pin 2 is lapdetected1, then you could use the following:

    void setup() {
      attachInterrupt(digitalPinToInterrupt(2), lapdetected1, FALLING);
    }

Thereby you would remove the `detachAllInterrupts()`, and all the way down to `attachAllInterrupts()` from the loop construction and thereby you would be able now to process interrupts within the lapdetected1-algorithm and run what ever you would want to run, normally, from within the loop-construction.

body:
> The code in the loop() is surrounded with:

it doesn't make much sense for you to "process the interrupts" in the loop(). Use ISR instead.


body:
For my engineering class, I am building a digital scale. My team has assembled the prototype out of:

 - Arduino Uno
 - Hx711 amplifier module
 - 1 kg load cell
 - 2 push buttons
 - A 4 digit 7-segment display module we found online, but we don't know its specific name
 - HC-05 Bluetooth module, no specific manufacturer
 - Lilypad switch CR2032 battery module
 - DC-DC step up to 5V boost converter module

Our prototype works. Well, sort of (we're still trying to work out the boost converter and c2032 to work). We have diagrammed how each module connects to each other on a piece of paper. However, we want to properly diagram this in a way so we can create a PCB for it.

I have tried the Eagle and Fritzing programs. I am very inexperienced with them. I am not able to find the HC-05 and LED display .sch or .fzz files online for this, so I have came to a halt. I am not sure how each of these modules are actually wired together either.

What can I do next?

title: I have a diagram of my Arduino circuit. How do get it ready for PCB manufacture?

Answers: 2

body:
You can find the parts on [fritzing.org][1]. Anyway. You can get rid of some parts and save money if you pick the right ones. Instead of an Arduino Uno take an [Arduino Pro Mini][2] with 3.3V and [HC-05][3] without a breakout for 5V Arduinos.

Doing that everything will smaller and running on 3.3V thus getting rid of the DC-DC converter.

  [1]: http://forum.fritzing.org/c/parts-submit
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardProMini
  [3]: http://forum.fritzing.org/t/hc-05-custom-board/2443

body:
You can try to implement the circuit without an Arduino board [on a breadboard][1]. So you can get more information about what works and what not. From there after making necessary changes (if there is any), you can draw the schematics and create a PCB layout using Orcad, Eagle etc.There are a lot of tutorials out there about PCB designing.

  [1]: https://www.arduino.cc/en/Main/Standalone


body:
I'm using an Arduino Uno and two (3-pin) rotary encoders for a project. Since the loop takes a bit long and accuracy is important, I'd like to use interrupts to read the values from the rotary encoders. Also, pins 2 and 3 are occupied so I can't use hardware interrupts.

I'm using the Rotary library ([github link][1]) for the rotary encoders and the EnableInterrupt library ([github link][2]) for external interrupts. The Rotary library includes an interrupt example, but I couldn't manage to modify it to work with pin change interrupts. This is my current state (test code):

    #include <EnableInterrupt.h>
    #include <Rotary.h>

    Rotary r = Rotary(2, 3);

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

      /* Original interrupt setup:
      PCICR |= (1 << PCIE2);
      PCMSK2 |= (1 << PCINT18) | (1 << PCINT19);
      sei();
      */

      enableInterrupt(2, interruptFunction, CHANGE);
      enableInterrupt(3, interruptFunction, CHANGE);
    }

    void loop() {

    }

    void interruptFunction() {

      Serial.println("Int. called");

      unsigned char result = r.process();
      if (result == DIR_NONE) {
        // do nothing
      }
      else if (result == DIR_CW) {
        Serial.println("ClockWise");
      }
      else if (result == DIR_CCW) {
        Serial.println("CounterClockWise");
      }
    }

Everytime I turn the encoder for one step, the interruptFunction gets called a bunch of times (about 2~4) but the r.process() call never returns a value.

My current guess is that this has something to do with the rotary encoder outputting gray code, but I'm not quite sure how my approach differs from the Rotary interrupt example using hardware interrupts.

Hope you can help!

  [1]: https://github.com/brianlow/Rotary
  [2]: https://github.com/GreyGnome/EnableInterrupt

title: Using rotary encoders with pin change interrupts

Answers: 5

body:
I too had this problem. I chased my tail in SW for hours. I was making the ISRs non-reentrant (assumed they accidentally were), I was doing SW debouncing etc. I even looked at the signal on a scope but did not see any significant bounces.
I eventually added 0.1uF capacitors to the inputs and that solved all my problems with the ISR.
So don't trust the encoder manufacturers, there WILL be signal bounce and your Arduino WILL detect it and throw multiple interrupts.
Good luck with your project!
LDP

body:
> Everytime I turn the encoder for one step, the interruptFunction gets
> called a bunch of times (about 2~4)

This is due to contact bounces. You should either implement a hardware debouncing circuit (a simple R-C filter could be enough. Do not connect instead large capacitors directly in parallel to your contacts, as when the contact closes, the energy stored on the capacitor will damage over time the contacts. Using large capacitances on an input can also lead to problems when power is removed), or better a good software debouncing strategy.

For instance, when the interrupt is called the first time, disable the pin-change interrupts. Then set up a timer, which will trigger an interrupt when it expires (the time should be larger than the bounce time, usually several ms or more). Then in the timer interrupt, first put your code:

      unsigned char result = r.process();
      if (result == DIR_NONE) {
        // do nothing
      }
      else if (result == DIR_CW) {
        Serial.println("ClockWise");
      }
      else if (result == DIR_CCW) {
        Serial.println("CounterClockWise");
      }

end re-enable the pin-change interrupts.

      enableInterrupt(2, interruptFunction, CHANGE);
      enableInterrupt(3, interruptFunction, CHANGE);

> but the r.process() call never returns a value.

r.process() will ALWAYS returns a value. Maybe you did mean that it returns DIR_NONE ?

body:
check the library to see if it debounces the input.

if not, write your own code. usually state machine-based approaches are very resistant to switch bounces.

body: The correct solution is to use a debouncing circuit. The MC14490 is a hex debouncing circuit and is perfect for this type of application. No need to block interrupts or set timers. It's available as either SMD or thru hole.

body:
Code Correction 7th October - Tidy code as per comments
Code Correction 7th October - proper reading of rotary encoder

 Uses the Pin Change interrupts to allow increment and decrement of the 2 rotary encoders within an interrupt service routine using arduino (in my case nano) with ATMEGA328P chip. Need to add 2 x 104 (0.1uF caps) at the rotary encoder between each pin and the centre ground pin to stop the debounce, doesnt work without the capacitors added. Does not need any library. Watched the Tutorial: Pin Change Interrupts on the Arduino by makecourse which helped understand the Pin change interrupts, will help to watch this if have a different version of arduino so know what digital pins relate to what interrupts.

              //*******************************************  rotary encoder ************************************************************
              #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))    //shortcut way to clear a bit in a register
              #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))     //shortcut way to set a bit in a register

              #define Encoder1pin 3 //corresponds to PCINT19
              #define Encoder2pin 4 //corresponds to PCINT20
              #define Encoder3pin 5 //corresponds to PCINT21
              #define Encoder4pin 6 //corresponds to PCINT22
              #define Encoder5pin 7 //corresponds to PCINT23

              unsigned long encoderPos1 = 100;
              unsigned long oldEncPos1 = 0;
              unsigned long encoderPos2 = 100; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
              unsigned long oldEncPos2 = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)

              volatile byte portDstatus;

              volatile bool readingEncoder1pin = 0;
              volatile bool readingEncoder2pin = 0;
              volatile bool readingEncoder3pin = 0;
              volatile bool readingEncoder4pin = 0;
              volatile bool lastreadingEncoder1pin = 0;
              volatile bool lastreadingEncoder2pin = 0;
              volatile bool lastreadingEncoder3pin = 0;
              volatile bool lastreadingEncoder4pin = 0;

              void setup() {

                Serial.begin(9600);

              //*************************************************** rotary encoder ******************************************************************************
                pinMode(Encoder1pin, INPUT);//define pin as INPUT
                digitalWrite(Encoder1pin, HIGH);//connect the internal pull-up resistor - this will yield a HIGH readout if the switch is open.
                pinMode(Encoder2pin, INPUT);
                digitalWrite(Encoder2pin, HIGH);
                pinMode(Encoder3pin, INPUT);
                digitalWrite(Encoder3pin, HIGH);
                pinMode(Encoder4pin, INPUT);
                digitalWrite(Encoder4pin, HIGH);
                pinMode(Encoder5pin, INPUT);
                digitalWrite(Encoder5pin, HIGH);

                //setting up the interrupt pins:   //I needed to set all of these otherwise the serial monitor does not read the byte correctly -
                                                   // and it doesnt work.

                sbi (PCICR, PCIE2); // enable interrupt PCI2);
                sbi (PCMSK2,PCINT23); // set the interrupt control bits for pins 7-3. These bits control whether the pins can trigger the interrupt or not.
                sbi (PCMSK2, PCINT22);
                sbi (PCMSK2, PCINT21);
                sbi (PCMSK2, PCINT20);
                sbi (PCMSK2, PCINT19); // we do not want to set interrupt control for pins 0 or 1 since this is serial reading .

              //******************************************************************* LED *********************************************************************
              }

              void loop()

                  {
                   }

              ISR(PCINT2_vect) // Interrupt Service Routine. This code is executed when a state change occurs on a pin
              {

                    portDstatus=PIND;
                   readingEncoder1pin = bitRead(portDstatus,3);
                   readingEncoder2pin = bitRead(portDstatus,4);
                 if(lastreadingEncoder1pin == 1 && lastreadingEncoder2pin == 0 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
                  {
                      encoderPos1 ++;
                       lastreadingEncoder1pin = readingEncoder1pin;
                       lastreadingEncoder2pin = readingEncoder2pin;
                  }

                  else if(lastreadingEncoder1pin == 0 && lastreadingEncoder2pin == 1 && readingEncoder1pin == 1 && readingEncoder2pin == 1)
                  {
                    encoderPos1 --;
                      lastreadingEncoder1pin = readingEncoder1pin;
                      lastreadingEncoder2pin = readingEncoder2pin;;
                  }
                  else
                    {
                       lastreadingEncoder1pin = readingEncoder1pin;
                       lastreadingEncoder2pin = readingEncoder2pin;
                    }

        //  reading the second encoder:

                   readingEncoder3pin = bitRead(portDstatus,5);
                   readingEncoder4pin = bitRead(portDstatus,6);

                 if(lastreadingEncoder3pin == 1 && lastreadingEncoder4pin == 0 && readingEncoder3pin == 1 && readingEncoder4pin == 1)
                  {

                      encoderPos2 ++;
                       lastreadingEncoder3pin = readingEncoder3pin;
                       lastreadingEncoder4pin = readingEncoder4pin;
                  }

                  else if(lastreadingEncoder3pin == 0 && lastreadingEncoder4pin == 1  && readingEncoder3pin == 1 && readingEncoder4pin == 1)
                  {
                    encoderPos2 --;
                      lastreadingEncoder3pin = readingEncoder3pin;
                      lastreadingEncoder4pin = readingEncoder4pin;;
                  }
                  else
                    {

                       lastreadingEncoder3pin = readingEncoder3pin;
                       lastreadingEncoder4pin = readingEncoder4pin;
                    }
                 // serial print for testing only then remove from ISR
              Serial.print(encoderPos1);
              Serial.println(encoderPos2);

                 }


body:
I'm having trouble understanding how to activate interrupts so that they operate only when they should. With this code, I seem to get erratic performance when I either attach or unattached interrupts, or when I try using noInterrupts.
What I am trying to accomplish is to deactivate the alarm function from running until a slight delay is initiated upon hitting an incorrect key. That would allow leaving the premises without triggering the interrupt. Does noInterrupt only affect the function in which it is placed??

    ///////////////////////// initialize & includes //////////////////////////
    #include "SIM900.h"
    #include "sms.h"
    #include "Keypad.h"
    #include <GSM.h>
    SMSGSM sms;
    //To change pins for Software Serial, use the two lines in GSM.cpp.
    int PIR_SensorPin = 2;
    int LED_OutPin = 11; //green
    int Alarm_OutPin = 12; //red
    int alarm_count = 0;
    volatile boolean trigsensor = false;
    boolean away = false;
    const byte interruptPin = 2;
    int z = 0;
    int i = 0;
    int timeout = 10000;

    //////////////////////////// setup keyPad //////////////////////////
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    char keys[ROWS][COLS] =
    {
      {
        '1', '2', '3', 'A'
      }
      ,
      {
        '4', '5', '6', 'B'
      }
      ,
      {
        '7', '8', '9', 'C'
      }
      ,
      {
        '*', '0', '#', 'D'
      }
    };
    byte rowPins[ROWS] = {
      6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
    }; // connect to the row pinouts of the keypad
    byte colPins[COLS] = {
      3, A0, A1, A4
    }; // connect to the column pinouts of the keypad
    Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    const char PIN[5] = {
      '9', '6', '7', '9', '#'
    }; // PIN number
    char key_input[5] = {
      0, 0, 0, 0, 0
    }; // used for comparison

    //////////////////////////////// setup ///////////////////////////////////
    void setup() {
      Serial.begin (9600);  // Establish Serial connection;
      pinMode (LED_OutPin, OUTPUT);   // Set pinMode.
      pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
      pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
      digitalWrite (LED_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
      digitalWrite (PIR_SensorPin, LOW);
      Serial.println ("Studio Alarm starting up."); // Serial message that GSM shield is starting up
      if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
        Serial.println ("Status = Network READY");
        digitalWrite (LED_OutPin, HIGH);
      }
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); // PIR as interrupt
      Serial.println ("System Ready");
    }

    //////////////////////////////// void loop ///////////////////////////////////
    void loop()
    {
      readKeypad(); // Serial.println ("at keypad");
      if (trigsensor == true) {
        alarm ();
      }
    }

    ///////////////////////////// void trigger ///////////////////////////////////
    void trigger() {
      trigsensor = true;
      alarm();
    }

    //////////////////////////////// void alarm ///////////////////////////////////
    void alarm() {
      Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("trigsensor="); Serial.println (trigsensor);
      Serial.println ("at Alarm");
      if (away == true && trigsensor == true) {
        noInterrupts();////////////////////////////////
        // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
        Serial.println ("MOTION detected: SMS Sent");
        for (alarm_count = 0; alarm_count <= 5; alarm_count++) { // Cycle outputs if triggered
          digitalWrite (Alarm_OutPin, HIGH); delay (1000); // On/Off/On/Off/Off
          digitalWrite (Alarm_OutPin, LOW); delay (500);
          digitalWrite (LED_OutPin, HIGH); // delay (1000);
          //   digitalWrite (LED_OutPin, LOW); delay (1000);// End by turning off light
          Serial.println (alarm_count);
        }
      }
      trigsensor = false;
      readKeypad();
    }

    //////////////////////////////// read Keypad ///////////////////////////////////
    void readKeypad() {
      char key = keypad.getKey();
      if (key != NO_KEY) { // if a keypad input
        key_input[z] = key;
        tone(10, 900, 100);
        Serial.print ("Key_input["); Serial.print(z); Serial.print ("] = "); Serial.println(key);
        z++;
        if (z >= sizeof(key_input)) {
          z = 0;
        }
        switch (key) {
          case '*': // resets key_inputs to "0"
            z = 0;
            break;
          case '#': // pressed to "enter"
            z = 0;
            for ( i = 0;   i < 4 ;  i++ ) {
              Serial.print(key_input[i]);
            }
            Serial.println ("-------");
            delay(100); // for extra de-bounce
            checkPIN();
            break;
        }
      }
    }

    //////////////////////////////// check PIN ///////////////////////////////////
    void checkPIN() {
      Serial.println ("@ checkPIN ");
      int correct = 0;
      int i;
      for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
        if (key_input[i] == PIN[i]) {
          correct++;
        }
      }
      if (correct >= sizeof(PIN) - 1) {
        Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
        correctPIN();
      }
      else {
        incorrectPIN();
      }
    }

    //////////////////////////////// correct PIN ///////////////////////////////////
    void correctPIN() {              // do this if correct PIN entered
      Serial.println ("@ correct PIN ");
      digitalWrite (LED_OutPin, HIGH);
      digitalWrite (LED_OutPin, LOW);
      trigsensor = false;
      away = false;
      readKeypad();
    }

    ///////////////////////////// incorrect PIN ///////////////////////////////////
    void incorrectPIN() {           // do this if incorrect PIN entered
      noInterrupts();
      Serial.println ("@ incorrect PIN ");
      //detachInterrupt(0); Serial.println ("interrupt off 1");
      trigsensor = false;
      away = true;
      digitalWrite (LED_OutPin, HIGH);
      delay(timeout);
      attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH); Serial.println ("interrupt on 2");
      alarm(); Serial.println ("here");
    }

title: Trying to understand interaction of interrupts, noInterrupts and delays

Answers: 1

body:
Well, yes, I think attaching and detaching interrupts isn't really something that you should do to often. It also won't really make your code very much more readable.

You may have a look at programming (embedded systems) in general. A technique I like to do is making a (non-blocking) state machine. In this way you don't even need interrupts (you can actually have interrupts if you want, though).

Also, it may be worth noting that making your code more readable and understandable is likely going to improve your "idea of what is going on" and thus improve it's reliability. This is commonly done by designing and applying "scope" to your code. You've done well on the keypad functions, giving them a sane name and reasoning. You could've put them in a class, but that's not where the errors are at.

Basically, your alarm has a few states:

 - Armed
 - Unarmed
 - Alarm!
 - Just activated

From these, you can form a state diagram.
Usually, "events" lead to the state of your system being changed.
For example:

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

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

<!-- End schematic -->

(Sorry for "abusing" the schematic editor (:  )
As you can see, events can be user interaction/sensors/timing, basically anything.

By designing your code in a state diagram, you get an idea of what you want your machine to do, at what moment. And what other states it can go to from there (and when/how).

Your code will become something along the lines of:

setup

    enum STATE{
      armed,
      unarmed,
      justActivated,
      alarm
    };

    STATE systemState = unarmed;
    long timeGettingArmed;

loop

    switch(systemState){
       case armed:
       if(breakinSensor.check() == HIGH){
          systemState = alarm;
       }else if(keyPad.check() == deactivated){
          systemState = unarmed;
       }
       break;
       case unarmed:
       if(armButton.check() == HIGH){
          timeGettingArmed = millis(); // Or you could just do a delay here.
          systemState = justActivated;
       }
       break;
       case justActivated:
       if(timeGettingArmed + waitTime < millis()){
         systemState = armed;
       }
       break;
       case alarm:
       if(keyPad.check() == deactivated){
         systemState = unarmed;
       }else{
         beep();
       }
       break;
    }

Ofcourse you'll have to highly adapt this code to suit your needs, I doubt it will even compile. But it can also be a part of designing your program, try just writing it out in words (or explaining it to someone), before you program it.

*You could make use of the interrupts by checking in the interrupt if the state is "armed" and then setting the state to "alarm". This way you avoid the interrupt messing up any of your logic and having to disable it.

The cool thing of this "non-blocking" (if you don't use delays) state machine is that you can actually add more statemachines to it, and it will seem like the processor does everything at the same time. This is because it skips rather fast through the "i/o checks".


body: This is mostly a conceptual question. Is it possible to have two scripts running on an Arduino, where one is a Julia script, and one is a Python script or something like that?

title: Running Multiple Languages on Arduino

Answers: 1

body:
Basically no, because you can't run either Julia *or* Python, let alone both together.

Bear in mind also what an Arduino is (what most of them are, anyway): a low (computational) power microprocessor with a tiny amount of RAM. No operating system, no multi-tasking. Not in the same league as, for example, a Raspberry Pi.


body:
I am using 2 adafruit PWM servo shield in order to generate 25 PWM signals. In particular I am using this shield: https://www.adafruit.com/products/1411

A python script sends the commands to the Arduino (Mega 2560) through pyserial. The commands are like "A0 P1 S500\n". Each argument separated by a space. The first chooses the shield, the second one the pin, and the third one the speed.

The code running in the Arduino is as follows:

    #include <Adafruit_PWMServoDriver.h>

    #define BUFFER_SIZE 200

    // Init both adafruit boards
    Adafruit_PWMServoDriver pwm0 = Adafruit_PWMServoDriver(0x40);
    Adafruit_PWMServoDriver pwm1 = Adafruit_PWMServoDriver(0x41);

    int read_command(char *buffer)
    {

     static int pos = 0;
     int rpos;

     if (Serial.available() > 0) {
      Serial.println(Serial.available());
      char readch = Serial.read();

      switch (readch) {

       case '\n':
        rpos = pos;
        pos = 0; // Reset position index ready for next time
        Serial.println(buffer);
        return rpos;

       default:

        if (pos < BUFFER_SIZE -1) {
         buffer[pos++] = readch;
         buffer[pos] = '\0';
        } else {
         Serial.println("666"); //buffer overflow
        }
      }
     }
     // no end line or char found, return -1
     return -1;

    }

    void parse_command(char* command)
    {

     char* parameter;
     parameter = strtok(command, " ");
     long shield, pin, speed;

     while (parameter != NULL) {

      switch(parameter[0]) {

       case 'A':
        shield = strtol(parameter+1, NULL, 10);
        break;

       case 'P':
        pin = strtol(parameter+1, NULL, 10);
        break;

       case 'S':
        speed = strtol(parameter+1, NULL, 10);
        break;

      }
      parameter = strtok(NULL, " ");
     }

     for (int x=0; x < BUFFER_SIZE; x++)
      command[x] = '\0';

      if (shield == 0)
        pwm0.setPWM(pin, 0, speed);

      if (shield == 1)
        pwm1.setPWM(pin, 0, speed);

    }

    void setup()
    {

      Serial.begin(9600);
      Serial.flush();

      pwm0.begin();
      pwm0.setPWMFreq(100);  //Max is 1600, Kevin was using 1000
      pwm1.begin();
      pwm1.setPWMFreq(100);

    }

    void loop()
    {

      static char buffer[BUFFER_SIZE];

      if (read_command(buffer) > 0)
        parse_command(buffer);

    }

As said, I am sending the commands from a Python script, where for example I have a function called "activate all", that will send 25 commands like "A0 P1 S500\n" (obviously with different values after the A and the P) to the serial port. I also have a function called "disable all", which is very similar to the previous command, but setting the S to 0 so like "A0 P1 S0\n".

So, as I start the serial communication, if I execute from Python "activate_all", I can how all the PWM signals are generated at the same time. I know it is actually 1 by 1, but it is fast enough to seem simultaneously to the human eye. If I then send a disable_all, I can see how all the PWM signals are set to 0 at the same time.

This works as expected for a while, but after some point, when I send an activate_all, it will indeed activate all of them, but it activates each PWM signal one by one, with a delay of around 1 second between activations (so you can clearly see them going one by one), and a very similar effect when disabling them all. From this point on, which seems slightly different each time, every time I want to activate more than one pwm signal at the same time, it will add this 1s delay between activations.

The only way I have to fix this is to send from the python a "flush()". which seems to be fix it. Doing flushes from the Arduino code, like when for example serial.available is 0, doesnt seem to fix it.

I don't know what exactly I am doing wrong. I guess the way I am handling the communication buffer is wrong, but I haven't seen where my mistake is.

A very similar code to the one pasted here was used in another project, in that case it was interfaced with Labview, and in that case everything seem fine.

In case you wonder about the code running in the Python script, it is like this:

    import serial, time, json

    class BZBoard:

        def __init__(self, port):

            self.ser = serial.Serial(port, 9600, timeout=120)
            time.sleep(2) # serial docs recommend a wait just after connection
            self.ser.flush(); self.ser.flushInput(); self.ser.flushOutput();

            self.motors = {
                just naming the pins
                }

        def __del__(self):

            self.disable_all()
            self.ser.close()
            del self.ser

        def close(self):

            self.disable_all()
            self.ser.close()
            del self.ser

        def activate_motor(self, motor_code, speed=300):
            ''' code as in A1 or C2 as marked in the actual board. See the dict motors'''

            shield, pin = self.motors[motor_code]
            command = "A%d P%d S%d\n" % ( shield, pin, speed )
            self.ser.write(command.encode())

        def activate_all(self, speed=300):

            for key in self.motors.keys():
                self.activate_motor(key, speed)

        def disable_motor(self, motor_code):

            shield, pin = self.motors[motor_code]
            command = "A%d P%d S0\n" % ( shield, pin )
            self.ser.write(command.encode())

        def disable_all(self):

            for key in self.motors.keys():
                self.disable_motor(key)

    if __name__ == "__main__":

        board = BZBoard("/dev/ttyACM0")

So the user will do for example a lopp that repeats itself 20 times, where it will activate_all, wait 1 second, disable_all, wait 1 second. The first 10 iterations or so, everything will be fine and the PWM are generated all of them at the same time (with respect to the human eye), but after that, the PWM signals are generated 1 by 1, with a delay of 1s or so between them.

title: Initially my Arduino executes a series of PWM signals simultaneously, but after some iterations it adds around a second between PWM executions

Answers: 1

body:
There seems to be reason to think about filled buffers causing stalls and timeouts, but comments regarding 5-second sleeps between trials seem to rule that out.  To debug what's actually happening, you might blink an LED each time you receive a character, and another LED each time you call your `parse_command()` routine; and if you have an oscilloscope, look at the serial transmissions back and forth to see whether delay is due to something at the Arduino end vs at the host end.

That said, I think it would make sense to simplify the protocol by getting rid of your input buffer and just processing input as it comes.  For example, you could use the following letters as post-fix actions.

    A  Select shield 1
    B  Select shield 2
    P  Set pin number, eg 11P selects pin 11
    S  Set speed, eg 472S sets speed to 472
    N  Send current speed to current pin, then increment pin number

For example, the command sequence for “disable_all” could look like:

    0S0PANNNNNNNNNNNN 0PBNNNNNNNNNNNNN

This is easy to parse on the fly; declare `int val=0` and any other needed variables before `loop()`, then within `loop()` say:

      char inc;   // For incoming character
      while (Serial.available()) { // Get characters
        inc = Serial.read();
        if (inc >= '0' && inc <= '9') {
          val = 10*val + (inc-'0');
        } else {
          switch (toupper(inc)) {
          case 'A':
            board = 0;
            break;
          case 'B':
            board = 1;
            break;
          case 'P':
            pin = val;
            break;
          case 'S':
            speed = val;
            break;
          case 'N':
            if (PinNumberIsOk(board, pin))
              pwm[board].setPWM(pin, 0, speed);
            ++pin;
            break;
          default :
            ; // handle blanks, returns, whatever
          }
          val = 0;  // Set val to zero on any non-digit
        }

As another example, the sequence `4PA 11SN13SN17SN` would send speeds 11, 13, and 17, respectively, to motors 4, 5, 6 on the first shield.


body:
RTL8170 is a new module, which is in many ways better than the old ESP8266 module. We are able to flash this module with Arduino using an Ameba Writer, and it should be able to support any code that is supported by the ESP (with some adjustments). It has been officially supported by Realtek's environment but it does not use all the GPIO (only 2). Luckily, pvvx developed an environment for Arduino IDE, which we can install and use through this tutorial: https://hackaday.io/project/19163/logs

I have uploaded a modified SimpleWebServerWiFi sketch from Ameba RTL8170 examples by both trying the official Realtek and pvvx's environments, and using LEDs to troubleshoot (I don't have an SPI/I2C LCD or a Serial-to-USB) I found the module being able to connect to my Samsung's hotspot but unable to communicate with the module because server.available() never turns true. When my module connects to my Samsung Note 4's hotspot, I see its IP (192.168.43.123) and fail to connect to it via a browser (on the phone or with a Windows laptop). Android port scanning apps indicate that the target IP address of the module has no open ports. Code below.

Update2: I've made adjustments to the code according to suggestions, but it still didn't respond. Updated code below:

       /*-----------------------------------------------------------------|
      |  Build using pvvx's enviroment: https://github.com/pvvx/RtlDuino  |
      |  Tutorial: https://hackaday.io/project/19163/logs                 |
      |=================================================================*/

    #include <WiFi.h>

    char ssid[] = "WiFi_SSID";      //  your network SSID (name)
    char pass[] = "password";   // your network password
    int keyIndex = 0;   // your network key Index number (needed only for WEP)
    String currentLine = "";   // make a String to hold incoming data from the client

    int status = WL_IDLE_STATUS;
    WiFiServer server(80);

    void setup() {
      pinMode(1,OUTPUT);

      //Serial.begin(38400);      // initialize serial communication
      pinMode(LED_BUILTIN, OUTPUT);      // set the LED pin mode
      // check for the presence of the shield:
      if (WiFi.status() == WL_NO_SHIELD) {
        //Serial.println("WiFi shield not present");
        while (true); // don't continue
      }
      String fv = WiFi.firmwareVersion();
      if (fv != "1.1.0") {
        //Serial.println("Please upgrade the firmware");
      }

      // attempt to connect to Wifi network:
      while (status != WL_CONNECTED) {
        //Serial.print("Attempting to connect to Network named: ");
        //Serial.println(ssid);         // print the network name (SSID);

        // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
        status = WiFi.begin(ssid, pass);
        // wait 0.2 seconds for connection:
        delay(200);
      }

      server.begin();                   // start the web server on port 80

    }

    void loop() {

      WiFiClient client = server.available();   // listen for incoming clients

      if (client) {                             // if you get a client,

        //Serial.println("new client");           // print a message out the serial port
        while (client.connected()) {            // loop while the client's connected

          if (client.available()) {             // if there's bytes to read from the client,

            char c = client.read();             // read a byte, then
            //Serial.write(c);                    // print it out the serial monitor
            if (c == '\n') {                    // if the byte is a newline character

              // if the current line is blank, you got two newline characters in a row.
              // that's the end of the client HTTP request, so send a response:
              if (currentLine.length() == 0) {

                // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                // and a content-type so the client knows what's coming, then a blank line:
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Length: 88");
                client.println("Content-Type: text/html");
                client.println("Connection: Closed");
                client.println();

                // the content of the HTTP response follows the header:
                client.print("Click here turn the BUILTIN_LED on
");
                client.print("Click here turn the BUILTIN_LED off
");

                // The HTTP response ends with another blank line:
                client.println();
                // break out of the while loop:
                //break;
              } else {    // if you got a newline, then clear currentLine:
                //digitalWrite(1,HIGH); // Doesn't turn ON
                currentLine = "";
              }
            } else if (c != '\r') {  // if you got anything else but a carriage return character,
              //digitalWrite(1,HIGH); // Turns ON
              currentLine += c;      // add it to the end of the currentLine
            }
            //digitalWrite(1,HIGH); // Turns ON
            // Check to see if the client request was "GET /H" or "GET /L":
            if (currentLine.endsWith("GET /H")) {
              digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
            }
            if (currentLine.endsWith("GET /L")) {
              digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
            }
          }
        }
        //digitalWrite(1,HIGH); // Turns ON
        // close the connection:
        client.stop();
      }
    }

**Update 1:**

I am still unable to fix the code. If no one can fix this code, please feel free to provide a totally new code.

P.S.: If this question keeps stagnating, I'll remove it and recreate it.

Any help is appreciated. Thank you!

title: RTL8170 Web Server - client unable to connect

Answers: 2

body:
Inside the while loop, where you give the link to click you have a break that prevents the handling of the answer from the client.

I would reconsider the use of that break and structure the code to not use it at all.

body:
If you must use `String`, get its declaration out of `loop()`. You're only fragmenting your heap and reducing available RAM. Instead, declare it in the file scope and reserve sufficient space for a request line with the `reserve()` method in your `setup()`.

Though response headers are supposed to be case-insensitive, it's still a good idea to follow the 'standard', spaces and all, like this for instance:

    HTTP/1.1 200 OK
    Content-Length: 88
    Content-Type: text/html
    Connection: Closed

Try sending all the fields above, especially the content length. And get rid of the `break` like mico said. There's no way your builtin LED will turn on or off if you keep breaking right after you respond to the client.


body:
I am using an XBee-PRO S2b module. I have sent data from the router Xbee to the coordinator Xbee.

Now I want to send a command packet from the coordinator to the router Xbee to set a pin high.

My coordinator is in API mode and the router is in AT mode.

Can anyone say how to do that?

title: How to send command from coordinator to router in Xbee?

Answers: 1

body: In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s


body:
Im having a problem with my arduino code.Im trying to make an alarm system with a pir sensor.So when the pir activates and the buzzer starts buzzing i want to be able to type a set password in the keypad and the buzzer should stop buzzing. since my passcode is 4-digit (1331) I wrote this code, but it`s not working.

     while(i<=4,i++)
    {
    char key = keypad.getKey();

    pass.append(key);
    }
    if(pass.evaluate())
    {
      digitalWrite(buzzer, LOW);
        keypad.waitForKey();
        delay(6000);
    }
My idea is that the program checks 4 times for the pressed key and adds it to the guessed password (im using the password library and the password is defined as well as int i=0;)
But for some reason when I type 1331 the buzzing continues. Please help me with that project and excuse my grammar, English is not my native language.

edit:
the full code:

    #include <Password.h>
    Password pass = Password( "1331" );

    #include <Keypad.h>
    int sensor = 11;
    int buzzer = 10;
    int i = 0;

    const byte rows = 4; //four rows
    const byte cols = 4; //four columns
    char keys[rows][cols] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };

    byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
    byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

    void setup() {
    pinMode(sensor, INPUT);
    pinMode (buzzer, OUTPUT);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    keypad.waitForKey();
    digitalWrite(buzzer,HIGH);
      delay(125);
      digitalWrite(buzzer, LOW);
      delay(6000);

    }

    void loop() {

      char state = digitalRead(sensor);
      if (state == HIGH)
      {
        digitalWrite(buzzer, HIGH);
        while(i<4,i++)
        {
        char key = keypad.getKey();
        //keypad.waitForKey(); not sure if i should use that

        pass.append(key);
        }
        if(pass.evaluate())
        {
          digitalWrite(buzzer, LOW);
            keypad.waitForKey();
            delay(6000);
        }

      }
          }

title: How do I check if a password is right? (keypad input)

Answers: 4

body:
 1. Without knowing how the pass.* works, it will be impossible to pinpoint the problem.
 2. 'key' gets an ASCII value. Is that would you are expecting?
 3. Does pass.* reset (start over) once 4 digits?
 4. Just a guess, but I believe that *.waitForKey() does not consume the key.
 5. The algorithm only *gets* the key four times; then, it checks.

body:
This is classical indexing problem:

while with <= 4 actually runs five (5) rounds.

So, use < 4.

body:
This is completely the wrong way of doing a loop. Since Arduino uses C++ I made this test program:

    #include <stdio.h>

    int main (void)
      {
      printf ("starting\n");
      int i = 0;
      while(i<=4,i++)
         {
         printf ("%i\n", i);
         }
      printf ("done\n");
      return 0;
      }

This prints:

    starting
    done

Note that the loop is executed **zero** times. This is because you used the "comma operator".

From https://en.wikipedia.org/wiki/Comma_operator you can see:

> In the C and C++ programming languages, the **comma operator** (represented by the token `,`) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

In other words, your loop adds one to `i` and checks if it is zero (before adding one). Thus the loop terminates immediately.

A better construct would be:

    for (i = 0; i < 4; i++)
       {
       // whatever
       }

That is the standard C/C++ way of doing a loop a fixed number of times.

---

Also, most keypad libraries return `NO_KEY` if the user hasn't pressed a key.

You should test if `keypad.getKey()` returns `NO_KEY` and if so do nothing.

All your code would have done (if it had executed 4 times) was get 4 times `NO_KEY` (in a few microseconds) which would not be the correct password.

body:
In case anyone was wondering, heres the code I came up with and now it works.

    #include <Keypad.h>
    int sensor = 11;
    int buzzer = 10;
    int red = 12;
    int i = 0;
    String Pass = "1331";
    String tempPass = "";

    const byte rows = 4; //four rows
    const byte cols = 4; //four columns
    char keys[rows][cols] = {
      {'1','2','3','A'},
      {'4','5','6','B'},
      {'7','8','9','C'},
      {'*','0','#','D'}
    };

    byte rowPins[rows] = {8, 7, 6, 9}; //connect to the row pinouts of the keypad
    byte colPins[cols] = {5, 4, 3, 2}; //connect to the column pinouts of the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );

    void setup() {
    pinMode(sensor, INPUT);
    pinMode (buzzer, OUTPUT);
    StartingBuzz();
    keypad.waitForKey();
    digitalWrite(red,HIGH);
    digitalWrite(buzzer,HIGH);
      delay(200);
      digitalWrite(buzzer, LOW);
      delay(60000);
    }

    void StartingBuzz()
    {
    digitalWrite(buzzer, HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer, HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
    delay(125);
    digitalWrite(buzzer,HIGH);
    delay(125);
    digitalWrite(buzzer, LOW);
      }

    void UnlockBuzz()
    {
      delay(200);
           tone(buzzer,3250,200);
           delay(300);
           tone(buzzer,3500,200);
           delay(300);
           tone(buzzer,4000,200);
      }

    void loop() {
      i=0;//resets the password-checking loop.
      tempPass = "";//resets the guessed password.
      char state = digitalRead(sensor);
      if (state == HIGH)
      {
        digitalWrite(buzzer, HIGH);
        A:
        {
        while(i < 4)
        {
        char key = keypad.getKey();
        if(key != NO_KEY)
        {
          tempPass += key;
          i++;
          }
        }
        }
        if(Pass == tempPass)
        {
          digitalWrite(buzzer, LOW);
          digitalWrite(red, LOW);
          UnlockBuzz();
          keypad.waitForKey();
          digitalWrite(buzzer,HIGH);
          delay(200);
          digitalWrite(buzzer, LOW);
          digitalWrite(red, HIGH);
          delay(60000);
        }
        else
        { tempPass = "";
           i=0;
          goto A;
          }

      }
    }


body:
Please check the arduino program given below and help me to find out error.
The program is for following hardware.
GSM 800 module
Arduino Uno board
Limit switch(2)

We place two limit switch at main door & back door as main door is open the message will be send that is Main door is open & when it closed it will send message Main door is closed. This is same for Back door also.

We run this program & it run but it sends the massage repeatedly after some time.
Please help me to find out error..

***my ARDUINO code is***

    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;
    bool i = true;
    bool j = true;
    bool k = true;
    bool l = true;
    int buttonState1 = 0;
    int buttonState2 = 0;
    void setup() {

      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void loop() {
      buttonState1 = digitalRead(Main);
      if (buttonState1 == HIGH && i == true ) {
        digitalWrite(Main_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Main Door is closed");
        Serial.write(0x1A);
        delay(5000);
        i = false;
        j = true;
      }
      else
      { if (buttonState1 == LOW && j == true )

        { digitalWrite(Main_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91---------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Main Door is open");
          Serial.write(0x1A);
          delay(5000);
          i = true;
          j = false;
        }
      }

      buttonState2 = digitalRead(Store);
      if (buttonState2 == HIGH && k == true) {

        digitalWrite(Store_led, HIGH);
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"");
        Serial.print("+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print("Store room is Closed");
        Serial.write(0x1A);
        delay(5000);
        k = false;
        l = true;
      }
      else
      { if (buttonState2 == LOW && l == true)
        {
          digitalWrite(Store_led, LOW);
          Serial.println("OK");
          delay(1000);
          Serial.print("AT+CMGF=1\r\n");
          delay(500);
          Serial.print("AT+CMGS=\"");
          Serial.print("+91------------------");
          Serial.print("\"\r\n");
          delay(5000);
          Serial.print("Store room is Open");
          Serial.write(0x1A);
          delay(5000);
          k = true;
          l = false;
        }
      }
    }

title: door protector arduino program

Answers: 1

body:
I can't see any obvious flaws in the code other than the excessive use of delay. However you could make your code a lot cleaner which makes it easier to spot the errors.<br>
The version below has the duplicate lines moved into a function and instead of using the poorly named i,j,k & l to track two states it uses two variables to do the same job. Finally things that don't need to be global have been moved to being local.

    const int Main = 7;
    const int Store = 8;
    const int Main_led =  13;
    const int Store_led =  14;

    void setup() {
      Serial.begin(9600);
      pinMode(Main_led, OUTPUT);
      pinMode(Store_led, OUTPUT);
      pinMode(Main, INPUT);
      pinMode(Store, INPUT);
    }

    void sendMessage(char *text) {
        Serial.println("OK");
        delay(1000);
        Serial.print("AT+CMGF=1\r\n");
        delay(500);
        Serial.print("AT+CMGS=\"+91-------------");
        Serial.print("\"\r\n");
        delay(5000);
        Serial.print(text);
        Serial.write(0x1A);
        delay(5000);
    }

    void loop() {
      static int oldState1 = -1;
      static int oldState2 = -1;

      int buttonState1 = digitalRead(Main);
      if (buttonState1 != oldState1) {
        digitalWrite(Main_led, buttonState1);
        if (buttonState1 == HIGH)
          sendMessage("Main Door is closed");
        else
          sendMessage("Main Door is open");
        oldState1 = buttonState1;
      }

      int buttonState2 = digitalRead(Store);
      if (buttonState2 != oldState2) {
        digitalWrite(Store_led, buttonState2 );
        if (buttonState2 == HIGH)
          sendMessage("Store room is closed");
        else
          sendMessage("Store room is open");
        oldState2 = buttonState2;
      }
    }


body:
I am trying to key in the timing for how long the bldc motor needs to spin via keypad. I hope you can help me with this. I'm using delay() to set the timing of bldc motor spin. How do I key in a series of numbers in seconds, and then put it in the delay()?

The idea for this code is to enter the speed and timing via keypad.  After entering the speed and timing, button '#' is used to move the bldc motor according to the speed and timing entered. My question is how do I make my code to compile where speed is keyed in first, timing second then button '#' to run the motor?

Here is my code so far...

    #include "Keypad.h"
    #include "LiquidCrystal.h"
    #include "Servo.h"

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

    Servo myservo;

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //four columns
    char keys[ROWS][COLS] =
     {{'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'*','0','#'}
      };
    byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
    int count=0;

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

      lcd.begin(16,2);
      lcd.setCursor(0,0);
      lcd.print("S:");
      lcd.setCursor (0,1);
      lcd.print ("T:");

      myservo.attach(11);
    }

    void loop()
    {
        static char buffer[4], spintime[4];
        static byte i = 0, a = 0;
        char key = keypad.getKey();

        // i < 3: prevent buffer overflow
        if  ('0' <= key && key <= '9')   // this is for speed entry
        {
            buffer[i] = key;
            ++i;
            buffer[i] =0;  // null-terminate buffer
            lcd.setCursor (2,0);
            lcd.print(buffer);
        }

         if  ('0' <= key && key <= '9') // this is for timing entry
         {
            spintime[a] = key;
            ++a;
            spintime[a] =0;  // null-terminate buffer
            lcd.setCursor (2,1);
            lcd.print(spintime);
        }
        else if (key == '#')            // this is to run the motor after speed and timing are entered
        {
            int value = atoi(buffer);
            myservo.write(value);       //speed of motor
            int timing = atoi(spintime);
            delay (timing*1000);        // keep the motor spin for ( timing entered) second
            myservo.write(0);
            i = 0;
        }
    }

title: Enter timing value via keypad for bldc motor spin

Answers: 1

body:
As I understand it, you want to enter the speed, then the time, then '#'.

Let's imagine you want a speed of 22 and a time of 3.  The device will see `2`, `2`, `3`, `#`.  How will it know whether you're asking for a speed of 22 and a time of 3, or a speed of 2 and a time of 23?  Simple answer: it cannot know.  So we need to find a way to tell it.

My suggestion: we'll enter speed followed by `*`, and time followed by `#`.  (There are other possible solutions to this.)

We also need to decide the longest number the user can enter, and what happens if they enter a longer one, or if they don't enter one at all?  Let's say the longest number is 3 digits, and if they enter a longer one, we will ignore the extra digits.  So if they enter `123456789#`, we will register `123#`.  (Again, there are other solutions.)

There's some stuff in your code about an LCD, but you don't mention it in the question, so I have ignored it.

Lastly, I am assuming your code to drive the motor and read keys is correct.

Here's some `loop` code which I hope will do the above.  It will read numbers until it finds either a `*` or a `#`, convert the number to an integer, and store it as either `time` or `speed`.  When it has *both* speed and time, it will spin the motor and reset the values.

    void loop()
    {
        // Where we will store the number as we type it.
        // This buffer is large enough for a 3-digit number, pull a null terminator
        char buffer[4];

        // The speed of the motor
        static int speed = 0;

        // The time to spin for
        static int time = 0;

        // Input up to 3 numbers until we find a * or #
        int i=0;
        while (1)
        {
            char key = keypad.getKey();

            // If it's a number AND we have space left, add to our string
            if ('0' <= key && key <= '9' && i<3)
            {
                buffer[i] = key;
                i++;
            }
            // If it's a * or #, end
            else if ('#' == key || '*' == key)
            {
                // Null terminate
                buffer[i] = 0;

                // Convert to an integer
                int value = atoi(buffer);

                // Set the appropriate value
                if ('#' == key) time = value;
                if ('*' == key) speed = value;
                break;
            }
        }

        // If we have both speed and time...
        if (speed > 0 && time > 0)
        {
            // ...spin the motor at the required speed
            myservo.write(speed);
            // ...and for the required time
            delay(time*1000);
            // ...then stop it
            myservo.write(0);

            // Reset the values for next time
            time = 0;
            speed = 0;
        }
    }


body:
Is there a way to put an ESP8266 into a sort of "sleep" mode where it draws less power than usual, and then wakes up on a pin going high? I've tried doing this with delay, which still draws 20 mA, and with the deepsleep function that comes with the esp library, which can't sleep for short periods of time to watch for the pin going high. I'm building a watch, and power draw is of great concern to me. Is there possibly a way I could build or code this differently to make it more power efficient?
Basically it works like this, but the full code (at it's current state) can be found [here](https://gist.github.com/MrMai/f08da604c8a57844470407ad6b2604c6).

    void loop() {
        delay(1);
        // check for power signal stuff
        if(digitalRead(0)) {
            // execute data fetching 'n stuff
        }
    }

title: Wakeup Pin ESP8266

Answers: 2

body:
Without seeing the code and optimizing it I can tell you the following:

ESP8266 has three ways to save power:

 1. Modem sleep - only wlan modem shutdown, connection kept open
 2. Light sleep - less cpu usage, fast recovery
 3. Deep sleep - suspend all, close wifi too, slow recovery

http://bbs.espressif.com/viewtopic.php?t=133

body:
ESP8266 does have deep sleep mode. The link to http://bbs.espressif.com/viewtopic.php?t=133 posted earlier sums it up pretty well, despite being old.

However, a few things that are different from Arduino or should be considered if you're building a battery-operated device:

  - when the MCU wakes up from deep sleep, the entire application is restarted. Yes, beginning from the setup() function - just as if it was reset. You cannot put it to the deep sleep and then resume from the same place keeping all variables etc. You can only detect that the device was woken up from the sleep by reading a flag in the setup() function.

  - check your board. If you're not using bare ESP8266, but some development board such as NodeMCU or WittyCloud, it usually has number of other circuits powered on even when the MCU is sleeping. Particularly, USB-UART bridge and maybe power LED.

  - check your power source. Again, if you're using a development board, very likely it has an inefficient LDO voltage regulator. Even when MCU is powered down, the LDO can still use a few mA just to power itself (quiescent current). There are special low quiescent current regulators exist, very useful for battery-operated application.

  - finally, I see your code refers some OLED display. Just to be sure - is it powered down or excluded from the measurement? OLED doesn't need a lot of energy, but will drain a battery in a few days.

Personally, I do have experience creating a battery-operated device on ESP8266, which wakes up every few minutes, connects to wifi and sends some data. An old 700mAh Lithium battery is enough to run it for approximately a month. And I managed to get the sleep power to about 40 microAmps. Still a few times more than the chip itself needs, but good enough for me.


body:
I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:

    <<Content not supported>>

I also tried sending it to a basic mobile. It displayed:

    Content can't be displayed

I tried changing the encoding using the `AT` command.

    AT+CSCS="UCS2"
    AT+CSCS="GSM"

It didn't work for any encoding.

The command I use to send SMS is:

    ---> AT+CMGF=1
 <--- OK
 ---> AT+CMGS="10 digit number"
 <--- >
    > Hello!
    ^Z

Can someone please tell me what is going wrong? Thank you in advance!

title: Unable to receive SMS on Android

Answers: 1

body:
In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.

The AT commando that (perhaps) will work for you is the **ATZ**, in the SIM900 works for me.

You can look over [here][1] to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.

Hope you can find an answer.

  [1]: http://www.propox.com/download/docs/SIM900_AT.pdf


body:
Recently i bought an "Serial 128X64 OLED LCD Display SSD1306".

I searched for available libraries and tried to find the best one to use before actually experimenting with this device.

I came across a hackaday article mentioning a "HIGH SPEED SSD1306 LIBRARY"

So that drew my attention and got on with it. This is the link to the afforementioned library for the Arduino DUE.

[DayOLED_SSD1306][1]

  [1]: https://github.com/GravCorp/DayOLED_SSD1306

Right from the beginning i had some trouble with the wiring.
I wired 3.3 volts to input, GND, RES, DC, CS pins are wired according to the library example..
But the library contains no info on how to wire D0 and D1 pins. Since this OLED works both I2C and SPI, i thought maybe these two pins are ommited.

So i hooked it up, load up the example code and got compilation errors.

Here are the errors:

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawPixel(int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:114:14: error: 'swap' was not declared in this scope

         swap(x, y);

                  ^

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastHLine(int16_t, int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:598:16: error: 'swap' was not declared in this scope

           swap(x, y);

                    ^

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp: In member function 'virtual void DayOLED_SSD1306::drawFastVLine(int16_t, int16_t, int16_t, uint16_t)':

    C:\Users\User1\Documents\Arduino\libraries\DayOLED_SSD1306-master\DayOLED_SSD1306.cpp:666:16: error: 'swap' was not declared in this scope

           swap(x, y);

Anybody got a clue what is going on with the swap() function?
Maybe it's deprecated?

Anyone has managed to get this library working?
Or maybe has managed to get this Display working even with another library?

title: SSD1306 OLED LCD Library Errors

Answers: 2

body:
I've had good success with the u8g2 library for the small I2C OLEDs.
[u8g2 on GitHub][1]

  [1]: https://github.com/olikraus/u8g2

body:
I have managed to get this somewhat working with these 4 libraries:
#include <SPI.h>,
#include <Wire.h>,
#include <Adafruit_GFX.h>,
#include <Adafruit_SSD1306.h>.
These should all be in the include library in the ide.
Hope this helps!


body:
with the following code:

    int foo = bar[1].toInt;

or

    int foo = bar[1].toInt();

I get this error

    request for member 'toInt' in '*(bar + 1u)', which is of non-class type 'uint8_t {aka unsigned char}'
the context for this is bar is the response from a HTTP client over web sockets

title: toInt error when converting character of string to interger

Answers: 2

body:
I'm not quite clean on what you are trying to do.  So lets assume the String has "abc123" in and you want the numeric part.

    const String input = "abc123";
    const int foo = input.toInt();  // This will not work!

    const String input = "abc123";
    const String tmp = input.substring(3); // Take the end of the string
    const int foo = input.toInt();  // foo == 123

    const String input = "abc123";
    const String tmp = input.substring(3,4); // Take the end of the string
    const int foo = input.toInt();  // foo == 1 or 12 (can't quite tell from the docs)

Is one of those what you want to do?

You can't take a character and then apply a function from the string class to it without making it a String first.

    int foo = String(bar[1]).toInt();  // This should work

body:
The Arduino function `toInt` requires a `String` object.
You're passing it a single character, not a `String`.

    int foo = String(bar[1]).toInt();


body: Essentially I am looking to build a remote controlled car using dc motors and one arduino uno to be on the car to supply the power logic and i wanted to use another arduino to be the remote. I was curious what the most effective method would be as to pairing these two devices in a way that it would provide the maximum range possible while still maintaining a decently high bandwidth limit. The reason for this is hopefully i can have the arduino mounted to the car connected to a camera where the camera would send a video feed over to the remote control. I was thinking about using a bluetooth module between the two such as a HM-10 but i wouldn't be able to send a video feed this way because bluetooth cannot transmit that much data at once. However if that is the most practical option i can get over the fact of not having a live video feed and send an image ever 5 seconds or so instead of live. Appreciate any insight on what the most effective method would be in terms of efficiency between range and data stream bandwidth.

title: Connect Two Arduino Uno's

Answers: 2

body: You can use raspberry pi and computer to send commands and receive video feed

body:
You wouldn't be able process (acquire, store, resize, output) any sensible video signal with the Uno (or any other Atmega-based board). The amount of memory and clock speed is way too low. Peripherals and instruction set are also lacking - no DMA, FPU, DSP instructions. Arduinos barely cope with audio - any kind of video is out of question, except if you want something like a 5fps 32x32 raw feed. Uncompressed, of course.

If you want another hobby-friendly open source solution, I'd look at something with at least an ARM M4 core, with DMA of course. For communication, regular IEEE 802.11 Wifi is your best bet (high throughput) - those 433Mhz RF modules only transmit 4800bps or so.

There may be better solutions, but I've only used stm32f429 for video: they have DMA(2D), display interface (RGB, 8080 memory interface, ...), DCMI (digital camera interface). Wifi could be handled by something like WifiMCU.

You could use the STM32F429DISCOVERY board with LCD for you remote controller, another STM32F4 board with a camera (ex http://hackaday.com/2014/12/04/serial-camera-courtesy-of-the-stm32f4/) and pair them with two [WifiMCU](http://www.wifimcu.com/)s, if You want to do it with off-the-shelf boards.


body:
I want to connect 24 DS18B20 sensors to arduino by onewire library in the same digital pin .

Can anyone post an example code ?

Thanks

title: Arduino + DS18B20 array

Answers: 1

body:
Use the OneWire and the DallasTemperature libraries. They are both in the Arduino IDE in the Library Manager.

The DallasTemperature library has the example "Multiple". You need to make an array of DeviceAddress.

To tell them apart, you have to label each temperature sensor with its device address (a unique identifier inside each DS18B20). Therefor you have to connect them one-by-one and write down the device address.

Start with one sensor, and if that works, try to make arrays.

For 24 temperature sensors, you need a lot of wires. That could make it less reliable. You can use two or three or more pins as well. Then you have to create more than one "OneWire" bus in the sketch.

There are many examples for multiple DS18B20 sensors. For example this one is with an array: [Arduino forum: "multiple temp sensors ds18b20"][1].

  [1]: https://forum.arduino.cc/index.php?topic=393653.0


body:
I need programmable current control, fading from zero to 2 milliAmps.  I was hoping to use Arduino's AnalogWrite(), which uses Phase Width Modulation (PWM) to simulate analog output with a sawtooth wave on a duty-cycle; to control an LM334Z to deliver a slowly ramped low current delivery.
[The application is a TransCranial Direct Current Stimulation (TDCS) micro-current delivery to the human scalp. Jumping straight to 2 milliAmps is uncomfortable].
Will PWM work? Or, do I need some sort of smoothing circuitry to soften the PMW before it is applied to the LM334Z's Rset pin to accomplish the above?

title: Can I drive an LM334(Z) from an Arduino with AnalogWrite()?

Answers: 3

body:
You control the LM334 with a resistance, not a voltage. The current is set by multiplying the current through the resistor.

Maybe you can do what you want by replacing the `Rset` with a digital potentiometer?

body:
> LM334Z's Rset pin to accomplish the above?

Most of that type of circuit has its operations be determined by the current In or out of that pin. So a voltage signal may not work - you will need to experiment. I have had some success with analogs dds chips and linear programmable osscillators.

So try it on your chip. Nothin to lose.

body: If you don't need super high accuracy, using a MOSFET's ohmic region, plus a smoothing filter on the output of your PWM (analog out), could be a solution.


body:
I have two files, the first file is a `library` that I use to handle `push buttons` and initialize it and the second is where I handle my code and change `LED` state when `push button` is pressed, but my code doesn't work, I'm using `Atmega32A` micro-controller.

**my library code:**

    #ifndef ButtonLibrary
    #define ButtonLibrary

    #ifndef numberOfButtons
    #define numberOfButtons 2
    #endif

    #ifndef bit_is_clear
    #define bit_is_clear(sfr, bit)   (!(_SFR_BYTE(sfr) & _BV(bit)))
    #endif

    #include <avr/io.h>

    char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel);
    void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection);
    void initialize_led(int pinofled, unsigned char port, unsigned char datadirection);
    void change_led_state(int pinofled, unsigned char port);

    char pressed[numberOfButtons];
    int pressed_confidence_level[numberOfButtons];
    int released_confidence_level[numberOfButtons];

    void initialize_button(int pinofbutton, unsigned char port, unsigned char datadirection)
    {
     datadirection &= ~(1 << pinofbutton);
     port |= 1 << pinofbutton;
    }

    void initialize_led(int pinofled, unsigned char port, unsigned char datadirection)
    {
     datadirection |= 1 << pinofled;
     port &= ~(1 << pinofled);
    }

    void change_led_state(int pinofled, unsigned char port)
    {
     port ^= (1 << pinofled);
    }

    char ButtonPressed(int buttonnumber, unsigned char pinofbutton, unsigned char portbit, int confidencelevel)
    {
     if(bit_is_clear(pinofbutton, portbit))
     {
      pressed_confidence_level[buttonnumber] ++;
      released_confidence_level[buttonnumber] = 0;
      if(pressed_confidence_level[buttonnumber] > confidencelevel)
      {
       if(pressed[buttonnumber] ==0)
       {
        pressed[buttonnumber] = 1;
        return 1;
       }
       pressed_confidence_level[buttonnumber] = 0;
      }
     }
     //button isn't pressed
     else
     {
      released_confidence_level[buttonnumber] ++;
      pressed_confidence_level[buttonnumber] = 0;

      if(released_confidence_level[buttonnumber] > confidencelevel)
      {
       pressed[buttonnumber] = 0;
       released_confidence_level[buttonnumber] = 0;
      }
     }
     return 0;
    }
    #endif

**my main code:**

    #define F_CPU 1000000UL

    #include <stdio.h>
    #include <stdlib.h>
    #include <avr/io.h>
    #include <util/delay.h>
    #include "ButtonLibrary.h"

    int main(void)
    {
     initialize_button(PIND4, PORTD, DDRD);
     initialize_button(PIND3, PORTD, DDRD);
     initialize_led(PINC7, PORTC, DDRC);
     initialize_led(PINC6, PORTC, DDRC);

     while(1)
     {
      if(ButtonPressed(0, PIND, 3, 500) == 1)
      {
       change_led_state(PINC6, PORTC);
      }
      if(ButtonPressed(1, PIND, 4, 500) == 1)
      {
       change_led_state(PINC7, PORTC);
      }
     }
    }

when I press the `push button` nothing happens, I think there is something wrong in my `initialize` functions or `change_led_state` function but I don't know it.

title: Atmega32 push button library problem

Answers: 0


body:
I've been trying to make an accelerometer calibration tool for my Arduino Nano and MPU6050, but the arduino seems to randomly do incorrect addition. If you look at the output of the console, it works fine for the first 4 iterations, then on the fifth, decides that -31904+-7964 is equal to 25668. It is supposed to be -39868. It does this every time I run it, usually between the 3rd to 6th iteration, but with different numbers.

    bool calix = true; //X calibrated or not
          while(calix)
          {
            accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
            Serial.print("PrevAvgX: "); Serial.println(axo/i);
            Serial.print("Axo: "); Serial.println(axo);
            Serial.print("RawX: "); Serial.println(ax);
            axo = (float)ax + (float)axo;
            i += 1;
            Serial.print("Axo2: "); Serial.println(axo);
            Serial.print("RawX: "); Serial.println(ax);
            float cax = axo/i; //Current Average (x)
            Serial.print("AverageX: "); Serial.println(cax);
            delay(100);
            accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
            Serial.print("NewX: "); Serial.println(ax);
            float offsettocurrent = ax-(axo/i);
            Serial.print("AverageX-RawX: "); Serial.println(offsettocurrent);
            if(offsettocurrent>5 or offsettocurrent<-5)
            {
              Serial.println("Offset not accurate enough. Continuing.");
            }
            else
            {
              Serial.println("Offset accurate enough. Finishing calibration");
              break;
            }
            delay(100);
          }

Serial console output:

    Initializing I2C devices...
    Testing device connections...
    Connected to MPU6050
    Attempting full calibration
    PrevAvgX: -1
    Axo: 0
    RawX: -8048
    Axo2: -8048
    RawX: -8048
    AverageX: -8048.00
    NewX: -8028
    AverageX-RawX: 20.00
    Offset not accurate enough. Continuing.
    PrevAvgX: -8048
    Axo: -8048
    RawX: -7940
    Axo2: -15988
    RawX: -7940
    AverageX: -7994.00
    NewX: -7964
    AverageX-RawX: 30.00
    Offset not accurate enough. Continuing.
    PrevAvgX: -7994
    Axo: -15988
    RawX: -7972
    Axo2: -23960
    RawX: -7972
    AverageX: -7986.00
    NewX: -8016
    AverageX-RawX: -30.00
    Offset not accurate enough. Continuing.
    PrevAvgX: -7986
    Axo: -23960
    RawX: -7944
    Axo2: -31904
    RawX: -7944
    AverageX: -7976.00
    NewX: -8016
    AverageX-RawX: -40.00
    Offset not accurate enough. Continuing.
    PrevAvgX: -7976
    Axo: -31904
    RawX: -7964
    Axo2: 25668
    RawX: -7964
    AverageX: 5133.00
    NewX: -7944
    AverageX-RawX: -13077.00
    Offset not accurate enough. Continuing.

title: Arduino randomly does incorrect addition

Answers: 1

body:
`int` only goes from `-32768` to `32768`, and rolls-over, as you've seen.
Use a `long` data type instead and you can go MUCH further from zero. Use `double` instead of `float` likewise, when you need more room. Be aware however that larger types use more RAM, and in the case of `double`, execute a bit slower as well.


body:
I am trying to make a circuit using an ATmega328, that has a reset button that behaves like many consumer devices:

 1. A short press just restarts the micro-controller
 2. A long press (5 seconds?) causes the settings to be restored to default

What is the best way to achieve this behaviour? I imagine it is going to require two pins? Can it be done just using passive components?

Thanks!

title: Two function Reset button - long/short press

Answers: 3

body:
It can be done with one button, one resistor, one capacitor and one GPIO pin (in addition to the RESET pin):

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

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

<!-- End schematic -->

Pressing the button causes a LOW pulse on the RESET pin (in the exact same way as the USB interface does).

During your startup procedure you read the GPIO pin you have chosen. If it's LOW the button is still being pressed in. If it's HIGH it has been released.

If you are using an Arduino with the normal bootloader the bootloader itself imposes a 2 second delay (which may be enough for you). Alternatively you will need to have your own delay in your program before reading the button to ensure that you have plenty of time to release the button so you don't accidentally reset your settings.

body: Use a state machine to detect thee king presses. Once done, you can either trigger a hardware or a software reset, or to simulate one by jumping to the reset vector - you will need to write the code to support that, like an explicit initialization of variables, etc.

body:
You can set the **_RSTDISBL_** (bit 7 on the _HIGH fuse_) to disable the external reset and use the _reset_ pin as PC6 to manage the reset behavior from your program.

[![RSTDISBL ATmega328P][1]][1]

The second part is to capture when reset button is pressed: put some code in the **ISR for PCINT1 handler** when the pin changes (_PCINT14_ pin function). If you are programming an Arduino board, the reset button is pulled up (press becomes LOW and release becomes HIGH).

Detecting long press or short press is a timer affair. According to your requirements, you will restore some EEPROM values or external state to **factory defaults** before the microcontroller resets with a long press.

This C snippet will reset the microcontroller after the short or long press ([watchdog timer feature][2]):

<!-- language: c -->

    #include <avr/wdt.h>

        // ...
        wdt_enable(WDTO_15MS);
        for (;;) {}

  [1]: https://i.stack.imgur.com/0PyFw.png
  [2]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__watchdog.html


body:
        #define LS 2      // left sensor
    #define RS 3      // right sensor

    /*-------definning Outputs------*/
    #define LM1 4       // left motor
    #define LM2 5       // left motor
    #define RM1 6       // right motor
    #define RM2 7       // right motor

    void setup()
    {
      pinMode(LS, INPUT);
      pinMode(RS, INPUT);
      pinMode(LM1, OUTPUT);
      pinMode(LM2, OUTPUT);
      pinMode(RM1, OUTPUT);
      pinMode(RM2, OUTPUT);
    }

    void loop()
    {
      if(digitalRead(LS) && digitalRead(RS))     // Move Forward
      {
        digitalWrite(LM1, HIGH);
        digitalWrite(LM2, LOW);
        digitalWrite(RM1, HIGH);
        digitalWrite(RM2, LOW);
      }

      if(!(digitalRead(LS)) && digitalRead(RS))     // Turn right
      {
        digitalWrite(LM1, LOW);
        digitalWrite(LM2, LOW);
        digitalWrite(RM1, HIGH);
        digitalWrite(RM2, LOW);
      }

      if(digitalRead(LS) && !(digitalRead(RS)))     // turn left
      {
        digitalWrite(LM1, HIGH);
        digitalWrite(LM2, LOW);
        digitalWrite(RM1, LOW);
        digitalWrite(RM2, LOW);
      }

      if(!(digitalRead(LS)) && !(digitalRead(RS)))     // stop
      {
        digitalWrite(LM1, LOW);
        digitalWrite(LM2, LOW);
        digitalWrite(RM1, LOW);
        digitalWrite(RM2, LOW);
      }
    }

i got this code from a site.My doubt is if the left sensor is not reading means it has value of zero hence it is on black line and the right sensor is on white line.Then it should move to left side itself.BUt the program says it should moves to right.Iam a beginner.Please help me to clear my doubt

title: In line following robot do this code work perfectly as iam unclear about the right and left moving programing lines

Answers: 1

body:
This depends on how the sensors are arranged. However, assuming they are setup like eyes on our heads, then the code would be correct.

If the left sensor does not see the line, but the right sensor does, then that means the line is on the right side of the robot, and thus turning to the right would bring the line back into view of the left sensor.


body:
I recently bought arduino Yun shield, and I didnt had any external USB storage connected, I downloaded [`get-pip.py`][1] on Yun using wget and ran `python get-pip.py` which resulted in 5mb storage on yun now full and even pip is not installed.

how do I free up space or reset yun shield to original , and use USB storage as default location for storing all opkg and python onto USB storage drive ?

  [1]: https://bootstrap.py pa.io/get-pip.py

title: How do I free up space on arduino Yun shield?

Answers: 0


body:
I'm trying to understand the implementation of `attachInterrupt`. For `LOW`, `CHANGE`, `RISING` and `FALLING` it seems simple enough; it sets some chip-specific registers and stores the given callback in `intFunc`, then invokes the callback from inside its own thin wrapper callback.

But the [documentation][1] says that on the Arduino Due, Zero and MKR1000, it can also accept `HIGH`. I can't find any reference to this in the code, and I can see that `HIGH` (= `0x01`) and `CHANGE` (= `1`) would be indistinguishable after preprocessing, so I can only assume a macro is involved somewhere, but I can't see one in the source.

How does the library implement this? Where is the code?

  [1]: https://www.arduino.cc/en/Reference/attachInterrupt

title: attachInterrupt HIGH

Answers: 0


body:
When i am uploading my code to `arduino nano`, i am getting message about high dynamic memory usage (87%):

    Sketch uses 17,628 bytes (57%) of program storage space. Maximum is 30,720 bytes.
    Global variables use 1,751 bytes (85%) of dynamic memory, leaving 297 bytes for local variables. Maximum is 2,048 bytes.
    Low memory available, stability problems may occur.

But despite this, its uploading to my `arduino nano` and everything works fine without action method's code. How to use code (code to work with LCD) wich is located in `action()` method. If i use hidden code, im getting message `error opening test.txt` (not enough memory). But if code which is controls LCD screen is annotated then `SD` card works fine.

If i use this code, i'm getting problem with SD card. But i can still use LCD and SD on same arduino board separately without any problems, but if i try to combine it, im getting some problems with SD card reading.

    void action() {
    //  display.display();
    //  display.clearDisplay();
    //  display.setCursor(0, 0);
    //  display.setTextSize(2);
    //  display.setTextColor(WHITE);
    //  display.println(sensorValue);
    // if uncomment this code, i am getting error with sd card reading (possible memory issue)
    }

 All code:

    #include <Wire.h>
    #include <Adafruit_SSD1306.h>

    #include <SPI.h>
    #include <SD.h>

    #define OLED_RESET 4
    Adafruit_SSD1306 display(OLED_RESET);

    const int analogInPin = A0;  // Analog input pin that the potentiometer is attached to
    const int analogOutPin = 9; // Analog output pin that the LED is attached to

    int sensorValue = 0;        // value read from the pot
    int outputValue = 0;        // value output to the PWM (analog out)

    int count_iterations = 0;

    #if (SSD1306_LCDHEIGHT != 32)
    #error("Height incorrect, please fix Adafruit_SSD1306.h!");
    #endif

    File myFile;

    void setup() {

      /// SD START
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");
      myFile = SD.open("test.txt", FILE_WRITE);

      // if the file opened okay, write to it:
      if (myFile) {
        Serial.print("Writing to test.txt...");
        myFile.println("testing 1, 2, 3.");
        // close the file:
        myFile.close();
        Serial.println("done.");
      } else {
        // if the file didn't open, print an error:
        Serial.println("error opening test.txt");
      }
      myFile = SD.open("test.txt");
      if (myFile) {
        Serial.println("test.txt:");
        while (myFile.available()) {
          Serial.write(myFile.read());
        }
        myFile.close();
      } else {
        Serial.println("error opening test.txt");
      }
      //// SD END
    }

    void loop() {
      sensorValue = analogRead(analogInPin);
      if (sensorValue < 1000) {
        action();
      }
    }

    void action() {
    //  display.display();
    //  display.clearDisplay();
    //  display.setCursor(0, 0);
    //  display.setTextSize(2);
    //  display.setTextColor(WHITE);
    //  display.println(sensorValue);
    // if uncomment this code, i am getting error with sd card reading (possible memory issue)
    }

title: Arduino Nano memory issue. SD card and LCD screen together

Answers: 1

body:
Your code is using in the neighborhood of 150 bytes for text-strings in RAM, much of which can be moved to PROGMEM quite easily.  For example, replace

    Serial.print("Initializing SD card...");

by

    Serial.print(F("Initializing SD card..."));

Changes like that to `Serial.print()` arguments should free up about 140 bytes of RAM.  To free up another 8 bytes, instead of `SD.open("test.txt" ...)`, write `SD.open(FileName ...)` with `FileName` previously declared via `char *FileName = "test.txt";` so that the text `test.txt` appears in RAM once instead of twice.

In short, if 150 bytes will make the difference, that much memory reduction is easy.

---

I briefly examined the source code behind the `Adafruit_SSD1306.h` and `SD.h` headers, to see if they use some large arrays in RAM, such as 512 bytes of sector data, or some hundreds of bytes for frame buffers.

Ordinarily, such arrays are difficult to get rid of without a rewrite from scratch or without major loss of functionality.  For most one-off projects, the effort involved isn't worthwhile:  one can instead use an [Arduino Mega2560](https://www.arduino.cc/en/Main/arduinoBoardMega2560) system, which has 8 KB of RAM, vs the [Arduino Nano's](https://www.arduino.cc/en/Main/ArduinoBoardNano) 2KB RAM; or can use an [Arduino Due](https://www.arduino.cc/en/Main/ArduinoBoardDue) with 96KB RAM; or a [Teensy](https://www.pjrc.com/teensy/), with 8, 16, or 64KB RAM.

However, if you plan a production run and are trying to hold down costs by using Nanos, consider the following approach:   Carefully arrange the processing so that you are done with SD buffers before needing a display frame buffer; and revise the libraries so the SD buffer and frame buffer overlap.  That is, place the smaller buffer within the same region of memory holding the larger buffer.  If processing can't be neatly separated, blank the display while using the shared buffer area for accessing SD data.

[Note, I edited this answer and expanded discussion of buffers in the libraries.]


body:
I have an unusual bug with the code I have written for my rover V2 robot.

I have a raspberry pi running some computer vision code written in opencv tracking an object doing the heavy processing.

Once the object is detected, a command is sent via serial (USB) to make the robot move left, right, forwards etc.. The pi sends: w, a or d for the direction it wants the rover to move, it then turns off it's ability to send any further commands via a flag and will turn this back on when the rover sends a response confirming it has completed the command.

The idea is, eventually the rover v2 will be able to do some audio processing itself so it can turn and face the direction of a sound impulse but always prioritize any incoming serial data, sending the more accurate movement commands.

So my idea has been to implement an interrupt routine that is called upon receiving a command using the less than perfect approach suggested [here][1].

So now for the weird part.. the code works entirely... until the motors have power!

If the Rover V2 motor power is entirely disabled the interrupt routine will work flawlessly. The Raspberry Pi will send a command and receive every reply from the Rover.

However, if the Rover V2 Motors are powered on, the Rover will receive all commands and send replies accordingly. The issue is for some reason, the Raspberry Pi will occasionally not receive a reply rendering the robot stationary as no more commands can be sent, this happens after varying periods of time all the way from 2 successful command interrupts to 100.

The fact that this occurs only when power is applied to the motors on the Arduino, is leading me to believe it is not a fault in the Pi code.

Why is it, that as soon as the power is applied to the motors there is inconsistency in the transmission of serial replies?

Does anybody have any suggestions on how I could further diagnose the cause of this fault?

Or is there any obvious issues in this code I have not seen?

Thanks in advance!

ohkneel

Code can be  viewed [HERE][2]

  [1]: http://forum.arduino.cc/index.php?topic=45076.0
  [2]: http://pastebin.com/YxV1Ne5H

title: Serial Write fails to send when Motors moving

Answers: 0


body:
I have an arduino mega 2560 and I'm trying to program it using Arduino IDE 1.8.1. The problem is that I also need to keep open another program that will communicate with the Arduino using the COM port. I usually have to make very small changes to the code with the IDE and then check the results in the program.

However, when the IDE has finished uploading the program it will not release the COM port, and the program I'm using will give me an error message saying "access denied". This is a problem because I want to keep both programs open at the same time.

In fact I could just: make my correction to the code, close the IDE when it has finished, open the program I need, check whether the correction I made was right, otherwise close it again and open the IDE again, but that would take an insane amount of time and it would be quite annoying.

Is there a way to force the Arduino IDE to release the COM port so that other programs could communicate with the Aduino?

title: Arduino IDE doesn't release COM port after programming

Answers: 2

body: This type of problem happens many time with me. Try to disconnect your ARDUINO MEGA from your PC / LAPTOP and then connect it again. It must be solve your problem. If this will not work then restart your PC / LAPTOP and try it out again.

body:
To force the Arduino IDE to disconnect from the COM port, simply go into the Tools menu, go to Ports and select another COM port.

Alternatively, you can open and then close the serial port monitor (Ctrl+Shift+M then Alt+F4).


body:
I am working on a small project with Processing and Arduino, in which, depending upon the value of a photoresistor, it displays whether it is day/night/evening.

I read the value from the photoresistor and write the value to the serial port. Then in Processing I read the value from the serial port and display depending on the value.

But I get a very flickery output, and there is always a -1 imprinted on the screen as shown in the video.

Please help me out.

[link to the video][1]

**Code for Arduino:**

    int ldr1 = A0;
    int x,y;

    void setup() {
      pinMode(ldr1,INPUT);
      Serial.begin(9600);
    }

    void loop() {
      x = analogRead(ldr1);
      Serial.write(x);
      delay(100);
    }

**Code for Processing:**

    import processing.serial.*;
    Serial port;
    int x,y;

    void setup() {
      size(640, 320);
      port = new Serial(this, "COM3", 9600);
    }

    void draw() {
      background(0);
      x = port.read();
      text(x,100,100);
      if(x < 400 && x > 200) {
        textSize(32);
        fill(0,0,255);
        text("it is evening",200,200);
      }
      if(x < 200 && x > 20) {
        textSize(32);
        fill(0,255,0);
        text("it is night",200,200);
      }
      if(x > 400 && x < 900) {
        textSize(32);
        fill(255,0,0);
        text("it is morning",200,200);
      }
    }

  [1]: https://drive.google.com/open?id=0B5NnRFsbrHprNlJYYnBFcUNJQ3M

title: Problem in getting the output (language: Processing and Arduino IDE)

Answers: 1

body:
If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial_read_.html

it says:
*"Returns a number **between 0 and 255** for the next byte that's waiting in the buffer. **Returns -1 if there is no byte,** although this should be avoided by first cheacking available() to see if data is available."*

Either before calling "Draw" function, or inside "Draw", you should first check:

    if(port.available()){
      //do your checking for X value and set text as you are doing before

    }

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.

You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.

      int val = analogRead(ldr1);
      val = map(val, 0, 1023, 0, 255);
      Serial.write(val); //now you will not lose information

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.