text:
PWM Control, How to stop LED from Flickering?
What is required is controlling the brightness of an LED using both Buttons and a Potentiometer,
Button A: Increase
Button B: Decrease /Dim
Potentiometer: Increase and Decrease,
This however must happen on 1 single circuit and must display the results on an LCD.
If I do this separately, meaning buttons without potentiometer and visa versa, I win, the moment I combine the two. I get flickering when working the buttons, due to the potentiometer.
Alternative Research:https://www.instructables.com/id/Smooth-Potentiometer-Input/
Code Below
#include <LiquidCrystal.h>
#include <Wire.h>
// ------------------------------------------------------------

int LED1          = 9;
int ButtonLeft    = 8;
int ButtonRight   = 7;
int brightness    = 0;

// ------------------------------------------------------------
byte buttonState1     = 0;
byte lastButtonState1 = 0;

byte buttonState2     = 0;
byte lastButtonState2 = 0;

unsigned long switchMillis;

// ------------------------------------------------------------

int potValue1 = 0;
int potValue2 = 0;
int potPin= A0;
int readValue;
int writeValue;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// ------------------------------------------------------------
void setup() {

  lcd.begin(16, 2);
  pinMode (potPin, INPUT);
  pinMode(LED1,OUTPUT);
  pinMode(ButtonLeft,INPUT);
  pinMode(ButtonRight,  INPUT);
  lcd.clear ();
}

// ------------------------------------------------------------
void loop(){

    if (millis() - switchMillis >= 5)
  {
    switchMillis = millis();
    checkSwitches();
  }

   readValue = analogRead(potPin);
   writeValue = (255./1023.) * readValue;
   analogWrite(LED1, writeValue);

    potValue1 = analogRead(potPin) / 10;
    potValue2 = potValue1 / 1.02;

    lcd.setCursor(0,0);
    lcd.print("Potent=");
    lcd.print(potValue1);
    lcd.print("%");
    delay(100);
    lcd.print(" ");
    delay(1);
}

void checkSwitches() {

    analogWrite(LED1, brightness);
    delay(10);

  buttonState1 = digitalRead(ButtonLeft);

  if(buttonState1 == HIGH){
    brightness--;
    if(brightness < 0){
      brightness = 0;
    }
  }

  buttonState2 = digitalRead(ButtonRight);

  if(buttonState2 == HIGH){
    brightness++;
    if(brightness > 255){
      brightness = 255;
    }
  }

 lcd.setCursor (0,1);
 lcd.print ("Brightness=");
 lcd.print (brightness);
 lcd.print ("   ");
}

This is like having two players, play a single player game, by both of them pressing the buttons on the same single controller. Of course the game character is making weird moves. PS, I think a rotary encoder might be more appropriate to use here.

Your code doesn't make much sense.
You set the LED to 2 different brightness values that don't have anything to do with each other: The pot brightness and the button-based brightness. You only adjust the LED based on switches once every 5 mS. Thus the LED is going to flicker between 2 different brightness values.
What do you want it to do? How do you want to control the brightness based on input from both the pot and your switches? (What is the relationship between the buttons and the pot? Should the button input alter max/min value of the pot up and down? Should holding the button down change the brightness by 1 value per a specific time unit? Say 2 increments/decrements per second?)
Describe the user interface you want to achieve, and then think through how you would do that in code.

"Describe the user interface you want to achieve, and then think through how you would do that in code." +1.

Hi Duncan, the flickering only occurs upon addition of the pot, if I ran the code without the pot, everything works accordinging.
This is my second code, I could present you with the first but I still get the same problem.
Even if I removed the switchMillis section in the code. Even before I was told the arduino couldnt understand what to do because I didnt have buttonstates, but I added those to no success.
Bottom line is, I need to control the brightness of an LED using both Pot and Buttons, alone each I can do, but I dont know how to do it all within the same code.

@BoiG can you describe to us exactly how the buttons and pot interact? If I decrease the pot, then use the increase button, what should happen? If I then increase the pot? What if I’m at max via the button, then crank the pot up? Then back down? It’s not clear what you’re really trying to achieve.

You're trying to build something and don't have a clear idea of what it is. You need to define, in clear precise detail, what you want to do, and then think through how to achieve that in code. We can't help you unless you can be clear about how you want your program to behave.


text:
ESP01 won't boot when connected to the LED strip
I have a weird bug behavior.
I have an ATX power supply, which powers a long WS2812B 5v strip, controlled by the Esp 01 and the board...
Now the bug happens only when I connect the data pin to the strip. The ESP won't start after I restart the ATX PSU. And if it does it just crashes after some time...
Here is the SPOOKY part: when I start the esp WITHOUT the pin connected and plug it in after it starts it will keeep working for days... but sometimes it just decides it will go bananas... W T F! Any ideas why?????
I suspected voltage drops, but nope. I tried a battery, a second adapter and a USB power... none helped. Same behavior as soon as you connect the strip and hit restart/update, it goes bananas...

On ESPs there are some pins, that need to have a specific value during boot. As the ESP01 already has so few pins, you might have used one of them, so the connected strip might prevent the ESP from booting. I currently don't have the time, but you can google that yourself.

That is the tx pin. this is a standard led module which uses the standard GPIO2 pin. so it should not be possible that i got that pin. Any other ideas? i ordered an other esp so cross fingers it works.

it's probably pulling down gpio2, preventing a normal boot. watch the voltage on that pin during startup; if not vcc, bingo.

ye im suspecting that im missing the 500ohm resistor you should put on the data line. will update when i have it.

I used a 470Ohm to connect GPIO2 and VCC. (to ensure HIGH during boot phase).
As suggested on : https://www.esp8266.com/viewtopic.php?p=77993
esp01 5v to 3.3shifter 470Ohm

Regards,
Dom

source: Stack Exchange

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

sort: votes


text:
SIM900 and Mega 2560 not sending SMS
I just bought a SIM900 Arduino shield from AZDelivery. I only have a Mega 2560 board, thus I am trying to use this although most examples (like the tutorial from AZDelivery) are with the Uno board. I am using the SIM card from my mobile phone, not having any PIN. This is the Arduino library I am using.

I didn't flash anything on the SIM900 board prior to testing, because in the instructions from AZDelivery Ebook this was not mentioned.
My NetLight LED is blinking constantly (1 blink per second) I guess it is not finding the mobile network.
At the momemt, I only have a 1A supply, though I've already ordered a new one with 2A. Could this be the reason for point 2? Does the board need 2A to log into the network?
Asuming it would log into the network, the AZDelivery Instruction Sketch/Example is using "SoftwareSerial.h" due to its compatibility to the Uno board. Since I am using a Mega board, can I just use D30 and D31 and set them as Rx and Tx using the SoftwareSerial library?
Can you give me a link to an up-to-date library and/or example for SIM900 working with the Mega 2560 Rev3 and Arduino 1.8.4?

I hope you can help me getting started with the SIM900 module.

I was just able to send an SMS (even with the 1A supply). Here the answers to my questions.

No, it is not necessary to flash the SIM900 board
I was not connected, because I didn't insert the SIM card properly on the shield.
No it does not necessarily need 2A for logging into network and obviously not for sending SMS though there might be reasons for the board consuming 2A during SMS sending, e.g. bad network connection.
If you want to use Sotware Serial, you need certain digital lines allowing software interrupts. In the case of the MEGA board, e.g. D10, D11 or for the UNO D7,D8.
I was using this tutorial to get communication via SoftwareSerial working. Afterwards I added the code for sending SMS.

I hope I can help some others who are looking for a low level description of how to get started with MEGA and SIM900.

the mega board has 4 hardware serial ports; why use software?

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

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


text:
Arduino + SIM808: How to get only the JSON object response without the header?
I have been successfully getting the response from my web server. The problem is I get the whole package with header and content/body:
Recv: 325 bytes: HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
Date: Wed, 02 Aug 2017 03:26:37 GMT
Connection: close
Content-Length: 18

1501644397698.2585

I want to only assign this 1501644397698.2585 to my double variable. How can I do this?
This is the code which sends and prints the response:
Serial.println("waiting to fetch...");
sim808.send(http_cmd, sizeof(http_cmd)-1);
while (true) {
  int ret = sim808.recv(buffer, sizeof(buffer)-1);
  if (ret <= 0) {
    Serial.println("fetch over...");
    break;
  }
  buffer[ret] = '\0';
  Serial.print("Recv: ");
  Serial.print(ret);
  Serial.print(" bytes: ");
  Serial.println(buffer);
  break;
}

You need to receive the whole header and them trim what you don't want. The easiest way of doing this is scanning the header string for a new line (\n) character. From the start of the string to the new line gives you a line of the header. If the length of this substring is < 1 then look for the next line. Now scan between the start and the new line and see if you see a colon (:), if you do then this line is part of the header, look for the next new line. Otherwise use strtod() to convert the data to a double.
It should be something like this (not compiled, not tested):
char* response = ".........";
char* pStartOfLine = response;
char* pEndOfLine = response;
bool bFoundData = false;
while (!bFoundData && pEndOfLine)
{
  while (pEndOfLine != NULL && *pEndOfLine != '\n')
    pEndOfLine++;
  if (pEndOfLine && pEndOFLine != pStartOfLine)
  {
    char* pStartOfData = pStartOfLine;
    while (pStartOfLine != pEndOfLine && *pStartOfLine != ':')
      pStartOfLine++;
    if (*pStartOfLine != ':')
    {
      theData = strtod (pStartOfData, NULL);
      bFoundData = true;
    }
  }
}

If it's in a separate function then you could just return rather than use the Boolean.
The order of the lines in the header are not guaranteed, but will always be in the same order from the same device with the same software, so as a cheat you could look for 'Content-Length: 18\r\n' and then just take the next non-blank line after that, but this is a more hacky way of doing it.

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


text:
Mega + SIM808 GPRS GSM GPS IPX-SMA module power on from code
Is it possible to turn on the SIM808 module from code? There is a button in the SIM808 board to activate the module, but I need to turn it on from the code automatically. This is because my device will be stored hidden inside a vehicle so I do not have to keep turn on and off by hand.
This is the model.

Looking at the pictures it looks like it should be possible to take the two exposed connections of the switch and add flying leads to them and run them back to the microprocessor to allow it to turn them on and off.  The possible problem is the current that has to run through the switch.
You will need to investigate, but it looks like it could be done like that if you can't find a better solution.

Actually that switch should just be turned on. The problem is with the power button, I need to hold it for about 2 seconds and then release it to fully activate the module functions. That is the problem.

Sorry I said switch but I meant the button near where it says "Press this to Start"


text:
analogWrite is not working - while trying to control DC motor speed
I'm trying to control the speed of DC Motor using

Arduino R3
NPN Transistor (2N2222A331)
10k potentiometer
2M ohm resistor
Diode

I'm not using L298N and I'm also not using L293D.
DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer.
Circuit seems to be alright as DC motor is running.
The code is as follows
int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;

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

void loop()
{
 potValue = analogRead(potPin);
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);
 delay(2);
 Serial.print("potentiometer = " );
 Serial.print(potValue);
 Serial.print("t motor = ");
 Serial.println(motorValue);
}

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino  "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.
Things that I tried

tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.
this leads me - to believe that, my analogwrite isn't working.
please help me understand as to what i'm i doing wrong?
The Circuit is as follows

set the value with analogWrite only if it changed. now you restart PWM in every loop

Referring to this datasheet you have connected the transistor the wrong way around. Also, 1M resistor at the base is way too high. Bipolar transistors are current amplifiers (amplification at about 50-100 in your case) and with 1MOhm at the base there will be no current through the base at all. I would try with 2k for a beginning.
I hope you have another transistor because this one seems to be broken and I'm pretty sure that it's not a fault in the analog output. If the output stage of the uC was broke there would be no reaction (at least in a correct circuit)

Two things to test:

Have you tried to put an LED (and resistor to protect it) in the motor's place? If the brightness changes, your setup (Arduino+transistor) is working. If not, maybe you've killed your 2N2222 by giving it a wrong diode or something else is wrong.
Have you tried reducing the PWM frequency? An LED can follow a fast change, but a motor can't. Also, by turning on-off the motor less frequently you dissipate less power on your transistor and diode. A quick search gave me this: this.

Well, 2M resistor to the base? If the motor is running with that, the transistor must be broken (shorted). Just try to check if the motor is running with disconnected base.
You can also check PWM output by connecting LED with resistor (no, not 2M ohms, just about 330 ohms). For the transistor 1k should be sufficient maybe little less (depends on motor current and h21e amplification coeficient).
Also there are some versions 2N2222 with emitter and collector swapped. And reversed transistor has much lower current amplification coeficient.
And I hope you are using external power supply, USB is not a good idea. Starting power is usually way too much for the overcurrent protections.
Anyways, this works for me:
void setup() {
  pinMode(9, OUTPUT);
}

void loop() {
  analogWrite(9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(100);
}

2N2222A + 1k + PC FAN + 12V Fan Power supply.
Connections: E -> Gnd, C -> FAN-, FAN+ -> 12V, 12V GND -> Arduino GND, Pin 9 -> 1k -> B
On the Arduino side 47k trimmer and the USB

Thanks for the reply !! ....but issue remains !!
Motor is not running with disconnected base !!
i checked PWM output with LED and resistor (dimming brightness of LED) ....it seems to work as per expectation
Tried swapping the connections of emitter and collector .....DC motor ran but no speed control
adriuno dint powerup with 9v battery for the DC motor circuit....so im using USB as power supply !!
im running out of options , please do help me !!

@SharathChandra Works for me perfectly with PC FAN and external 12V PSU. Even with 2ms delays.

And also DC motor + antiparallel shottky is working (with own PSU)

Can you vary the speed of a plain DC motor using PWM?  I would think pulsed DC would play havoc with it, giving strange results. I'd expect to need an RC filter to convert the pulsed output into a fairly constant DC output. I know some servos are made to run on DC, but a normal DC motor?

@DuncanC Sure I can, but it's without the load. It's a small dc motor from some old walkman. However as it's DC motor with commutator, I don's see why it should be so bad, maybe bigger EMI. And the power peaks gives some extra torque at low RPMs.


text:
Having issue with a redeclaration as a different kind of symbol
Been struggling with this for a few days and I suspect that i have several issues but I cannot find them.
Project: Need a serial count that counts by 5-50 and a button interrupt should trigger a display of the current time and then continue counting.
Issue: Cannot complete compiling because my "void rtcTime()" is saying I am redeclared as different kind of symbol.
Any help the community can provide is greatly appreciated.
Code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include "RTClib.h"
#include <Wire.h>

RTC_DS1307 rtc;

int count = 5;
int rtcTime = 0;
int pin = 0;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup (){

  pinMode(2, INPUT);

  rtc.begin();

  while (!Serial); // for Leonardo/Micro/Zero

  Serial.begin(9600);

  if (! rtc.begin()) {
   Serial.println("Couldn't find RTC");
   while (1);
      }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    // rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
     }

     attachInterrupt(pin, rtcTime, RISING);
}

void loop()
{
  // Count X5 on Serial Monitor

  if (count > 50)
    {
    count=5;
    Serial.println(count);
    }

   else if (count<50)
    {
    count=count+5;
    Serial.println(count);
    delay(1000);
     }
  }

void rtcTime() {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    }

Error Message:

Arduino: 1.8.10 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560,
  ATmega2560 (Mega 2560)"
ds1307_workingCopy_Mod5:60:14: error: 'void rtcTime()' redeclared as
  different kind of symbol  void rtcTime() {
                ^ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:9:5:
  note: previous declaration 'int rtcTime'  int rtcTime = 0;
       ^~~~~~~ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:
  In function 'void setup()':
  /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:38:42:
  warning: invalid conversion from 'int' to 'void ()()' [-fpermissive]
        attachInterrupt(pin, rtcTime, RISING);
                                            ^ In file included from sketch/ds1307_workingCopy_Mod5.ino.cpp:1:0:
  /Users/kiko/Desktop/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/Arduino.h:150:6:
  note:   initializing argument 2 of 'void attachInterrupt(uint8_t, void
  ()(), int)'  void attachInterrupt(uint8_t, void (*)(void), int mode);
        ^~~~~~~~~~~~~~~ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:
  In function 'void rtcTime()': ds1307_workingCopy_Mod5:60:14: error:
  'void rtcTime()' redeclared as different kind of symbol  void
  rtcTime() {
                ^ /Users/kiko/Documents/Arduino/ds1307_workingCopy_Mod5/ds1307_workingCopy_Mod5.ino:9:5:
  note: previous declaration 'int rtcTime'  int rtcTime = 0;
       ^~~~~~~ Multiple libraries were found for "RTClib.h"  Used: /Users/kiko/Documents/Arduino/libraries/RTClib-1.3.3  Not used:
  /Users/kiko/Documents/Arduino/libraries/RTCLib_by_NeiroN Multiple
  libraries were found for "Wire.h"  Used:
  /Users/kiko/Desktop/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/Wire
  exit status 1 'void rtcTime()' redeclared as different kind of symbol
This report would have more information with "Show verbose output
  during compilation" option enabled in File -> Preferences.

It's not a good idea to use rtcTime for everything....

You gave the same name rtcTime to a variable and a function. Cannot work

I'm voting to close this question as off-topic because it's a pure programming problem, a very simple syntax error, not related to Arduino

KIIV, I have no emotional attachment to "rtcTime", just changed it to "buttonPressed" and changed it also in the declaration at the beginning to "volatile int buttonPressed=0". No change into the results, still error "void buttonPressed() redeclared as different kind of symbol", thanks for the input though, I did feel it to be better to stay away from words that may be commands.

@pancho22448 It kinda won't help, if you change both variable and function named rtcTime to buttonPressed... It's still variable and function with the same name buttonPressed after that change. Small hint: Change ONE OF THEM!

The Arduino builder doesn't create forward declarations of functions for functions used in code as callbacks. It has something to do with the occurrence of the name without the usual form of function call.
You could move the function rtcTime before setup() so it is visible for the use as parameter in attachInterrupt or you can create a forward declaration for the compiler. Your attempt to make the name of the function valid was to create a variable with this name. This way you created the error of duplicate name.
Add
void rtcTime();

before setup() function and remove int rtcTime = 0;


text:
HELP with, I think, are wrongly placed Interrupts
I am still struggling to get this sketch functional. The problem seems to lie with the interrupts, and relying on them to turn on and off the PIRtrigger when needed. Everything else seems to be OK. This is a slightly modified sketch from what I had uploaded earlier, with some changes that I thought would fix the problem. In general, a "correct" PIN disables the alarm from firing as it sets the "away" flag to "false", which works. An "incorrect" PIN sets "away" to "true" which, when a trigger is activated via an Interrupt, sounds the alarm. The program should then go to readKeypad for further function, which it appears to do. The following shows the result after an incorrect PIN:
Key_input[0] = #
@ checkPIN
@ incorrect PIN
away=1 PIRtrigger=0
at Alarm
after alarm

The trigger then doesn't seem to get activated. Can anyone HELP!? Thanks.
///////////////////////// 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;
volatile boolean PIRtrigger = false;
boolean away = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;
int timeout = 10000;
unsigned long time = millis();

//////////////////////////// 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()
{
  interrupts();
  readKeypad(); Serial.println ("at keypad");
  alarm();
}

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

///////////////////////////// void alarm ///////////////////////////////////
void alarm() {
//  PIRtrigger = false;
  time = millis(); // reset time.
  interrupts();
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  Serial.println ("at Alarm");
  if (away == true && PIRtrigger == true) {
    // (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);
      Serial.println (alarm_count);
    }
  }
  PIRtrigger = false;
  //  away = false;
  Serial.println ("after alarm");
  Serial.print ("away="); Serial.print (away); Serial.print (" "); Serial.print ("PIRtrigger="); Serial.println (PIRtrigger);
  noInterrupts(); /////////////////////////////////
  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();// go to correct PIN instructions
  }
  else {
    incorrectPIN(); // go to incorrect PIN instructions
  }
}

///////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  // digitalWrite (LED_OutPin, HIGH);
  digitalWrite (LED_OutPin, LOW); // on-board LED to show the status of alarm
  PIRtrigger = false; // turn the PIR state to off
  away = false; // turn the away state to off
  noInterrupts();
  readKeypad();
}

///////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
 //  noInterrupts(); // Serial.println ("interrupt off 1");
  Serial.println ("@ incorrect PIN ");
  away = true;
  digitalWrite (LED_OutPin, HIGH); // tied to Alarm output level
  //Has time passed? delay(timeout) - allow time to leave premises
  PIRtrigger = false;
    alarm();
  }

First, as AH L said, there is no HIGH interrupt on a Uno. Looking at Arduino.h we see:
#define HIGH 0x1
#define LOW  0x0

...

#define CHANGE 1
#define FALLING 2
#define RISING 3

Thus your HIGH interrupt (which doesn't exist) is really a CHANGE interrupt.
Next, you seem to be recursively calling stuff.

loop calls readKeypad.
readKeypad calls checkPIN
checkPIN calls correctPIN
correctPIN calls readKeypad

So this code is digging itself deeper and deeper into function calls. It will eventually run out of stack.
i.e.
readKeypad -> checkPIN -> correctPIN -> readKeypad -> checkPIN ...

You need to restructure.
See my page about interrupts.
Also see my page about state machines.

I know that it is ugly code; from repeatedly making changes/additions to try to get it to work. I have cleaned up some and will continue on others. Thanks for your feedback. I wasn't thinking about a stack issue.

How do I better manage the stack?

Don't do recursive calls. For example don't have a call b and inside b call a. Read the link I gave about state machines.

Thanks. I plan to try state machines in the very near future.

Most Arduinos don't support interrupting when a pin is HIGH. Try changing attachInterrupt (digitalPinToInterrupt (2), trigger, HIGH) to attachInterrupt (digitalPinToInterrupt (2), trigger, RISING).

Thanks. I had tried CHANGE and HIGH with same results. I will try RISING to see what happens.


text:
AT+CENG=2,0 What type is the returning LAC?
The AT+CENG=2,0 command is giving me this result:

+CENG: 0,"0794,48,00,510,10,53,7944,10,00,36e3,255"

My LAC is 36e3 but what is the type? (Int, Double, byte, string)?
I get this code to translate cell ID and LAC into lat long:
class GMM {
  public static byte[] PostData(int MCC, int MNC, int LAC, int CID) {
    /* The shortCID parameter follows heuristic experiences:
     * Sometimes UMTS CIDs are build up from the original GSM CID (lower 4 hex digits)
     * and the RNC-ID left shifted into the upper 4 digits.
    */
    byte[] pd = new byte[] {
      0x00, 0x0e,
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x00, 0x00,
      0x1b,
      0x00, 0x00, 0x00, 0x00, // Offset 0x11
      0x00, 0x00, 0x00, 0x00, // Offset 0x15
      0x00, 0x00, 0x00, 0x00, // Offset 0x19
      0x00, 0x00,
      0x00, 0x00, 0x00, 0x00, // Offset 0x1f
      0x00, 0x00, 0x00, 0x00, // Offset 0x23
      0x00, 0x00, 0x00, 0x00, // Offset 0x27
      0x00, 0x00, 0x00, 0x00, // Offset 0x2b
      0xff, 0xff, 0xff, 0xff,
      0x00, 0x00, 0x00, 0x00
    };
    Console.WriteLine(pd.Length);
    bool isUMTSCell = ((Int64)CID > 65535);
    if ((Int64)CID > 65536) /* GSM: 4 hex digits, UTMS: 6 hex digits */
      pd[0x1c] = 5;
    else
      pd[0x1c] = 3;
    pd[0x11] = (byte)((MNC >> 24) & 0xFF);
    pd[0x12] = (byte)((MNC >> 16) & 0xFF);
    pd[0x13] = (byte)((MNC >> 8) & 0xFF);
    pd[0x14] = (byte)((MNC >> 0) & 0xFF);
    pd[0x15] = (byte)((MCC >> 24) & 0xFF);
    pd[0x16] = (byte)((MCC >> 16) & 0xFF);
    pd[0x17] = (byte)((MCC >> 8) & 0xFF);
    pd[0x18] = (byte)((MCC >> 0) & 0xFF);
    pd[0x27] = (byte)((MNC >> 24) & 0xFF);
    pd[0x28] = (byte)((MNC >> 16) & 0xFF);
    pd[0x29] = (byte)((MNC >> 8) & 0xFF);
    pd[0x2a] = (byte)((MNC >> 0) & 0xFF);
    pd[0x2b] = (byte)((MCC >> 24) & 0xFF);
    pd[0x2c] = (byte)((MCC >> 16) & 0xFF);
    pd[0x2d] = (byte)((MCC >> 8) & 0xFF);
    pd[0x2e] = (byte)((MCC >> 0) & 0xFF);
    pd[0x1f] = (byte)((CID >> 24) & 0xFF);
    pd[0x20] = (byte)((CID >> 16) & 0xFF);
    pd[0x21] = (byte)((CID >> 8) & 0xFF);
    pd[0x22] = (byte)((CID >> 0) & 0xFF);
    pd[0x23] = (byte)((LAC >> 24) & 0xFF);
    pd[0x24] = (byte)((LAC >> 16) & 0xFF);
    pd[0x25] = (byte)((LAC >> 8) & 0xFF);
    pd[0x26] = (byte)((LAC >> 0) & 0xFF);
    return pd;
  }

  public static string[] GetLatLng() {
    string[] result = new string[2];
    try {
      String url = "http://www.google.com/glm/mmap";
      HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));
      req.Method = "POST";
      int MCC = Convert.ToInt32(510); //actual data
      int MNC = Convert.ToInt32(10); //actual data
      int LAC = Convert.ToInt32(36e3); //actual data - gives error here
      int CID = Convert.ToInt32(7945); //actual data
      byte[] pd = PostData(MCC, MNC, LAC, CID);
      req.ContentLength = pd.Length;
      req.ContentType = "application/binary";
      Stream outputStream = req.GetRequestStream();
      outputStream.Write(pd, 0, pd.Length);
      outputStream.Close();
      HttpWebResponse res = (HttpWebResponse)req.GetResponse();
      byte[] ps = new byte[res.ContentLength];
      int totalBytesRead = 0;
      while (totalBytesRead < ps.Length) {
        totalBytesRead += res.GetResponseStream().Read(
        ps, totalBytesRead, ps.Length - totalBytesRead);
      }
      string r = System.Text.Encoding.UTF8.GetString(ps);
      Console.WriteLine(r);
      if (res.StatusCode == HttpStatusCode.OK) {
        short opcode1 = (short)(ps[0] << 8 | ps[1]);
        byte opcode2 = ps[2];
        int ret_code = (int)((ps[3] << 24) | (ps[4] << 16) | (ps[5] << 8) | (ps[6]));
        if (ret_code == 0) {
          double lat = ((double)((ps[7] << 24) | (ps[8] << 16) | (ps[9] << 8) | (ps[10]))) / 1000000;
          double lon = ((double)((ps[11] << 24) | (ps[12] << 16) | (ps[13] << 8) | (ps[14]))) / 1000000;
          result[0] = lat.ToString();
          result[1] = lon.ToString();
          return result;
        } else {
          return result;
        }
      } else return result;
    }
    catch (Exception ex) {
      result[0] = ex.Message;
      return result;
    }
  }
}

Related: Get Latitude Longitude From AT+CNETSCAN and AT+CENG=2,0. If you don't know what LAC is, why do you care what type it is?

36e3  looks like a 16-bit hexadecimal value to me. Or it could be engineering notation (36×10³ - unlikely though since it would normally be represented as 3.6e4). What it means though I don't know - the manual would tell you.

@Nick I know what LAC is, but somehow the code above always returns null. So I was wondering if I pass the value incorrectly to google. I pass 14051 as LAC and google gives me nothing, the returning value is null.

@Juraj - Do you think this question deserves an up-vote? It's closed. The "same" moderator who closed it, answered it, and got 20 rep for it. Personally, I think it's a great question, so +10 rep.

LAC is "Location Area Code" - the code assigned by the operator to a group of cells that operate as one single broadcast unit.
It is returned to you as a hexadecimal representation of an unsigned 16 bit integer.
To know where the LAC is physically located on the planet you need to look it up in a table. I believe only the operator can give you that information. OS providers like Apple and Google most likely also have access to that data through agreements with operators.


text:
Connecting Arduino Mega + SIM800L to a car battery
I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.
So:
Car battery > Mega > SIM800L
What do I need to achieve this?
This is the SIM800L model:

I want to connect the car battery

The Mega has an NCP1117 linear voltage regulator onboard. This is qualified for automotive use, however the max. output current at 12V input voltage is only 1A, which is too less to supply your SIM800.
Next thing you should consider: The car voltage is not stable. Voltage peaks up to 40V can occur, especially when starting the engine. This will stress your components, and destroy them in worst case.
I would use two DC/DC converters with high enough input voltage and adjust one to 7V output (for the Arduino), the other one to 4V (for the SIM) and connect the ground lines together.
For voltage level matching between Arduino and SIM Uart see page 32 of SIM800 hardware manual.

With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).
First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).
Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in this image).


text:
Arduino writes only one time on SD card - Data log
I connected the SD card to Arduino as it's explained here. The problem is that the Arduino writes only once to the SD card and I don't understand the reason.
#include <SD.h>
#include <SPI.h>

int CS_PIN = 4;

File file;

void setup() {
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  Serial.print("Initializing SD card...");
  if (!SD.begin(CS_PIN)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("card initialized.");
}

void loop() {
  String dataString = "TEST";
  File dataFile = SD.open("datalog.txt");
  if (dataFile) {
    dataFile.println(dataString);
    dataFile.close();
    Serial.println(dataString);
  } else {
    Serial.println("error opening datalog.txt");
  }
  delay(1000);
}

The output on Serial Monitor:

Arduino write only one time on SD card error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt error opening
  datalog.txt error opening datalog.txt error opening datalog.txt error
  opening datalog.txt error opening datalog.txt

I also tried to use:
SD.open("file.txt", O_RDWR | O_APPEND);
SD.open("file.txt", O_RDWR | O_CREAT);

As I saw Adding data to an SD card file, but it doesn't work.

don't you need a mode when opening?

open the file in setup. then write data in loop. after all data has been written, close the file

You are opening the file in read mode but should be opening it in write mode. Change File dataFile = SD.open("datalog.txt"); to File dataFile = SD.open("datalog.txt", FILE_WRITE);.
You can remove this line of code: digitalWrite(10, HIGH);.
The arduino.cc website is also an excellent source of information regarding the SD library.

File dataFile = SD.open("datalog.txt");

Repeatedly opening the same file is probably not a good practice, if you want to retain previously written contents.

For people having the same problem. I had the same problem where the SD Card would only run the if statement once and then not read it anymore. For some reason, after I ran the CardInfo, DumpFile, and ReadWrite example scripts in the SD Library (changing the title of the SD.open() command to the one that I was using), my code began to work and it started running the if statement each time. I would recommend trying this if you're experiencing the same problem.

Interestingly enough, I was having a problem opening a file on my SD Card using the SD Card Reader Sensor and my Elegoo Mega2560 and running the CardInfo example ( on the SD Library) solved it for me. The first time the CardInfo example gave an error, and then (just saying what I did) I popped my SD Card and put it back in and then ran the CardInfo example again and then it worked. So... If you guys are having any problems. Try using the CardInfo example from the SD Library and re-insert your SD Card.

this indicates problems with the CS pin


text:
Interrupt fires a random number of multiple times for one pulse
This is my first time posting on this forum. I have tried to format this question properly, but let me know if I need to correct anything. I searched to see if someone else had a similar problem, but let me know if someone has already answered this question.
Overview: I am sending pulses to my Arduino, but sometimes one single pulse is interpreted as anywhere from 2 to 30 pulses. But after looking at the pulse on an oscilloscope (see Fig. 1) I am not sure why. When I use a really long wire the ratio of false pulses to legit pulses is about 1 to 1. I shortened the length of the wire and improved the situation, so that only 1 in about every 2,000 pulses is registered as a false pulse.
For one test, I added a capacitor to the short wire situation, but that increased the rise time and made the problem worse. I am currently using attachinterrupt and have tested the situation with using both a rising and falling edge. Right now, I mainly want to understand how interrupts work on the Arduino in light of my current problem, although I welcome general advice.

When I set the interrupt to the falling edge, why does the Arduino still sometimes count 1 pulse as several? The falling edge in the photo, which is for the really long wire case, lasts about 40 microseconds and appears to have a clean break. The pulse remains low for about 80 milliseconds. Could the falling interrupt trigger during the rise time based off the oscillatory behavior shown in Fig. 1? I smoothed out the signal by adding in a 1 nF capacitor, but the Arduino still counted false pulses. So could the rise time period have anything to do with it? I also have a 10k Ohm pullup resistor connected to the Arduino's 5 V for the pulse path.

I have the relevant code attached below. I have much more code as well, but it deals with saving pulseCounts to the SD Card and uploading electricity consumption files through the cell network.
Cheers.
//Global Variables
unsigned long pulse_time = 0;
unsigned long last_pulse_time = 0;
byte code = 1; //code let's me see if a false pulse was reported for each
//SD file

void setup() {
  attachInterrupt(digitalPinToInterrupt(3), onPulse, RISING);
}

void onPulse() {
  pulse_time = millis();
  if ((pulse_time - last_pulse_time) > 50 ) {
    Serial.println("Good Pulse");
    pulseCount++;
    last_pulse_time = pulse_time;
  } else {
    Serial.println("Bad Pulse");
    pulseCount++;
    code = 2;
  }
}

That is not a nice pulse. You can fix it with a rc filter and a transistor. The transistor can be triggered at a lower voltage. Looking at the scope picture, about 1.5 to 2V would be a good trigger voltage (because the 0V is much stronger than the 5V level). You may not use the Serial.println in a interrupt function because they use interrupts themself. Because of the Serial.println, you can not make any conclusions with this sketch.

Thanks, I ran the test again leaving out the Serial.println statements and instead printed the statements in loop(), but I still get false pulses. I believe I have tried a RC filter. I always have a 10 kOhm resistor tied to the 5 V line, but then I added a 1 nF capacitor between the pulse line and ground. The signal from that is much smoother, but it increases the rise time, so I still have false pulses. I could add a transistor, but before adding hardware I am more curious about why it is counting multiple pulses. Is there a way to determine if it is rise time or the oscillations?

How is the signal generated? Is it just pulled low by the external source? I'd try a lower value pull-up resistor? Also, a Schmitt trigger could help to prevent the effect of a (very) slow rise.

I have a pulse meter that generates a pulse for every unit of electricity consumed.  Yes, the pulse line is default high (5 V) and is then pulled low for the duration of the pulse to 0 V before returning high.  I have done a test with a 1 kOhm resistor, and it decreased the rise time to about 4 milliseconds as compared to about 25 milliseconds in the short wire case.  The signal looks smooth, but I have been warned that there may be unintended consequences for making a pull up resistor below 10 kOhms.  Is there a reason I should be hesitant about lowering the pull-up resistor value?

Firstly, unless the processor pin is a Schmitt trigger, increasing capacitance will only make the problem worse by allowing any noise to be interpreted as multiple high-low transitions.  For a CMOS logic input the area around the transition point of 1/2 VDD typical is actually an area of linear operation, not digital.
A Schmitt trigger introduces hysteresis such that when the signal is interpreted as a high level, it must go low by more than the hysteresis to be interpreted as a low level again.  This is accomplished with a bit of positive feedback added to a buffer where the output transition from low to high then pulls the input that much higher or a transition from high to low pulls the input that much lower:

The red line represents the typical CMOS threshold and the green lines represent the thresholds defined by the hysteresis of the Schmitt trigger.  The hysteresis defines the noise immunity of the input.  Most processors have pins that are equipped with a Schmitt trigger or and external device like a 74HC14 can be used.
Another way to deal with this type of noise is to lock out any transitions within the expected pulse-to-pulse transitions:  Once triggered, no more transitions are allowed until the lock out time expires.

ATmega inputs are Schmitt triggers.

Okay, from this article link  it mentions that for a 5 V arduino, VIH = 3.0 V.  Does that mean that if I set the Interrupt to RISING, that it should only trigger when the pin voltage starts below VIH and then becomes higher than VIH?  Is VIH the correct term for a CMOS threshold and does VIH = 3.0 V on my ATMEGA328 chip?  The oscillatory behavior on the oscilloscope seems to occur when the voltage is more than 4 V.

For that part at 5V the maximum low voltage (VIL) is 1V and the minimum high voltage (VIH) is 3V.  When an interrupt is set to trigger on a rising edge, then that means the input must go from low to high to generate an interrupt but even a short noise pulse of a few micro seconds from high to low to high again can generate a new interrupt.  I see from your scope capture that there is a lot of ripple on the input which means that there is probably a lot of ripple on your 5V... if your 5V goes higher while your input stays the same, this looks to the processor like the input is going lower.


text:
NodeMCU successfully uploaded sketch but it does not work from Arduino IDE
NodeMCU successfully compiled and uploaded a simple blink sketch on board, no errors at all, but the LED stays on constantly and does not blink. Also I have checked the power is enough. I have checked this with all pins but the red LED only stays on and doesn't blink. I have no idea what could have gone wrong. And how to fix this?

Fixed it....
turns out that in the tools, the board was selected to be NodeMCU 0.9
when it should actually have been NodeMCU 1.0
so i just changed it to NodeMCU 1.0 and it worked!

accept your answer to finalize this Q&A

@Juraj isn't there a 24h waiting period as on other sites?


text:
fatal error: avr\wdt.h: No such file or directory in Arduino Due
I am using an Arduino Due for vehicle tracking with a GPS/GPRS device. Before using Arduino Due I used an Arduino Uno. When I tryi to load my code in the Arduino Due, it shows me "fatal error: avr\wdt.h: No such file or directory". I can't delete the watchdog from my code as it is important for my device.
Now how can I solve this problem?

I googled this library https://www.arduinolibraries.info/libraries/sodaq_wdt

The Due is a very different board than the Uno. It uses a completely different architecture (ARM vs AVR). You can't use AVR-specific  code on an ARM chip, and the Watchdog code is AVR-specific.
You will have to find (or write) the equivalent ARM code using the Due's register set instead.

the question is "Now how can I solve this problem ?"

This may help: http://forum.arduino.cc/index.php?topic=350058.msg2416416


text:
How can I set up outputs without using digitalWrite?
Consider the following:
#define IN1 9
#define IN2 10

pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);

void LeftMotor(Direction direction) {
  digitalWrite(IN1, direction == Forward ? LOW : HIGH);
  digitalWrite(IN2, direction == Forward ? HIGH : LOW);
}

How can I modify the LeftMotor method to achieve the same result without using digitalWrite?

Nope! I want it to react faster.

https://www.arduino.cc/en/Reference/PortManipulation

This will not make it react faster. Add more of your sketch if you want help with that. Cheers!

@MikaelPatel: according to the link i posted above, it will be faster, because it's "able to turn pins on and off very quickly, meaning within fractions of a microsecond ... . Direct port access can do the same job in a lot fewer clock cycles." (than digitalWrite). Now for an hbridge, it's not going to make a hill of beans diff, but the OP's question is legit.

Why do you think that digitalWrite isn't fast enough for your application? Direct port manipulation will be significantly faster than using digitalWrite, but for most things (like controlling a motor) digitalWrite is plenty fast enough. Port manipulation is harder to set up, harder to understand, and is not portable across devices (the port assignments are different for different Arduino models.)

@DuncanC digitalWrite is slow. Teach the kid how to set the ports directly. Your advice is horrible. Setting the registers isn’t hard.

@PhillyNJ, if the use case demands fast code, sure. If not, I'd say stick with digitalWrite(). Premature optimization is the root of all evil, after all.

I've written commercial software in assembler, back when that's what you had to do to get reasonable performance. I wouldn't recommend it today, however, for the same reason I wouldn't recommend direct port manipulation unless you really need that level of performance. I wrote an Arduino app for high speed photography of shooting things with air rifles, and for that I used direct port manipulation.

what is unclear in the arduino tutorial about direct port manipulation?

@DuncanC - The OP wasnt asking when he/she should use digitalWrite vs setting the registers directly, they were asking how to set the ports directly. A perfectly valid question.

@PhillyNJ: I think I see Duncan C's point. If the OP finds his program is not fast enough, it is most likely not because of digitalWrite(). Especially if a motor is involved, which is thousands of times slower than digitalWrite(). We can then either directly answer the OP's question (which you did) or try to help him understand his actual problem (which Duncan tries to do).

@EdgarBonet - Thanks for your point of view. I fear that these types of comments hurt the community. In this case, we aren't total sure of what the limitations of the motor is. The bottle neck could be the motor or his/her code. The OP will find out soon enough if they try both ways. Its a good learning moment. I find digitalWrite to be very slow, exceptionally when writing to something like a TFT that expects lots of data. Teaching this OP whats under the hood of the Arduino Library is always good. Lets not discourage it.

I moved to this community after checking answers on the arduino forum. I suppose you have been there also in the past. Actually the project involved is about decoding RF signals from a receiver (6 shannels, each 1 to 2 ms input) plus 4 pwm's for output, which is time critical. I am sorry that the method name is missleading, but i just tried to keep my question as simple as i could.

For motors, especially starting/stopping/inverting direction, as the rest of the code and comments suggest, digitalWrite is definitely fast enough.

Setting ports directly is a great way to learn AVR programming. I might recommend this book Make: Avr Programming.
First you need to set the direction of the port in the Data Direction Register as either input or output. If Input, check its state and handle it. Here is a small example.
#define HIGH 1
#define LOW 0

#define  SWI_PIN PORTB0
#define  BUTTON PORTB4

int main (void)
{
    // set the pin directions
    DDRB |=  (1 << SWI_PIN); // output
    DDRB &= ~(1<<PORTB4); //input
    while(true){

      if ((PINB & (1<<BUTTON)) == 0){ // pin is high! Rising edge
          PORTB &= ~(1<<SWI_PIN); // LOW turn off swi_pin
      }else {
          PORTB |= (1<<SWI_PIN); // HIGH  turn on swi_pin
      }

}

Not all Arduino pins are on port B. There are macros to make your solution a bit more universal and as fast as yours.

@DataFiddler no of course not. This is an example not a full lesson on setting ports.

digitalWrite() is just a convenience function to hide away complexity from the user, so that she/he can just use a pin number and a value. This complexity takes some time to execute. If this is too slow for you, you need to go a bit deeper into the rabbit hole and use direct port manipulation:
Inside the microcontroller on the Arduino all the special functions for peripherals and such (digital IO, ADC, Serial(UART), SPI, Timer, ...) are configured via Special Function Registers (SFR). These are specific memory places, that are directly connected to the peripherals. You can configure the whole microcontroller by setting these registers to specific values.
For digital IO you first need to know, that the microcontrollers pins are ordered into groups of max 8 pins. These groups are called Ports. Each available port of the microcontroller gets a character, like PORTB. On the Arduino Nano for example PORTD includes the pins 0 to 7.
For each port we have 3 different SFRs (with the x being the character for the corresponding port), where each bit inside the registers corresponds to one pin:

DDRx controls the direction of the pins. If you set a bit to 1 in there, the corresponding pin is set as output. If you set it to zero, the pin will be an input (which is also called High-Z for high impedance, because a digital input pin has a very high resistance).
PORTx controls the output hardware of the digital pins. If you have set a pin as output (as described above) you can use the corresponding bit in the PORTx register to set it's state. If you write a 1 to the bit, the pin will become HIGH (means, the voltage on the pin will go to the same level as Vcc, the supply voltage of the micrcontroller). If you write a zero, the pin will go to LOW (meaning the same level as ground). The PORTx register has a different function, when you configured a pin as input. In this case, a 1 will turn on the interal pullup resistor of the pin, which pulls the level of the pin to HIGH, when nothing is pulling it down to ground (like a switch for example). A zero disables the pullup.
PINx reflects the current state of the pins. If you configured the pins as input, this is the voltage level, that currently lies at the corresponding pin (about the actual voltage levels, see below). A 1 at a bit means, that the corresponding pin is HIGH, else it is LOW.

You can read all of this in the datasheet of the used microcontroller. The datasheet is a must read (at least the relevant chapters), if you want to control the microcontroller via its registers. In most microcontrollers these registers are named as above. But some microcontrollers might define other names. The corresponding datasheet will list all the registers with rather detailed descriptions.
Now let's take that knowledge into actual code. Here I assume an Arduino Nano, though you can exchange that for most other microcontrollers.
// Configure pin D3 as output
DDRD |= (1 << PD3);
// Configure pin D2 as input
DDRD &= ~(1 << PD2);
// Check, if pin D2 is HIGH
if(PIND & (1 << PD2)){
    // Set pin D3 to HIGH
    PORTD |= (1 << PD3);
} else {
    // Set pin D3 to LOW
    PORTD &= ~(1 << PD3);
}

Excourse on bitwise operators: The code above can only be understood by knowing bitwise operators, which are very important for direct port manipulations. I will break down the operations, that are done there:

First we have PD2 and PD3. These are defines from the Arduino core. They are set to the index of the bit, that corresponds to the named pin. So PD2 is defined as 2, PD3 is defined as 3, PD0 as 0.
1 << PD3: The << operator does a bitwise left shift, which means all bits of the value on the left are shifted to the left by the amount standing on the right of the operator. We shift the value 1 three digits to the left here. In binary that looks like this:
0b00000001 << 3 = 0b00001000

That set bit in the result is exactly at the place, where the bits for pin PD3 will be in the Special Function Registers.
DDRD |= (1 << PD3):  This is the same as doing DDRD = DDRD | (1 << PD3), so the |= operator is just an abbreviation for it. The bitwise OR operator | will unite the bits from both sides. If a bit is set to 1 at either side, the result will also have set this bit to 1. This means, that we can set a bit to 1 with this.
~(1 << PD2): The tilde ~ takes the inversion of the data. Alike above, the value inside the paranthesis can be written as binary value 0b00000100. The inversion will flip all bits to the other value: 0b11111011
DDRD &= ~(1 << PD2): The abbreviation is similar to the above. The bitwise AND operator & will also unite the bits of the values around it, but it will only set the resulting bits to 1, if both of the corresponding bits of the values are also set. Here this results in the third bit (the one for D2) being cleared to zero. All other bits (where you can see a 1 at the right value) are left untouched.
PIND & (1 << PD2): This is similar to the above, but now we don't have an inversion. We are doing PIND & 0b00000100 here. All bits of the result will be set to zero, except for the bit for D2. It will only be zero, if the corresponding bit was zero in PIND. Thus we have isolated the needed bit by this way.

You can also combine the same operations on a single register. Let's say we want to set both D2 and D3 as output. Then we can either write this as two seperate statements
DDRD |= (1 << PD2);
DDRD |= (1 << PD3);

or we can combine them into one statement by connecting them with the bitwise OR
DDRD |= (1 << PD2) | (1 << PD3);

The Arduino documentation also provides a site to explain direct port manipulation. Also again you should take the time to look into the datasheet of your used microcontroller. At first it will seems very difficult, but doing these direct port manipulations is a great way of learning how to use the SFRs, and then you can do all sorts of cool stuff with your microcontroller. So it really is worth it. You don't need to read or understand the whole datasheet at once.

How can I modify the LeftMotor method to achieve the same result without using digitalWrite?

After all this text now to the specific question. On the Nano pin 9 and 10 are PB1 and PB2. You used a conditional inside your digitalWrite() statement, which I will replace by a complete if statement here. So you can use
if(direction == Forward){
    PORTB &= ~(1 << PB1);
    PORTB |= (1 << PB2);
} else {
    PORTB |= (1 << PB1);
    PORTB &= ~(1 << PB2);
}

instead of your two digitalWrite() statements.

I don't know why this question is downvoted. As for 'canonical' answer it is better than the other.Maybe someone has a problem with reading...

chrisl provided a very good reference answer. Here I am just adding a
few bits of information about the pin mapping and the pin electrical
states.
Pin mapping
One of the firs things you need when dealing with direct port access is
the mapping between the Arduino pin names and the names of the
microcontroller (MCU) pins as given by the manufacturer. For the Arduino
Nano the mapping is the following:
 Arduino │ MCU
─────────┼─────
   RX0   │ PD0
   TX1   │ PD1
   D2    │ PD2
        ...
   D7    │ PD7
   D8    │ PB0
        ...
   D13   │ PB5
   A0    │ PC0
        ...
   A5    │ PC5

where “PD0” means “pin number 0 of port D” and so on. Notice that pins
A6 and A7 are not listed here, as they are analog only, with no digital
I/O capability.
The information above can be found on the product page of the board,
under the “Documentation” tab. Alternatively, an image search for
“Arduino <board name> pinout” will find some nice schematics like
the one below:

Pin states
This has already been covered by chrisl's answer in the description of
the DDRx and PORTx registers. Below is a summary table showing the
four available electrical states of the pins, and how they are selected
with the DDR and PORT bits:
 DDR │ PORT │ electrical state │ equation
─────┼──────┼──────────────────┼─────────────────
  0  │   0  │  INPUT (high-Z)  │ I = 0
  0  │   1  │  INPUT_PULLUP    │ V = Vcc − Rpu I
  1  │   0  │  OUTPUT LOW      │ V = 0
  1  │   1  │  OUTPUT HIGH     │ V = Vcc

The provided equations relate the output voltage (V) and the output
current (I) of the pin. Beware that these are just rough approximations,
as:

they neglect the output resistance, which is of the order of
25 Ω
an input pin can have some (sub-µA) leakage current
the pullup resistor is not completely linear
the datasheet only provides weak guaranties, such as a range for the
output voltage, conditioned on the output current being low enough.

How can I set up outputs without using digitalWrite?

So this question is actually about the fastest possible implementation of digitalWrite.
As described in other answers this can be achieved by using direct port manipulation. But there are actually libraries (for instance, https://github.com/mikaelpatel/Arduino-GPIO) that does this in a portable way and avoids some of the errors that can occur. The library is 10-100X faster than the Arduino core digital pin functions.
Pins in a MCU are organized in ports. On the AVR there are a set of 8-bit port registers that hold the current pin setting. To change the value of a pin the CPU has to read the register and change the corresponding bit associated with the pin. This has to be done as an atomic operation, i.e. an interrupt may not occur during the update of the port register.
To allow a very fast update, i.e. one instruction/1-2 clock cycle, the CPU has a set of special instructions. For the AVR there are bit set and clear instructions for the 32 first special registers. On the Arduino Mega some of the pins/ports have higher address special registers and cannot use the special instructions. To make the pin operation atomic explicit interrupt handling must be added.
Other issues with direct port manipulation is portability. Code written using the AVR io handling cannot be used on SAM (e.g. Arduino Due). There is actually even issues when changing between AVR MCUs.
In short, a portable faster implementation of digital pin functions is recommended.
Below is the code written with the GPIO. It is portable and as fast as direct port manipulation.
#include "GPIO.h"

GPIO<BOARD::D9> IN1;
GPIO<BOARD::D10> IN2;

IN1.output();
IN2.output();

void LeftMotor(Direction direction) {
  IN1 = (direction == Forward ? LOW : HIGH);
  IN2 = (direction == Forward ? HIGH : LOW);
}

or
void LeftMotor(Direction direction) {
  IN1 = direction != Forward;
  IN2 = direction == Forward;
}

or
void LeftMotor(Direction direction) {
  if (direction == Forward) {
    IN1.low();
    IN2.high();
  }
  else {
    IN1.high();
    IN2.low();
  }
}


text:
Arduino Uno with ESP8266 Wifi transceiver or ESP8266 NodeMCU board?
I already have an Arduino Uno, and I want to learn Internet-of-Things. I'm planning to use an ESP8266 since it's cheap. Should I purchase an ESP8266 Wifi transceiver module to use with my Arduino Uno or just buy an ESP8266 NodeMCU board?
Is there any advantage using an ESP8266 NodeMCU board to using my Arduino Uno with an ESP8266 Serial transceiver module?

don't be "one of those guys", program the ESP8266; it's a million times faster with a billion times more ram and flash (an exaggeration, but true in spirit)

The Uno has its place, but its not an ideal platform for a connected device.  The ESP is bigger, but can connect less hardware, but if you need more hardware connections you can always slave an UNO to the ESP :)

In my opinion, it is more desirable to program the ESP8266 directly. I'm always shivering when I see a Uno (ab)using the ESP8266 as a WiFi bridge when the ESP8266 already has everything needed for the project. Of course, this is highly project specific.
Advantages of programming an ESP8266 directly:

you learn about a new MCU and architecture (XTensa vs AVR)
you learn to use a new Arduino Core (Arduino-ESP8266)
ESP8266 is way more powerful than the Arduino Uno

80MHz (overclockable to 160MHz) vs 16 MHz
~40kB free RAM at startup vs 2 kB
4 MB Flash vs 32kB
can use an RTOS like FreeRTOS
Flash can be used as filesystem (e.g. for a HTTP(S) server)
==> we can build way more complex projects

WiFi radio and stack directly on the processor, no need to get information via a serial bridge

higher speed, more direct control over sockets etc.

you can try out other frameworks and languages, such as

Micropython
esp-open-rtos
the NodeMCU firwmare (Lua language)
Espressif's NON-RTOS / RTOS SDKs

easier to move to its big brother, the ESP32 (Dual-Core XTensa LX6 @ 240MHz, WiFi + BT, 4MB Flash, 520kB RAM (+4MB PSRAM optional), tons of peripherals and accelerators) for even more complex projects

Disadvantages:

only 1 ADC input (vs. 6) with a voltage range of 0 to 1.0V (unlike the normal 5V range on the Uno)

remedy: external ADCs via I2C / SPI (e.g. MCP3008)

3.3V device, must be careful when connecting to existing 5V devices or shields

remedy: logic level shifters, voltage regulators

less number of available digital GPIO pins (9 vs 13)

remedy: external GPIO expanders via I2C/SPI (e.g. PCF8574, MCP23017)

In summary, I think a good way of acquiring a better skillset is to try to explore and program a new board directly vs programming the old board and slapping the new one on top over serial. I hope this gave a rough overview of why an ESP8266 might be better (or worse) for a certain project.

Really good answer +1 isn't enough.


text:
3 sensors and wemos d1 r1 and web
I need to build an app that will display on browser data from 3 sensors.
My 3 sensors are: Humidity and temperature (DHT22), vibration sensor and distance sensor (HC-SR04).
I want to connect these 3 sensors to my WeMos D1 R1 and to send the data to be displayed on a webpage. Until now, I can locally (from Serial monitor of Arduino IDE) read the sensors one by one - I mean, I upload the code for each one... I don't know how to combine the 3 codes to work.
So my main question is how to combine these 3 codes into one and access the data from a webpage?
My codes are : vibration (I want to get rid of the LED, just to display the vibration value)
int LED_Pin = D13;
int vibr_Pin = D2;

void setup(){
  pinMode(LED_Pin, OUTPUT);
  pinMode(vibr_Pin, INPUT); //set vibr_Pin input for measurement
  Serial.begin(9600); //init serial 9600
}

void loop(){
  long measurement =TP_init();
  delay(50);
  Serial.println(measurement);
  if (measurement > 4000){
    digitalWrite(LED_Pin, HIGH);
  } else {
    digitalWrite(LED_Pin, LOW);
  }
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

DHT22 code:
#include <SimpleDHT.h>

// for DHT22,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT22 = D8;
SimpleDHT22 dht22;

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

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT22...");

  // read without samples.
  // @remark We use read2 to get a float data, such as 10.1*C
  //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
  float temperature = 0;
  float humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT22 failed, err="); Serial.println(err);delay(2000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((float)temperature); Serial.print(" *C, ");
  Serial.print((float)humidity); Serial.println(" RH%");

  // DHT22 sampling rate is 0.5HZ.
  delay(2500);
}

HC-SR04 CODE :
// defines pins numbers
const int trigPin = D5;
const int echoPin = D6;
// defines variables
long duration;
int distance_cm;
int distance_in;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(500);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(trigPin, LOW);
  /* Reads the echoPin, returns the sound wave
     travel time in microseconds */
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance_cm = duration / 58;
  distance_in = duration / 148;
  Serial.print("Distance: ");
  Serial.print(distance_cm);
  Serial.println(" centimeters");
}

I managed to merge the 3 codes into 1. I still need to adapt it to send the information on a webpage. Up to now, the code for 3 sensors is:
#include <SimpleDHT.h>

// for DHT22,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
const int trigPin = D5;
const int echoPin = D6;
long duration;
int distance_cm;
int distance_in;
int vibr_Pin = D8;
int pinDHT22 = D2;
SimpleDHT22 dht22;

void setup() {
  Serial.begin(9600);
  pinMode(vibr_Pin, INPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("TEMPERATURE & HUMIDITY");

  // read without samples.
  // @remark We use read2 to get a float data, such as 10.1*C
  //    if user doesn't care about the accurate data, use read to get a byte data, such as 10*C.
  float temperature = 0;
  float humidity = 0;
  int err = SimpleDHTErrSuccess;
  if ((err = dht22.read2(pinDHT22, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT22 failed, err=");
    Serial.println(err);delay(2000);
    return;
  }

  Serial.print("Temperature & Humidity: ");
  Serial.print((float)temperature); Serial.print(" *C, ");
  Serial.print((float)humidity); Serial.println(" RH%");

  // DHT22 sampling rate is 0.5HZ.
  delay(2500);
  Serial.println("=================================");
  Serial.println("VIBRATION");
  long measurement =TP_init();
  delay(50);
  Serial.print("measurement = ");
  Serial.println(measurement);
  Serial.println("=================================");
  Serial.println("DISTANCE");
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(500);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(500);
  digitalWrite(trigPin, LOW);
  /* Reads the echoPin, returns the sound wave
     travel time in microseconds */
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance_cm = duration / 58;
  distance_in = duration / 148;
  Serial.print("Distance: ");
  Serial.print(distance_cm);
  Serial.println(" centimeters");
}

long TP_init(){
  delay(10);
  long measurement=pulseIn (vibr_Pin, HIGH);  //wait for the pin to get HIGH and returns measurement
  return measurement;
}

So, in the serial monitor of Arduino IDE, we will see the values displayed for our 3 sensors. I would really appreciate if somebody can help me to integrate this code to an IoT platform.

https://thinger.io

I don't know if you can understand the code of my project, but there is a WebServer with html and js files you could modify for your use and the project is build up from multiple ino files for different sensors and actuators with setup and loop in every ino file https://github.com/jandrassy/Regulator/tree/master/Regulator

i will have a look and that link. my main problem is that my coding skills are basic and its hard for me to create/understand more complex structures. i need to do this application i've posted here to integrate it into a bachelors degree diploma project and i have only a few days left :(

I would suggest using thinger.io.  It has a library that is insanely simple to use.
This is code for a greenhouse monitor that I wrote using their library. It exposes the temperature and humidity from a DHT22, the time the unit has been running, and when it was last programmed. And all with OTA support as well.
#include <ESP8266WiFi.h>
#include <dht.h>
#include <ThingerESP8266.h>
#include <ArduinoOTA.h>
#include <Average.h>

dht dht22;

Average<float> temperature(10);
Average<float> humidity(10);

ThingerESP8266 thing("myaccount", "thisunit", "somekey");

void getSample() {
    static uint32_t ts = 0;
    if (millis() - ts < 10000) {
        return;
    }
    ts = millis();

    dht22.read22(D6);
    int samples = 0;
    while (
        (dht22.temperature < -100) ||
        (dht22.temperature > 200) ||
        (dht22.humidity < -100) ||
        (dht22.humidity > 200))
    {
        delay(10);
        dht22.read22(D6);
        samples++;
        if (samples > 10) {
            return;
        }
    }
    temperature.push(dht22.temperature);
    humidity.push(dht22.humidity);
}

void setup() {
    WiFi.hostname("Greenhouse");
    thing.add_wifi("MyWiFiSSID", "MyWiFiPSK");

    thing["temperature"] >> [](pson& out) {
        getSample();
        out = temperature.mean();
    };
    thing["humidity"] >> [](pson& out) {
        getSample();
        out = humidity.mean();
    };
    thing["uptime"] >> [](pson& out) {
        out = millis() / 1000.0;
    };
    thing["compiled"] >> [](pson& out) {
        out = __DATE__ " " __TIME__;
    };

    ArduinoOTA.setHostname("Greenhouse");
    ArduinoOTA.setPassword("MyOTAPassword");
    ArduinoOTA.begin();
}

void loop() {
    thing.handle();
    ArduinoOTA.handle();
}

It's a little more complex that you may need, since I do averaging and filtering of the sampled data to clean it up a little. All the magic of when to take samples and how to deal with the data is done on the thinger.io website. But the code, as you can see, is insanely simple.


text:
Distance Sensor. Calculating running median and average
I'm trying to smooth out values for my IR distance sensor through running median filtering and a running average. I've tried to do the averaging, but my values don't seem correct and I am confused about how I would do the median filtering. I am also using timer interrupts and I don't want to use libraries when calculating the average and median. I've attached the code where I attempted to calculate the average.
int analogpin = 5;
int sum = 0;
int index = 0;
int averead = 0;
const int numreadings = 9;
int i;
int timer1_counter;
int adc_val;
int int_flag;
int int_array[9];
float V;

void setup() {
  int_flag = 0;
  Serial.begin(9600);
  pinMode(analogpin, OUTPUT);
  for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
  }

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  timer1_counter = 59286;
  TCNT1 = timer1_counter;
  TCCR1B |= (1 << CS12);
  TIMSK1 |= (1 << TOIE1);
  interrupts();
}

ISR(TIMER1_OVF_vect) {
  TCNT1 = timer1_counter;
  int_flag = 1;
}

void loop() {
  if (int_flag == 1) {
    adc_val = analogRead(A2);
    V = 5.0 * adc_val / 1023.0;
    analogWrite(analogpin, adc_val / 4);
  }
  sum = sum - int_array[i];
  int_array[i] = analogRead(A2);
  sum = sum + int_array[i];
  index = index++;
  if (i == 9) {
    i = 0;
  }
  averead = sum / numreadings;
  Serial.print("\n"); Serial.print("Average Filter Reading: ");
  Serial.println(averead);
  delay(1);
}

index=index++; does nothing. Either use index=index+1; of index++. Also, you are using i for the array-index, but only (try to) increment index. I think that should be i=i+1. Because nowhere else i is changed, you always overwrite the same element in the array.

You're using int_flag in an ISR, shouldn't it be volatile? Also in loop() you never reset it to 0. This can't be right...

There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment index (with a bad
syntax), while you should be incrementing i instead. The second
problem is these lines:
for (i = 0; i <= 8; i++) {
    int_array[i] = 0;
}

Fix the index vs. i confusion, remove the lines above, and your
program should work.
Explanation: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index i has the value 9. Later, in loop(), and assuming you fixed
the first issue, the program does
i++;
if (i == 9) {
    i = 0;
}

and i has the value 10. From there i will continue incrementing, and
you are always writing outside of the array.
The root of the problem is that you used the same variable i for two
different purposes. There are several solutions to this:

use different variable names for different purposes
use local variables whenever applicable (here: in setup())
be defensive in your tests: instead of if (i == 9) write
if (i >= 9), but note that this alleviates but does not completely
solve the problem
remove the initialization of the array altogether.

I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.

Ok thank you. I will try that. Also, would you be able to explain to me how I would be able to calculate a running median as well? I'm pretty confused about that.

The OP does not seem to actually increment i, which might be the real problem. Also, sum isn't initialzed with analog values, so in my understanding averead will just be the last analog value divided by 9.

@SimSon: Indeed. I edited my answer.

@eateat: The simplest way to compute a running median is to copy the circular buffer into a temporary array, sort that array, and return the element in the middle. It may not be the most efficient way though. If you need a more detailed answer, look into existing running median libraries, or ask a proper question on this site.

analogRead() returns an integer and therefore your calculation V=adc_val*(5.0/1023.0) will be casted as int as well. I suggest changing it to V=5.0*adc_val/1023.0.
In general a running mean can be calculated like this:
#define buffer_size 9
#define analog_pin 5

int ring_buffer[buffer_size];
uint8_t index=0;
float running_mean() {
  ring_buffer[index]=analogRead(analog_pin);
  float mean=0;
  for (uint8_t i=0;i<buffer_size;i++) {
    mean+=ring_buffer[i];
  }
  if (++index>=buffer_size) index=0;
  return mean/buffer_size;
}

You should flush the buffer during initialization, otherwise you don't get proper readings before the 9th iteration.

Would that give a  proper average?

You didn't post a complete code snipped, so I can't say. But the line I mentioned will disturb averaging as the resulting resolution will decrease by 200 times.

But there is no magic about averaging: store data in a ring buffer and to calculate the mean: accumulate this biffer and divide by the buffer length

I'm doing that, but the values I am getting are very different from the unfiltered A to D readings (ie. like 247 for unfiltered and 63 for filtered).

I've added my full code.

Ok, I saw that you even don't use V and there are other parts in that code that do not make a lot of sense (at least in this snippet). Provide a minimal example that reproduces the error and is complete so we can compile it. Also you should enable compiler warnings, I'm sure there are some

So when I run the code that I gave you, it returns this:
Average Filter Reading: 61
Average Filter Reading: 61

Average Filter Reading: 60

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

Average Filter Reading: 61

you should tidy up or rethink/reimplement your code, you will then eliminate some errors, as there are: you don't reset your flag; you do not accumulate sum as you add and substract from it; you don't increment i even though you check its value. Google for "ring buffer" and you will understand how to write to int_array. You then need a function that reads a new analog value, writes it to the array and calculates and returns the average of int_array. This function can somehow substitute the actual analogRead() function.

Ok thank you. I will look into that. Also, how would I calculate a running median?

I can't say by heart, but that will not be the problem and only need some small changes. Also I don't think it will make a change as you only have 9 elements.

I've been kind and edited my answer with a possible function. Please note that I have no chance to test it right now

Re “your calculation V=adc_val*(5.0/1023.0) will be casted as int as well”: No, this is incorrect. It will be floating point.

Also note that, although the OP's original code has some errors, it uses an algorithm that is more efficient than the one you are proposing here.

Here is a simple alternative suggestion: Assuming you already know the average distance d and a new reading v comes in. The difference v-d can be used to update the average. But since you want you want to smooth this out over several readings, you only update d by a fraction of the difference: d += 0.8*(v-d). The factor controls the smoothing.
To get this started, you estimate that the first value you read is the average. This does not require an array to keep past readings around.

As the simplest IIR low pass filter, this is one of the most widely used. It is known as an exponentially weighted moving average.


text:
LSM9DS1 breakout - How to increase speed
With regards to the Adafruit LSM9DS1 breakout:
enter link description here
And using the Library:
enter link description here
I am trying to increase the sample rate, or speed of this chip.
I am using a Sparkfun Pro Micro 5V
With the adafruit library, you need to request accelerometer, gyro, magnetometer and temperature at once, and all I need is the accelerometer values. I am hoping by figuring out how to request only the accel values it will speed up the loop. But also, there must be another setting that could speed up the sample rate?
Any help would be appreciated!
my code currently:

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_LSM9DS1.h>
#include <Adafruit_Sensor.h>  // not used in this demo but required!
Adafruit_LSM9DS1 lsm = Adafruit_LSM9DS1();
#define LSM9DS1_SCK A5
#define LSM9DS1_MISO 12
#define LSM9DS1_MOSI A4
#define LSM9DS1_XGCS 6
#define LSM9DS1_MCS 5

void setupSensor()
{
  // 1.) Set the accelerometer range
  lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_2G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_4G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_8G);
  //lsm.setupAccel(lsm.LSM9DS1_ACCELRANGE_16G);

  // 2.) Set the magnetometer sensitivity
  lsm.setupMag(lsm.LSM9DS1_MAGGAIN_4GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_8GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_12GAUSS);
  //lsm.setupMag(lsm.LSM9DS1_MAGGAIN_16GAUSS);

  // 3.) Setup the gyroscope
  lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_245DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_500DPS);
  //lsm.setupGyro(lsm.LSM9DS1_GYROSCALE_2000DPS);
}

double accelX = 0;
double accelY = 0;
double accelZ = 0;
double rms = 0;

void setup()
{
  Serial.begin(115200);
  // Try to initialize and warn if we couldn't detect the chip
  if (!lsm.begin())
  {
    Serial.println("Oops ... unable to initialize the LSM9DS1. Check your
wiring!");
    while (1);
  }
  Serial.println("Found LSM9DS1 9DOF");
  setupSensor();
  delay(5000);//program stabilization
}

void loop()
{
  lsm.read();
  sensors_event_t a, m, g, temp;
  lsm.getEvent(&a, &m, &g, &temp);
  accelX = a.acceleration.x;
  accelY = a.acceleration.y;
  accelZ = a.acceleration.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}

Check the header of the library,
you will find readAccel readMag readGyro and readTemp in separate public functions and looking at the implementation of read it just calls those 4 in sequence. readAccel will update the accelData member field.
So you can just call lsm.readAccel() in the loop and then grab lsm.accelData directly and ignore the rest.
void loop()
{
  lsm.readAccel();
  accelX = lsm.accelData.x;
  accelY = lsm.accelData.y;
  accelZ = lsm.accelData.z;
  rms = (accelX*accelX)+(accelY*accelY)+(accelZ*accelZ);
  Serial.println(rms);
}

Thanks! I'll try this out, hopefully it will speed up the sampling a bit

This worked, the sample rate is significantly faster now that I implemented the code above from @ratchet freak

@MattG having looked at the code in a bit more detail it looked like getEvent also did a read(). So your original code was doing a full read twice and only using the data for half the samples actually read.

that makes sense, it is significantly faster now that I implemented your suggestions. Thanks again.

Here is a link to the LSM9DS1 datasheet. In Chapter 3 it describes how to put the device in Accelerometer-only mode. At a quick scan of it, I believe there was timing information also, but at least knowing how to do it, you could then make your own timing measurements.

I see you can put the device into accel mode only, but unfortunately I don't understand how to actually implement the instructions. Is this something that would be changed in the library files?

In the Adafruit library's Adafruit_LSM9DS1.h at line 243 are a handful of functions to read individual sensors (Sensor& getAccel ( void ) { return _accelSensor; }, for instance). To get the timing benefit, you may need to put the device in accel-only mode, which, yes, will need some study of the library .cpp file to figure out how to do it or where to add the capability. I also see that there are some data-rate selections available. But that's about all I know of this device. Any more will need looking at the library code and the datasheet.

ok, thanks for the input and help on this @jrobert !


text:
avr-gcc -D is ignored
Im trying to use XCode to compile avr program with arduino libs but seems like something wrong with my Makefile because it throws me warnings like
# warning "F_CPU not defined for <util/delay.h>"

but I use -D on CC and CXX which should define stuff I thought, here is my Makefile:
TARGET              = firmware
MCU                 = atmega32u4
F_CPU               = 16000000L
USB_VID             = 0x2a03
USB_PID             = 0x8036
USB_PRODUCT         = "USB Device"
USB_MANUFACTURER    = "Unknown"
ARDUINO_VERSION     = 107010

CC   =
CXX  = avr-g++
AR   = avr-ar
COPY = avr-objcopy
SIZE = avr-size
DUDE = avrdude

CFLAGS = -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)

CXXFLAGS = -c -g -Os -w -fno-exceptions -fno-threadsafe-statics -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)
all: compile

compile:

    $(shell $(CXX) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo src/program.cpp -o build/program.cpp.o)

    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/hooks.c -o build/hooks.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/WInterrupts.c -o build/WInterrupts.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring.c -o build/wiring.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_analog.c -o build/wiring_analog.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_digital.c -o build/wiring_digital.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_pulse.c -o build/wiring_pulse.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_shift.c -o build/wiring_shift.c.o)

    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/abi.cpp -o build/abi.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/CDC.cpp -o build/CDC.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial.cpp -o build/HardwareSerial.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial0.cpp -o build/HardwareSerial0.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial1.cpp -o build/HardwareSerial1.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial2.cpp -o build/HardwareSerial2.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial3.cpp -o build/HardwareSerial3.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HID.cpp -o build/HID.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/IPAddress.cpp -o build/IPAddress.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/main.cpp -o build/main.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/new.cpp -o build/new.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Print.cpp -o build/Print.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Stream.cpp -o build/Stream.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Tone.cpp -o build/Tone.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/USBCore.cpp -o build/USBCore.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WMath.cpp -o build/WMath.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WString.cpp -o build/WString.cpp.o)

    $(shell $(AR) rcs build/core.a build/hooks.c.o)
    $(shell $(AR) rcs build/core.a build/WInterrupts.c.o)
    $(shell $(AR) rcs build/core.a build/wiring.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_analog.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_digital.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_pulse.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_shift.c.o)
    $(shell $(AR) rcs build/core.a build/abi.cpp.o)
    $(shell $(AR) rcs build/core.a build/CDC.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial0.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial1.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial2.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial3.cpp.o)
    $(shell $(AR) rcs build/core.a build/HID.cpp.o)
    $(shell $(AR) rcs build/core.a build/IPAddress.cpp.o)
    $(shell $(AR) rcs build/core.a build/main.cpp.o)
    $(shell $(AR) rcs build/core.a build/new.cpp.o)
    $(shell $(AR) rcs build/core.a build/Print.cpp.o)
    $(shell $(AR) rcs build/core.a build/Stream.cpp.o)
    $(shell $(AR) rcs build/core.a build/Tone.cpp.o)
    $(shell $(AR) rcs build/core.a build/USBCore.cpp.o)
    $(shell $(AR) rcs build/core.a build/WMath.cpp.o)
    $(shell $(AR) rcs build/core.a build/WString.cpp.o)

    $(shell $(CC) -w -Os -Wl,--gc-sections -mmcu=$(MCU) -o build/program.cpp.elf build/program.cpp.o build/core.a -Lbuild -lm)

    $(shell $(COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 build/program.cpp.elf build/program.cpp.eep)
    $(shell $(COPY) -O ihex -R .eeprom build/program.cpp.elf build/program.cpp.hex)

$(TARGET).bin: compile

    $(shell $(COPY) -O binary build/program.cpp.elf $(TARGET).bin)

clean:

Where did you read that you want to use $(shell ...) for all commands?

found in web, XCode show error " *** missing separator . Stop" if I not using shell

@user840250 Do you have a tabs as indents? Four spaces won't work in Makefile.

You're confusing CPP (the C PreProcessor, avr-cpp when called from avr-gcc or avr-g++) with CXX (avr-g++) with disastrous results.

You are using $(CPPFLAGS) for *.cpp files but only $(CXXFLAGS) are defined.
This should be obvious from command line (if you enable showing executed commands for make)
And also:

CC =
using $(CPP) again only $(CXX) is defined

And don't forget Makefile needs tabs for indenting target commands (here you have four spaces, but it might be just replaced by SE)

oh... seems like I need some sleep :) thanks.


text:
Blinking LED's at changing rate
I am trying to blink two LED's, starting at slow rate then increasing to fast s follows: 1 on, 1&2 on, 2 on, 1&2 on, 1 on, etc. The blinks go through the loop twice then speed up and repeat until both are on continuously. Then I want LED's 3 & 4 to come on.
I got the 1 & 2 LED's to blink as I want but anything I put following my for / if loop goes into the loop.
This works for blinking the 1 & 2 LED's:
int led1 = 9;
int led2 = 10;
int led3 = 11;
int led4 = 12;
int delay1 = 700;
int delayAmount1 = delay1 / 10;

void setup() {

pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
}

void loop() {{
delay1 = delay1 - delayAmount1;

for (int i=0 ; i <2 ; i++) {

if (delay1 > 10)

digitalWrite(led1, HIGH); //yellow on (yellow)

delay(delay1);

digitalWrite(led2, HIGH); //red and yellow on (orange)

delay(delay1);

digitalWrite(led1, LOW); //yellow off (red)

delay(delay1);

digitalWrite(led1, HIGH); //yellow on (orange)

delay(delay1);

digitalWrite(led2, LOW); //red off (yellow)

digitalWrite (led1, LOW); //yellow off (all off)

}
}

// digitalWrite(led3, HIGH); //blue on

//delay(1000);

//digitalWrite(led4, HIGH); //green on

}

If I remove the // from
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

they become part of the loop. Can someone tell me what I am doing wrong? Kind of new to this.

check the line if (delay1 > 10)

The if(delay1>10) does not have the conditional code in {}, so it should look like
if(delay1>10) {
//conditional code, what happens if statement == true
}

And if I understood your project and code correctly, when delay1 <= 10 then you want the led3 and led4 to light up. So you want to add an optional else{} block. This optional block will be skipped, if the if statement is executed. If the if statement is not executed, because for example your delay1 is smaller or equal to 10, then the else block will be executed.
else{
//led3 and led4 light up
}

You have a number of code formatting problems, some aesthetic, and some structural.
You need to indent your code, and you need to use braces. If you don't format your code well you will have a very hard time figuring out what you are doing.
Here is an attempt to clean up your code:
void loop() {
delay1 = delay1 - delayAmount1;

for (int i=0 ; i <2 ; i++) {
    if (delay1 > 10) {
        digitalWrite(led1, HIGH); //yellow on (yellow)
        delay(delay1);
        digitalWrite(led2, HIGH); //red and yellow on (orange)
        delay(delay1);
        digitalWrite(led1, LOW); //yellow off (red)
        delay(delay1);
        digitalWrite(led1, HIGH); //yellow on (orange)
        delay(delay1);
        digitalWrite(led2, LOW); //red off (yellow)
        digitalWrite (led1, LOW); //yellow off (all off)
    }
}
// digitalWrite(led3, HIGH); //blue on
//delay(1000);
//digitalWrite(led4, HIGH); //green on

}
(I'm not sure what's supposed to be inside the if statement or not since you didn't have an opening brace.)
You also had 2 opening braces on your loop statement, which is very odd.
Note that using delay() to try to control more than one thing at a time is a bad idea. The delay() function causes your program to freeze everything until the delay is over. If you try to blink different LEDs at different rates, you can't. If you try to detect button presses while you are also blinking LEDs, you miss the button presses while your code is in a delay. There are lots of threads on the various Arduino boards on how to avoid using delay. Search on "Arduino blink no delay" to find the basics.