text:
Does not execute code on loop;only run code of set up
only display this:
ARDUMOTIVE
ArduinoBased
compassn.Compass
Michalis Vas.

nothing else. I tried another Arduino Uno, Mega, Nano, but execute only set up. Display is working.No compiler errors.Sketch upload it with out errors!!
i found here https://www.instructables.com/id/Arduino-Digital-Magnetic-Compass-HMC5883L-2-displa/
Code is here.Thank you.
`*          Ardumotive.com Project Corner
   Arduino digital magnetic Compass with two display modes
   using 3-Axis Digital Compass IC HMC5883L board
   Dev. Vasilakis Michalis / Ver. 1.0 / Date:17/3/2015      */

//Include libraries
#include <SPI.h>
#include <Wire.h>
#include <Button.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>
#include <Adafruit_HMC5883_U.h>
#include <Adafruit_Sensor.h>

//Init Display (SCLK, DIN, D/C, CS, RST)
Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);
//Init HMC5883L sensor
Adafruit_HMC5883_Unified compass = Adafruit_HMC5883_Unified(12345);

//Constants
const int lcdLight = 13; //BL pin of LCD to arduino pin 13 (BL = Back Light)
Button buttonA = Button(2,HIGH); //Button to turn on/off display light
Button buttonB = Button(8,HIGH); //Button for changing display mode
// For 1st display mode:
static unsigned char Leters[] = { 'N' , 'E' , 'S' , 'W' };
const static unsigned char PROGMEM arrow_bmp[] ={B00100000, B00100000, B01110000, B01110000, B11111000,};
// For 2nd display mode:
int r = 24; // radius of compass rose
int x0= 60; // x-origin
int y0= 24; // y-origin

//Variables
int flag=0;//Store buttonA condition 0:1st display mode / 1: 2nd display mode
int i=1;   //Store buttonB condition 1: light on / 0: light off

void setup() {
  pinMode(lcdLight, OUTPUT); // lcd led
  compass.begin();
  Wire.begin();
  display.begin();
  display.setContrast(60);
  //Print a welcome message in startup for 6sec.//////////
  digitalWrite(lcdLight,HIGH);
  display.clearDisplay();   // clears the screen and buffer
  display.setTextColor(BLACK);
  display.setCursor(0,2);
  display.print("  ARDUMOTIVE  ");
  display.setCursor(0,13);
  display.print(" ArduinoBased ");
  display.setCursor(0,23);
  display.print(" compassn.Compass ");
  display.setCursor(0,33);
  display.print(" Michalis Vas.");
  display.display(); // show splashscreen
  digitalWrite(lcdLight,LOW);
  delay(6000);
  /////////////////////////////////////////////////////////
  display.clearDisplay();   // clears the screen and buffer
}

void loop() {

  //if buttonB is pressed, 'flag' will change between 0 and 1
    if(buttonB.isPressed()){
      delay(100);//small delay
    if(flag==0){ flag=1; }
    else{ flag=0; }
  }
  //if buttonA is pressed, 'i' will change between 0 and 1
  if(buttonA.isPressed()){
    if(i==0){ i=1; }
    else{ i=0; }
  }
  //if i is equal with 0, set display light on, else set display light off
    if (i==0){
  digitalWrite(lcdLight,HIGH);}
    else{
  digitalWrite(lcdLight,LOW);
   }
  //Reading and calculate degrees:   /////////////////////////////////////
  //Get new sensor value every time that loop starting again
  sensors_event_t event;
  compass.getEvent(&event);
  //Variable heading stores value in radians
  float heading = atan2(event.magnetic.y, event.magnetic.x);

  // Once you have your heading, you must then add your 'Declination Angle', which is the 'Error' of the compassnetic field in your location.
  // Find yours here: http://www.compassnetic-declination.com/
  // Mine is: -13* 2' W, which is ~13 Degrees, or (which we need) 0.22 radians
  float declinationAngle = 0.22;  //<--Change 0.22 with yours. If you can't find your declination juct delete those lines ;)
  heading += declinationAngle;
  // Correct for when signs are reversed.
  if(heading < 0)   heading += 2*PI;
  // Check for wrap due to addition of declination.
  if(heading > 2*PI)heading -= 2*PI;
  // Convert radians to degrees for readability.
  float headingDegrees = heading * 180/M_PI;
  //Convert float to int
  int angle=(int)headingDegrees;
  //////////////////////////////////////////////////////////////////////////

  display.clearDisplay(); // Just in case...

  //if flag is equal with 0 - 1st Display Mode
  if (flag==0){
  DrawRow(angle); //call DrawRow function
  display.drawBitmap(40, 24,  arrow_bmp, 5, 5, 1);
  display.drawLine(42, 0, 42, 24, BLACK);
  display.setCursor(32,34);
  display.print(angle);
  display.setTextSize(1);
  display.print("o");
  display.display();
  delay(500); //print new value every 0.5sec
  }

  //if flag is equal with 1 - 2nd Display Mode
  if (flag==1){
  // Calculation of compass needle on lcd pointing to the direction
  DrawCircle(angle); //call DrawCircle function
  // Display actual heading
  display.setTextSize(2);
  display.setTextColor(BLACK);
  display.setCursor(0,0);
  display.println(angle);

  display.setTextSize(1);
  display.setTextColor(BLACK);
  display.setCursor(x0-2,0);
  display.println("N");

  display.setTextSize(1);
  display.setTextColor(BLACK);
  display.setCursor((x0+r)-5,y0-3);
  display.println("E");

  display.setTextSize(1);
  display.setTextColor(BLACK);
  display.setCursor(x0-2,y0+r-8);
  display.println("S");

  display.setTextSize(1);
  display.setTextColor(BLACK);
  display.setCursor((x0-r)+5,y0-3);
  display.println("W");

  // Triangle for direction
  display.drawTriangle(0, 46, 20, 46, 10, 18, BLACK);
  display.fillTriangle (0, 46, 20, 46, 10, 18, BLACK);
  display.display();
  delay(500); //print new value every 0.5sec
  }
}/// end of program

////////////      Functions    ////////////

//Draw rows and print letters to display - 1st Display Mode
void DrawRow(int angle) {

  display.drawLine(0, 0, 84, 0, BLACK);
  display.drawLine(0, 1, 84, 1, BLACK);

  display.drawLine(0, 22, 91, 22, BLACK);
  display.drawLine(0, 23, 95, 23, BLACK);

  display.setTextSize(2);
  display.setTextColor(BLACK);

  int start = 42 - angle / 3 ;
  if (start > 120) start += -120 ;

  int x = 0 ;
  int y = 18 ;
  for (int i=0; i<4; i++) {
      x = start + (i*30) -1;
      if (x>119) x += -120;
      display.drawPixel(x+1, y-2, 1);
      display.drawPixel(x, y, 1);
      display.drawPixel(x+1, y, 1);
      display.drawPixel(x+2, y, 1);
      display.drawPixel(x, y-1, 1);
      display.drawPixel(x+1, y-1, 1);
      display.drawPixel(x+2, y-1, 1);
      display.setCursor((x-4),(y-16));
      display.write(Leters[i]);
   }
  for (int i=0; i<24; i++) {
      x = start + (i*5) -1;
      if (x>119) x += -120;
      display.drawPixel(x+1, y+1, 1);
      display.drawPixel(x, y+2, 1);
      display.drawPixel(x+1, y+2, 1);
      display.drawPixel(x+2, y+2, 1);
      display.drawPixel(x, y+3, 1);
      display.drawPixel(x+1, y+3, 1);
      display.drawPixel(x+2, y+3, 1);
   };

  for (int i=0; i<8; i++) {
      x = start + (i*15)-1;
      if (x>119) x += -120;
      display.drawPixel(x+1, y-1, 1);

      display.drawPixel(x, y, 1);
      display.drawPixel(x+1, y, 1);
      display.drawPixel(x+2, y, 1);
      display.drawPixel(x, y+1, 1);
      display.drawPixel(x+1, y+1, 1);
      display.drawPixel(x+2, y+1, 1);

   };
}

////Draw circle and print letters to display - 1st Display Mode
void DrawCircle(int angle) {
  if (angle >= 0 && angle <=45) {    // 0-45 degrees
    int angle = angle/2;
    display.drawLine(x0, y0, x0+angle, y0-r, BLACK);
  }
  else if (angle >45 && angle <=90) {// 46-90 degrees
    int angle = (angle-44)/2 ;
    display.drawLine(x0, y0, x0+r, (y0-r)+angle, BLACK);
  }
  else if (angle >90 && angle <=135) {// 91-135 degrees
    int angle = (angle-90)/2;
    display.drawLine(x0, y0, x0+r, y0+angle, BLACK);
  }
  else if (angle >135 && angle <=180){// 136-180 degrees
    int angle = (angle-134)/2;
    display.drawLine(x0, y0, (x0+r)-angle, y0+r, BLACK);
  }
  else if (angle >180 && angle <=225){// 181-225 degrees
    int angle = (angle-178)/2;
    display.drawLine(x0, y0, x0-angle, y0+r, BLACK);
  }
  else if (angle >225 && angle <=270){// 226-270 degrees
    int angle = (angle-222)/2;
    display.drawLine(x0, y0, x0-r, (y0+r)-angle, BLACK);
  }
  else if (angle >270 && angle <=315){// 271-315 degrees
    int angle = (angle-270)/2;
    display.drawLine(x0, y0, x0-r, y0-angle, BLACK);
  }
  else if (angle >315 && angle <=360){// 316-360 degrees
    int angle = (angle-312)/2;
    display.drawLine(x0, y0, (x0-r)+angle, y0-r, BLACK);
  }
}

it doesn't even clear after 6 seconds?

Please give links to the modules of the display and the magnetometer that you use. How are they connected? Do you use extra resistors or extra level shifters? You could send messages to the serial port, to know what is going on.

And start debug, by adding Serial.Print in the loop you can verify if it is running or not. There is also a more comprehensive library available for debugging, https://playground.arduino.cc/Code/SerialDebugger

no,it does not clear after 6 seconds.I tried with same pin connection the lcd nokkia 5510 the scetch of Adafruit_PCD8544 library sketch pcdtest and lcd works fine.I also put in if{} and code  display.print("  something  "); to see if code execute and enter in loop,but nothing.I now try serial print to see what happen (like MatsK said).Is first time happens someting like it to me.Thank you very much  all for your help.

lcd screen 51110 is this https://www.aliexpress.com/item/High-Quality-8448-84x84-LCD-Module-blue-backlight-adapter-PCB-for-Nokia-5110-for-Arduino/32614334972.html?spm=a2g0s.12269583.0.0.313e7cdfn3UXYH

As you have a lot of test in the loop; I'll suggest first to add a "Serial.println("here"); at the beginning of the loop in order to see if yo enter the loop. Then, print some message in each "if/else" to see what's happening.

i edit code and add serial print.Now serial is  printing when button A or B  is pressed,flag when change 0 or 1,i  when change 0 or 1(all this execute in the loop!),but does not lcd print nothing,only freeze in first message of set up-->ARDUMOTIVE
ArduinoBased
compassn.Compass
Michalis Vas.   i believe,but i can not find,that maybe sensor is faulty and code allow display to show data of digital compass,ONLY when sensor send data!!!but i can not find this in code to overide,if is exist;Any help;

thank you very much all.I delete code of the compass sensor,overided it,and now lcd show graphics of digital compass,but no data.The sensor do not working.thank you very much all for you value help.I will buy another sensor module compass.

You might run into the same problem with a new sensor. The 5110 is sold as 3.3 to 5v, but it is not for 5v, only for 3.3v. We would like to know if you use a resistor for the backlight. Do you use a breadboard? Some breadboards have bad contacts. Sparkfun has a guide for the 5110 connected to a 5v arduino board: https://learn.sparkfun.com/tutorials/graphic-lcd-hookup-guide/all The HMC5883L magnetometer is a 3.3v chip. We do not know which module you have and how you have connected a 5v arduino board to a 3.3v sensor.


text:
Will a simple RC filter work with my mechanical rotary encoder, or do I need a Schmitt trigger?
I bought some incremental rotary encoders online  https://www.bourns.com/docs/Product-Datasheets/PEC12R.pdf
The spec sheet for those suggests a filter circuit for the outputs of the encoder that looks like this:

Adding that filter reduces, but doesn't eliminate, spurious signals from the encoder. I wanted to avoid adding Schmitt triggers or other solid state components since I don't have a lot of room left on my proto board for an IC, but I'm beginning to think I will have to add something with hysteresis since any filter that reduces jitter will also slow the rise time/fall time for the output of the encoder and keep it in the "gray area" between LOW and HIGH for a digital signal for too long.
Is there a way to wire these encoders and/or software that lets you read from them with simple passive filtering and/or software rather than adding something like a latch or Schmitt trigger for debouncing?

How fast are you turning the encoder? Are you measuring the speed of a motor? Using it for human/user input?

Look at the datasheet. These are manually turned encoders.

Duplicate of question here  https://electronics.stackexchange.com/questions/423688/how-do-you-pick-component-values-for-a-debouncing-filter/423695?noredirect=1#comment1052330_423695

@CrossRoads, is it bad form to ask related questions on different Stack Exchange sites? My question on the electronics SE site started out asking about picking component values, and then evolved into a more general question about debouncing. This thread is specifically about how to debounce my rotary encode for use with an Arduino.

Have you tried this library https://github.com/buxtronix/arduino/tree/master/libraries/Rotary with the interrupt.ino https://github.com/buxtronix/arduino/blob/master/libraries/Rotary/examples/interrupt/interrupt.ino sketch?

I've seen circuits where they added a diode, so the capacitor charges/discharges instantaneously, but get's RC-filtered in the other directions. In you'r case your interrupts triggers on a falling edge, so you connect the diode via the switch to ground, and have the pull-up resistor "slowly" charge the capacitor back up, when the switch is open. Not sure if this is really "better".

which problem are you having, too fast (jitter) or too slow (missing clicks)? GPIOs don't usually flip on a dime, and you can adjust the rc values to adjust the edge times if needed.

"which problem are you having, too fast (jitter) or too slow (missing clicks)". Seems to be jitter, but it's a bit hard to tell. Jitter will happen even if the signal is debounced, if the slope of the high/low and low/high transitions is too gradual and spends too much time in the "forbidden zone" of in-between voltages. (I think that's what is happening.)

I just added a Schmitt trigger to my circuit in addition to the RC filter shown in my question (an MC14584BCP). That seems to remove the jitter, but it seems to still under or over-count occasionally. (Using an ISR that reads the pins using port registers, so it should be plenty fast.)

See my self-answer and the edit to it. IT should be possible to do the debouncing in software, and the code is very close but not quite there.

Having just chased a problem using a software based debounce for several days, what I'll add is that for the encoders I was using (green no-name Chinese ones), if you put 10mA though the contacts then the signal is a LOT better.   So change the 10k to 470 Ohms.
Or if using 3.3V use 330 Ohms.  Solved all my problems.

The answer seems to be no. I added the RC filter suggested by the manufacturer and the results still jump around (The values sometimes increase by several steps at once, or decrease even when turning the decoder clockwise.)
I added a CMOS Schmitt trigger and it resolves the problem.
I really don't understand why that is, since apparently Arduino digital inputs have integrated Schmitt triggers. This thread from the Arduino forum discusses it at length:
http://forum.arduino.cc/index.php?topic=452599.15
The only thing I can think of is that the hysteresis band of the built-in Schmitt triggers is too narrow (2.08 - 2.63V at VCC of 5V and typical operating conditions) and the filtered voltage still bounces between those values.
I'm using a MC14584B Schmitt trigger that I had lying around, and it looks like it's hysteresis band is ≈2.1V to 2.7V (typical at 25°C) which is slightly wider and goes slightly higher than the hysteresis range of the Arduino itself.
The differences seem quite small though, so I'm confused as to why the Schmitt trigger eliminates the "bobbling" of values I'm seeing.
I could add delay based debouncing code to my Arduino program, but the decoder handler is written as an ISR and those are supposed to be as fast as possible, and the millis() function is supposed to be quite slow, making it difficult.
EDIT:
I asked a related question regarding filter component values on the EE stack exchange, and somebody there pointed out that I should only be seeing "bounce" on one pin at a time, and that I should be able to reject spurious changes purely through software. I'm trying to do that now.
My new code looks like this:
bool rotaryValueChanged = false;

bool pinAHasChanged = false;
bool pinBHasChanged = false;

enum ChangeTypes {
  fallingA,
  changingA,
  changingAOrB
  };
ChangeTypes changesToDetect = fallingA;

void encode() {
  pinAHasChanged = true;
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  //Fast equivalent to pinAState = digitalRead(rotaryPinA) == LOW
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;
  //Ignore state changes to pinA unless pinB has changed since the last change.
  //Also only pay attention if this is a falling edge
  //or we're tracking both rising and falling edge changes
  if (pinBHasChanged && (pinAState == false || changesToDetect != fallingA)) {
    rotaryValue +=  (pinAState == pinBState) ? -1 : 1;
    rotaryValueChanged = true;
    pinBHasChanged = false;
  }
}

void encodePinB() {
  pinBHasChanged = true;

  //Unless we're counting 48 ticks/rotation, don't count PinB changes.
  if (changesToDetect != changingAOrB) {
    return;
  }
  //Read the PinA & PinB (Digital Pins 2 & 3) using port register PINE, 4th and 5th bit
  bool pinAState = (PINE & (1 << 4)) == 0;
  bool pinBState = (PINE & (1 << 5)) == 0;

  //Ignore state changes to pinB unless pinA has changed since the last change
  if (pinAHasChanged) {
    rotaryValue +=  (pinAState != pinBState) ? -1 : 1;
    rotaryValueChanged = true;
  }
}

void setup() {
  attachInterrupt(digitalPinToInterrupt(rotaryPinA), encode, CHANGE);//FALLING
  attachInterrupt(digitalPinToInterrupt(rotaryPinB), encodePinB, CHANGE);
  //More setup code here...
}

This code is written to handle 3 possible options:

Only falling edge state changes on pin A (12 steps/rotation)
Rising or falling changes on pin A (24 steps/rotation)
Rising or falling state changes on either pin (48 steps/rotation.)

The key part of this is to have interrupts on both pins. When one pin changes, its interrupt handler sets a "this pin changed" bool to true. In the ISR (Interrupt Service Routine) for the other pin, it only pays attention to a state change if the other pin has changed. That way, when Pin A changes states, if it bounces, the other pin should not bounce at the same time and so unless pin B has changed, I can simply ignore additional changes to Pin A and handle my debouncing in software, and without having to do timing delays which are too slow for an ISR.
However, the code above doesn't quite work. Sometimes I get bogus reverse rotation readings. If I'm rotating the encoder clockwise, the values I get increase one by one as expected, but occasionally decrement by 1 and then go back to incrementing.
What am I doing wrong?
Since the bouncing should only ever occur on one pin at a time, the above code should give correct readings from a bare rotary encoder without any hardware debouncing needed, but it doesn't.
My test case is only counting falling edge transitions for Pin A of my encoder, so picking up spurious counterclockwise rotation readings suggests that sometimes Pin B is changing state at the same time as pin B. That shouldn't happen, so I'm confused.

Have a look at MC14490 hardware debouncer.

First of all, I would question the usefulness of debouncing a rotary
encoder. I would expect to have contact bounce only when the contact is
transitioning from HIGH to LOW or vice-versa. At this transition
point, both the HIGH and LOW readings are in a sense correct. A
non-debounced reading should then display a rotary angle that briefly
changes back and forth between two consecutive positions, with no
cumulative error.
I would suggest you forget about debouncing and just look at the state
changes. If you think you do need debouncing, handle it downstream, by
periodically querying the “raw” angle and updating the “debounced”
angle:

if the raw angle is more than one unit apart from the debounced angle,
bring this difference back to one unit.
if the raw angle has not changed since a fixed count of milliseconds,
then make the debounced angle equal to the raw angle.

Second point: you are not looking at the falling edged of input A, you
are looking at the rising edges. This is because pinAState
uses negative logic: it is true when the pin is LOW. It shouldn't
make a big difference though in terms of the logic of the code.
Third point: there is some flaw in your counting logic. I will not try
to analyze it in detail, as the whole debouncing concept you use does
not make sense to me, but only provide an example of how it can fail.
Let's assume the encoder is in the position where both inputs are LOW,
and you wiggle it a little bit so that each input, in turn, gives a
positive pulse, like this:
                _       _       _       _       _       _
input A      __/ \_____/ \_____/ \_____/ \_____/ \_____/ \_____
                    _       _       _       _       _       _
input B      ______/ \_____/ \_____/ \_____/ \_____/ \_____/ \_

rotaryValue      0     |   1   |   2   |   3   |   4   |   5

Here, rotaryValue is incremented on each rising edge of input A, save
for the very first one. In this case, the expected behavior is for this
variable to stay, say, within [−1, +1].

source: Stack Exchange

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

sort: votes


text:
Is it possible to connect miband2 and arduino nano (?)
I want to make an IOT project using an Arduino nano and I need heart rate sensors. I I have a miband2. So, is it possible to connect them ?

First find out what communication protocol the miband2 uses.

Mi band use BLE

You need to connect as a central device.
I've had good luck with the adafruit nrf52 feather.  Also see: https://github.com/Freeyourgadget/Gadgetbridge for the protocol.

To use BLE on Arduino, I tried google and found this Article:
Examples:

HM-10 (HM-11) BLE Module
BLE Nano
BLE Mini
BLE Shield v2.1
RFduino
Bluno series
BLE WT51822-ABS
Grove – BLE
BLEduino

Chose one that fits best, and use it.

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


text:
HC-05 bluetooth module
I was able to connect my HC-05, pair it with my phone, and I can see data in the Serial Bluetooth Terminal Android App.  But when I try to connect it to a certain application it says it cannot find it.  Can the application force a certain version of Bluetooth?  Am I missing something?  Thanks.

What to you mean by a "certain application"? Does the app (Android side) say it can't see the HC? Does the HC say it can't send data? More details please :)

The HC-05 modules use bluetooth 2.0. Certain apps would only be compatible with bluetooth 4.0 devices (BLE - Bluetooth Low Energy), such as an HM10 or AT09.
It could be that your app requires the device to use v4.0+. Are you able to find, and pair with the device using your android's default bluetooth device scanning/pairing features?
Assuming that your app does not require v4.0+, have you removed the connection from 'en'/'ch_pd' to 3.3v? If that was still connected (which is a required connection to enter AT command mode), then your bt module would not be able to accept incoming pair requests etc.
hope this has helped. :)

Thank you for your reply.  I think the app may be 4.0.  My understanding is the app is supposed to automatically connect.  You are not to manually pair it.  I can connect to it through my Android Bluetooth settings and also through the Bluetooth Terminal app.  So if the app requires 4.0 would which module would you recommend?  Thanks again.

HM10 would be my recommendation, but there are loads of what look like AT09 (also v4.0) claiming to be HM10's on ebay/amazon. I havent had issues with my AT09 (as of yet, not done much with it, and i ordered more hc05's as the antenna on the AT09 seemed very thin)
I'm sure there are android apps that allow you to scan for bluetooth devices using either 'classic' or v4+. haven't tried any of those out myself though.

Thank you.  I will get an HM10 and try it.


text:
Converting code for ATTINY85 to ATMEGA2560. Pin change interupts
I have code that compiles correctly for an ATTINY85 board using the ARDUINO IDE but I don't have an ATTINY85 board. I have an Arduino Mega ATMEGA2560 and when I select this board in the Arduino IDE the code does not compile and throws this error message
sketch_feb21a:216:3: error: 'GIMSK' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

   ^

sketch_feb21a:216:16: error: 'PCIE' was not declared in this scope

   GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts

                ^

sketch_feb21a:217:3: error: 'PCMSK' was not declared in this scope

   PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin

   ^

exit status 1
'GIMSK' was not declared in this scope

Here is the code snippet that throws the error
void sleep()
{
  GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT2);                   // Use PB3 as interrupt pin
  ADCSRA &= ~_BV(ADEN);                   // ADC off
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement

  MCUCR &= ~_BV(ISC01);
  MCUCR &= ~_BV(ISC00);       // Interrupt on rising edge
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sei();                                  // Enable interrupts
  sleep_cpu();                            // sleep

  cli();                                  // Disable interrupts
  PCMSK &= ~_BV(PCINT2);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit
  ADCSRA |= _BV(ADEN);                    // ADC on

  sei();                                  // Enable interrupts
}

ISR(PCINT0_vect) {
   /*noInterrupts();
   while (digitalRead(BUTTON_PIN) == LOW);

   delay(50);
   while (digitalRead(BUTTON_PIN) == LOW);
   playTrack(1 + (curTrack++ % 2));
   delay(400);

   interrupts();*/

}

Do you have a arduino atmega 2560 board? why do you want to put that into sleep mode?

Each processor has different registers, things that control stuff like interrupts, input and output. I would not expect code written for one processor, especially if it directly accesses the registers, to work on another processor.
You would need to look at the datasheet for the Atmega2560 and see how to control its pin change interrupts.

I have been looking at datasheets for both but I am just having trouble understanding what to change in order to make it work correctly.


text:
Using an external pull-up resistor vs INPUT_PULLUP
When would one would prefer to use an external pull-up resistor vs the internal:
pinMode(fanPin, INPUT_PULLUP);

Dredging through the forums and this site, the commonly recommended value for a pull-up resistor is seems to fall at 10K.
However, the ATmega32U4 datasheet's Table 29-1 says that RPU or "I/O Pin Pull-up Resistor" is between 20K and 50K ohms.
This question asks about internal vs external pull-ups for a simple button, but I'm asking in the general case.
What types of projects would fare better with internal pull-ups, and what type of projects would be better off with external pull-ups?
What are the considerations for preferring one over the other?
At the present, my project is hooking up an AM2302 / DHT22 temperature sensor.

Whats OUTPUT_PULLUP? Pulling an output high doesn't make a lot of sense.

I2C requires lower value pull-up resistors, so in that case you'd need external resistors. High noise environments could accidentally trigger an input if the pull-up is weak. But in most cases the internal pull-up is fine. And it's cheaper to not add a resistor, especially in very high volume manufacturing.

During manufacturing they sometimes change the value of the pull-up to a value resistor that is already on the board. Reducing the setup cost.

the internals are fine for most things, unless you have semi-low impedance on the sensor's output. Impedance is more than resistance.

@tkausl Thanks for pointing out that OUTPUT_PULLUP doesn't exist. Edited.

There is no OUTPUT_PULLUP that I am aware of. Use INPUT_PULLUP for most things.
Add 3.3K (3.3V) or 4.7K (5V) external pullups for I2C. If you saw a 'scope trace with 10K I2C pullup on 5V system and even short wiring, the rise time is really slow. 4.7K is much quicker.
10K for external pullup works well for slow things, like buttons, switches.  If the wire lengths are longer, then 4.7K could be used as well, maybe even 1K if the wires are long.  If running on battery power, 10K is better as there is less current flow when the input is low.

I almost always use external pull up/down resistors. I get more control over the value and can do more in hardware with them, whether that is debouncing buttons or using different types of transistors.
The easiest way to answer your question is to ask what you want to do. If you want active low, use pull up. Active high is pull down. Some transistors work much better with one or the other, so they could determine what you use. I2C uses weak pull ups to bias the transmission lines. If you need hardware filtering its much easier to design a filter with a known 25k resistor than with an unknown 20k-50k resistor. The list could go on an on but those are the most common situations I've run into.


text:
How to operate a brushless motor & ESC with an Arduino
I have recently bought two brushless motors (Brushless-300w-6-5-Wheel-Tyre-Motor-Hoverboard-Swegway-Board-Replacement-Part) along with two ESC (https://hobbyking.com/en_us/hobbyking-40a-esc-4a-ubec.html).
I have connected the hardware accordingly (photo attached, the potentiometer throttle included is not included in the photo).
And I try run the following code:
#include <Servo.h> //Using servo library to control ESC

Servo esc; //Creating a servo class with name as esc

void setup()

{

esc.attach(10); //Specify the esc signal pin,Here as D10

esc.writeMicroseconds(2000); //initialize the signal to 1000

delay(1000);

esc.writeMicroseconds(1000); //initialize the signal to 1000

delay(1000);

//Serial.begin(9600);

}

void loop()

{

int val; //Creating a variable val

val= analogRead(A0); //Read input from analog pin a0 and store in val

val= map(val, 0, 1023,1000,2000); //mapping val to minimum and maximum(Change if needed)
esc.writeMicroseconds(val); //using val as the signal to esc
}

The motors seem to vibrate and turn only when the potentiometer is at a specific point, and are then inert for all the subsequent positions.
Does anyone have any advice on how to overcome this issue?
Thanks!]1

I don't know how to control an ESC via the arduino, but I did just find this link which seems to have a fair amount of information, such as calibrating the ESC.
https://dronesandrovs.wordpress.com/2012/11/24/how-to-control-a-brushless-motor-esc-with-arduino/

It may or may not help if you read the troubleshooting part of the ESC manual:
https://cdn-global-hk.hobbyking.com/media/file/378561453X16958X28.pdf

If the photo and code attached are correct, you connected the ESC to physical pin 53 (I believe, photo is blurry), but when calling esc.attach() you are using pin 10. If this is the case and a mistake has been made, please either connect the esc to pin 10 or change the code to say esc.attach(53).

Your code immediately sets the ESC to high upon startup. Most ESCs have protection, and if the initial signal is high, they lockout until you go all the way back to low. You may not have low calibrated though, so it might not ever let you control it. Calibrate by (remove initial high-low code first) setting the pot to high (with the ESC disconnected from power), then powerup the ESC.  You should hear a bunch of beeps, and when it stops, slowly turn the knob all the way to low, and you should be met with some more beeps. Disconnect power, reconnect, and try control (starting with a LOW signal)


text:
Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?
I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.
To make the project neater I wanted to fit an on/off rocker switch to the project box making it look better and providing a more substantial switch. Mostly the on/off rocker switches come in 3 pin or 2 pin connections though. Is it possible for me to join it the 6 pin combining some of the pins in some way or not? I can also pick up another battery shield which has a 3 pin switch, again could I combine that with a 2pin if required or do I need to use a 3 pin rocker with it?
Some pictures of what i'm (or could be) using

(Current power bank, on/off switch on the right side in the middle, 6 pins)

Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)

Two pin rocker switch

Three pin, two way rocker switch

Looks like only 2 of the 6 pins are used. It's a simple on-off. The switch itself is a "Double Pole Double Throw", but the two poles are tied together to make it single pole (like a 3 pin switch), and one throw is ignored, making it 2-pin.
You can see on the underside of your board which pins are tied together with traces. Bridge those pin pairs to turn the board on.

Thanks Majenko, so basically the two pin rocker switch will work fine, just connect the middle pin to the two pins in the middle and the other pin to the two pins on the "on" side?

That is correct.

using a double pole switch creates built-in redundancy .... if one contact fails, then the switch will still operate normally

@jsotola The redundancy is generally an added bonus. Most people use a double pole switch when it's in that style because they are far more common, and hence cheaper.


text:
How to use an Arduino as an emulator to filter signals?

What should be the Arduino code to emulate it as a 3rd order IIR filter?

the picture is the simulink model

Do I smell homework? What did you try? What problem you had?

The Arduino code would be whatever the C code would be. I'm sure you can find some C code examples online...

that is a badly drawn diagram ..... there is no reason why any of the lines should cross

The Wikipedia page Digital filter shows how to derive the difference equation from the transfer function H(z), and how to practically implement it.


text:
Not able to find right library for MPU9250
I am using an Arduino Uno and learning to use the motion sensor. Currently I was not able to find the library which looks simple and would like to get your suggestion. I found this https://github.com/hideakitai/MPU9250 library to be simple but don't know how to use it.
For example, take this code:-
#include "MPU9250.h"

MPU9250 mpu;

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

    Wire.begin();

    delay(2000);
    mpu.setup();
}

void loop()
{
    static uint32_t prev_ms = millis();
    if ((millis() - prev_ms) > 16)
    {
        mpu.update();
        mpu.print();

        Serial.print("roll  (x-forward (north)) : ");
        Serial.println(mpu.getRoll());
        Serial.print("pitch (y-right (east))    : ");
        Serial.println(mpu.getPitch());
        Serial.print("yaw   (z-down (down))     : ");
        Serial.println(mpu.getYaw());

        prev_ms = millis();
    }
}

Some values are not defined here, like registration code and input pins. I am not used to reading the documentation code so might need help in that.

I didn't understand the docs

thanks for updating your post ..... you are asking the wrong question ..... you do not have a problem with the MPU9250 library ..... your problem is with I2C communication ..... https://www.arduino.cc/en/Reference/Wire

What is the problem here, are you getting any values? Yes, then good. Finding a simple solutions to complex problems isn't always a given. If it works, stick with it. If it doesn't work then show us the schematics? I would rely on this example since it's hiding all the logic. Until it's dis-proven.  You can build a schematic here to show us. (https://www.tinkercad.com/circuits). The code should work, but i dont see any code for wiring.

In the Arduino IDE, click on SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES.

Then, search for 9250, select the SparkFun one, and click INSTALL.

Finally, from the examples, choose the MPU9250BasicAHRS_I2C.


text:
What is mean of 700,150 number?
 if ((leftsensor >= 700) && (rightsensor >= 700))
   forward();
       else if((leftsensor <= 150) && (rightsensor <= 150))
   backward();
   else if((leftsensor <= 150) && (rightsensor >= 700))
   turnright();
   else if((leftsensor >= 700) && (rightsensor <= 150))
   turnleft();

The mean of 700 and 150 is 425. Or are you asking what they represent? They are some arbitrary threshold value that some sensor reading is being compared against.

A analogRead() value is between 0 and 1023. By looking at only that code we can only see that 700 and 150 are thresholds for steering a vehicle; a line-following robot?

As mentioned the mean of 700 and 150 is 425. What does this have to do with your code? Please be more clear about your scenario

those are you "shoulder" readings, while values between them are basically "dead space" (in joystick terms)

I have somewhat large experience in understanding people that use "bad" english as their secondary language. That's why I assume that even though the question you asked was "What is mean of 700,150 number?" the question you wanted to ask is "What is meaning of numbers 700,150 in code below?"
This was already answered by @MaximilianGerhardt in the comments.
If we assume that leftsensoris an integer value coming from analogRead then it's possible values are between 0 and 1023. The programmed created two arbitrary thresholds of values 700 and 150. Those values were probably calculated experimentally to negate signal noise, sensor imperfections and interference.


text:
RF Rx with NodeMCU error
I am using RF Tx with Arduino Uno and Rx with NodeMCU. I use RF switch library. At the recipient side if I use an Arduino Uno MCU. I can receive the output, but with NodeMCU I have a blank serial monitor; no output is shown. RF.enable (0) is used in my code and pin D2 is connected to data of RF module.
Some one help me please.

why not RF.enable(D2)?

The RF.enable(0) is the actual code line given in the example section .. will try what you have suggested.

Pin D2 is GPIO4 ... does the (0) specify the GPIO pin the RF module is connected to - if so, that's the problem ... either use (4) or (D2)


text:
invalid pure specifier (only '= 0' is allowed) before 'int'
#include <PixySPI_SS.h>
#include <Pixy.h>
#include <Adafruit_MotorShield.h>
#define X_CENTER        ((PIXY_MAX_X-PIXY_MIN_X)/2)
#define Y_CENTER        ((PIXY_MAX_Y-PIXY_MIN_Y)/2)

Pixy pixy;
 int TrackedBlock(int n) =
{
 int trackedBlock=0;
 float maxSize=0;
  for (int k=0;k<n;k++)
  {
    float newSize= pixy.blocks[k].height * pixy.blocks[k].width;
    if (newSize>maxSize)
    {
      maxSize=newSize;
      trackedBlock=k;
    }

  }
   return trackedBlock
}

For some reason the code returns the error message in the title every time I try to compile it. I can't really find any issues online that's the same as my error. Any help is appreciated!

What happens if you remove the "=" from this "int TrackedBlock(int n) = " and add a ";" at the end of this "return trackedBlock"?

yeah, because int TrackedBlock(int n) =  is not how you write a function in C

Look, this isn't a forum. Please post your answer using the "answer" box. Then it can be accepted. The only answer here right now is a "thanks" for your comment. This is totally subverting how Stack Exchange is supposed to work.


text:
Problems compiling with enum value PORT1-7
So I have this enum in a header file:
enum class ServoPort {PORT1 = 1, PORT2, PORT3, PORT4, PORT5, PORT6};

The trouble is that when I try to use it in the primary file (by doing MyClass::ServoPort::PORT1) I get a compile error:
exit status 1
expected unqualified-id before numeric constant

However, if I change the enum to be like so:
enum class ServoPort {PORT8 = 1, PORT9, PORT10, PORT11, PORT12, PORT13};

Then I do not get a compile error. What the heck? Can someone please shine some light on why this is happening?

Board: UNO R3
IDE: v1.8.5

Please add which Arduino board and IDE version.

If you are using an AVR based Arduino board it might be a conflict with the AVR header file pinsport.h.

@MikaelPatel done

Please see the file: arduino-xxx/hardware/tools/avr/avr/include/avr/portpins.h. If you really want to use these symbols you could undef them in your header file.

@MikaelPatel hmm, ok yeah I could see that being a problem if I was trying to do a #define PORT2 or something, but in this case I'm creating an enum that has a a member of that name. It seems to me that shouldn't cause a conflict? I'm from a Java background so maybe I don't know what I'm talking about...

The defines are pre-processed symbols before compiling. Your definition gives an illegal syntax when replaced. PORT1 = 1, PORT2, becomes, 1 = 1, 2.

@MikaelPatel I see, but shouldn't the preprocessor be smart enough to not do that?

Some reading: https://softwareengineering.stackexchange.com/questions/309389/what-is-the-origin-of-the-c-preprocessor, https://en.wikipedia.org/wiki/C_preprocessor, https://gcc.gnu.org/onlinedocs/cpp.pdf

Should add that #define, #undef, #include, etc, are not part of C/C++. It is the tools cpp, c pre-processor, that handles them before handling the resulting file to the compiler, cc/gcc.


text:
Code causing Servo motor not to work!
My sketch is compiling and loading, but when the program runs, the Servo motor does not work. The buttons work, the LED light works, Piezo buzzer plays the melody, the Stepper motor works but not consistently. The Servo/Stepper motors and LED worked until I introduced the code for the Piezo buzzer to play a melody. I'm new to programming and want to learn from others in a constructive way. I hope this forum is a place where people at all levels of knowledge and experience want to lend a helping hand. Here is my sketch:
#include <Stepper.h>
#include <Servo.h>

/*ARDUINO MOTOR SHIELD
 * The pin breakdown is as follows:
 * Function          Channel A   Channel B
 * Direction         Digital 12  Digital 13
 * Speed (PWM)       Digital 3   Digital 11
 * Brake             Digital 9   Digital 8
 * Current Sensing   Analog 0  Analog 1
 */

const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
const int dirChA = 12;     // assigning name "dirChA" to pin 12
const int dirChB = 13;     // assigning name "dirChB" to pin 13
const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
const int brkChA = 9;      // assigning name "brkChA" to pin 9
const int brkChB = 8;      // assigning name "brkChB" to pin 8

const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

const int pButton1 = 4;    // assigning name "pButton1" to pin 4
const int pButton2 = 5;    // assigning name "pButton2" to pin 5
const int pButton3 = 6;    // assigning name "pButton3" to pin 6
const int pButton4 = 7;    // assigning name "pButton4" to pin 7

const int ledLight = 2;    // assigning name "ledLight" to pin 2

Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
Servo myServo;  // initialize the servo library to logical name myServo

int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
int pButton4State = 0;     // variable for reading the pButton4 state as LOW or HIGH

int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

int myServoPos = 0;      // variable for when servo has reached it's position
int myServoFlag = 0;     // variable for servo when any of the 4 pButton are pressed

int tonePin = A3;        //variable for buzzer

void midi() {
    tone(tonePin, 233, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 412.325976562);
    delay(458.139973958);
    delay(4.82252604167);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 233, 555.555);
    delay(617.283333333);
    delay(77.1604166667);
    tone(tonePin, 233, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 412.325976562);
    delay(458.139973958);
    delay(4.82252604167);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 233, 555.555);
}

void setup() {
// Serial.begin(9600);   // initialize the serial port for messaging & troubleshooting

 // 1 Stepper Motor
 pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
 digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)

 pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
 digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)

 pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
 digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)

 pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
 digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)

 pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
 digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)

 pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
 digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)

 myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM

 // 4 Push Buttons
 pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
 digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)

 pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
 digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)

 pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
 digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)

 pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
 digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)

 // 1 Led Light
 pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
 digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
}

void loop() {
  //Read button state (pressed or not pressed?)
  pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
  pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
  pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
  pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

  // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
  if (pButton1State == HIGH) {
     pButtonFlag=1;  // change pButton1Flag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(40);          // step forward 40 steps to position 1
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        myServoFlag=1;             // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000); // hold position OPEN for 2 sec

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }

        myServoFlag=0;         // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
        midi();

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-40);          // step backward 40 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    // disable power to stepper

        digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
        delay(2000);
     }

  // position 2
  if (pButton2State == HIGH) {
     pButtonFlag=1;  // change pButtonFlag variable
  }
     if (pButtonFlag == 1){
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(80);          // step forward 80 steps to position 2
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
        delay(2000);

        myServoFlag=1;    // change ServoFlag variable to dispense chocolate

        if (myServoFlag == 1){
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 15 milliseconds for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
           delay(2000);

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
        }
        myServoFlag=0;                // changes myServoFlag value back to zero (0)
        digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
        midi();

        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-80);          // step backward 80 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper

        digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

        pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
        delay(2000);
    }

    // position 3
    if (pButton3State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(120);          // step forward 120 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;                // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
          midi();

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-120);         // step backward 120 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
     }
    // position 4
    if (pButton4State == HIGH) {
       pButtonFlag=1;   // change pButtonFlag variable
    }
       if (pButtonFlag == 1){
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(160);          // step forward 160 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate
          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

          if (myServoFlag == 1){
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
          }
          myServoFlag=0;   // changes myServoFlag value back to zero (0)
          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
          midi();

          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-160);         // step backward 160 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
          delay(2000);
       }
}

As expected, you want to control servo with pin 3,  but it’s been explained in other questions that ‘tone()’ interferes with PWM on pins 3 and 11. Servos are controlled by PWM signals.

I'm using a motor shield. I'm using Pin 10 to signal the Servo. Shouldn't that work? Pin 3 & 11 are being used by the Stepper

Code causing Servo motor not to work!   ..... disconnect the servo from the arduino ... i bet that it still will not be working .... it is not the code causing it not to work

@jsotola it's exactly the code causing it not to work

@RobertoLoGiacco, that is not true .... you do not require any code at all for the motor to be inoperative  ...... the code is not causing the motor to work is the correct statement ...... in other words, the code is not making the motor run

As already reported in the comments, the Tone library uses Timer2 an hardware module of the Atmega328P microcontroller, which is also in charge of generating the PWM signal on pins 3 and 11.
As pins 3 and 11 are both used by your code to pilot the servo motor, it should be of no surprise the motor starts to behave erratically once you added the code to play tones on the buzzer.
A solution would be not to use the PWM pins 3 and 11 as PWM (you can still use those, just not to generate PWM signals)
That is clearly reported in the docs:

 PWM frequencies are tied together in pairs of pins. If one in a pair is changed, the other is also changed to match:

Pins 5 and 6 are paired on timer0
Pins 9 and 10 are paired on timer1
Pins 3 and 11 are paired on timer2

And also:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).


text:
What functions are disabled with noInterrupts()?
The Arduino page for noInterrupts() says:

Some functions will not work while interrupts are disabled, and incoming communication may be ignored.

While it may not be possible to give a complete listing of what would be disabled, having an incomplete list of functions which definitely are disabled would be useful.
I was thinking of calling a DHT sensor library which internally uses millis() while interrupts were disabled to avoid both bit banging and servicing interrupts simultaneously if possible (the interrupt would hold and be processed after).
Which functions are definitely disabled when interrupts are disabled?
What about incoming communication? My guess is that it would be slightly worse on the ATmega32U4 (eg Leonardo) as the one processor does USB and everything else as well.

The following command grep ISR *.cpp will generate a list of all ISR functions in the Arduino core. These are the HardwareSerial (UART/USB: receive, transmitt) and Timer functions (millis, micros, tone).

From what I found turning off interrupts will definitely disable incrementing values of micros() and millis() This means that also every method that uses them like delay() will also not work correctly.
Of course manually attached interrupts using attachInterrupt() will also not work as intended.
According to comments by @Juraj Things that also will not work are Serial interrupts. Also libraries like Wire require interrupts for their logic.
EDIT: @EdgarBonet You are right, I removed incorrect info.

Serial receive is handled with interrupt for hardware Serials (including native USB) and software Serials

Wire library send and receive is implemented in an interrupt

The PWM you get from analogWrite() is not handled by interrupts: it's generated by the timers themselves.

SPI.transfer() also uses interrupts - but you can 'manually' wait them out to know when to proceed.  For example, I had a program where I needed to send out 45 bytes in 50uS (20KHz refresh rate). During testing, I kept seeing jitters in the datastream - about every 4uS if I recall. The micros() interrupt time. Turned off interrupts during the data burst and the jitter went away. So the command to send out a byte looked this, repeated 45 times (no for loop):
spdr = byte0; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
spdr = byte1; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
spdr = byte2; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
:
spdr = byte43; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;
spdr = byte44; nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;nop;

So the transfer needed 17 clocks with the SPI clock set to 8 MHz.
After the transfer I turned interrupts back on to wait for the next incoming signal edge to send out the next burst.


text:
Bit Bang I2C with port manipulation on AtTiny84: new pinout doesn't work
So I am trying to understand bit banging and port operations. I'm developing a breakout board with an ADXL343 IMU read by an AtTiny44 via i2c. I adapted this code from MIT's How To Make Almost Anything which I also explained a bit here in this thread. Like I mentioned there, I got it working with the MIT code, and now have a basic sketch that works for my original board, where I define the pins like this.
#define SCL_pin (1 << PB0)
#define SCL_pins PINB
#define SCL_port PORTB
#define SCL_direction DDRB
#define SDA_pin (1 << PB1)
#define SDA_pins PINB
#define SDA_port PORTB
#define SDA_direction DDRB

UNFORTUNATELY, I designed and fabricated a new board where the SCL and SDA pins are now PA3 and PA2 respectively. I tried to adjust the sketch by changing the defines to all be PORTA, DDRA, etc like this:
#define SCL_pin (1 << PA3)
#define SCL_pins PINA
#define SCL_port PORTA
#define SCL_direction DDRA
#define SDA_pin (1 << PA2)
#define SDA_pins PINA
#define SDA_port PORTA
#define SDA_direction DDRA

Problem is, the tiny44 ceases to read from the IMU with the new pinout. The input/output functions in the program look like this:
#define output(directions,pin) (directions |= pin) // set port direction for output
#define input(directions,pin) (directions &= (~pin)) // set port direction for input
#define clear(port,pin) (port &= (~pin)) // clear port pin
#define pin_test(pins,pin) (pins & pin) // test for port pin

The pi I am using is getting the initial values of data[], so I know it is communicating fine with the tiny44
I realize the pin mapping changes depending on the core I'm using. I don't think that impacts the way the SDA_pin and SCL_pin are defined, because defining them PB0 and PB1 worked... Plus I tried about every pin name possible.
I have also tried the Damellis and Drazzy cores, and neither is working for me.
I tried using a few BitBang libraries like SoftWire, but with no luck.
I have tried a few boards as well, so I don't think it's hardware related.
I don't know what else to try. Any help would be much appreciated! Thanks!!

You could try this variant https://github.com/mikaelpatel/Arduino-TWI and https://github.com/mikaelpatel/Arduino-GPIO.

Thanks Mikael! It looks like the TWI won't work on the Tiny44 because the microcontroller only has a USI(which allows TWI, but called differently)

There is a software, bitbang, version https://github.com/mikaelpatel/Arduino-TWI/blob/master/src/Software/TWI.h.

A USI version can be found in Cosa (another Arduino core), https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/USI/TWI.hh.

As you have changed the pins you will have to use bit-banging as the USI module is fixed to specific pins.

yeah my plan was to use bitbang between the tiny and the IMU, and then hardware TWI for max speed with connection to Rpi. The code I posted is for the ports/pins for the bit-bang part.


text:
How can big Arduino programs be analyzed easily?
I have an Arduino project code, but the problem is it has multiple functions and flow of control.
How could I convert this code into flowchart or control flow diagram?
Any software or online website?

Use doxygen and configure for full control and structure graphs.

Seems like you should be going the other way - create the flow chart first, then write the code to follow it.

Yes flow charts on function call level may be generated with doxygen (calls and callers). More details for instance here, https://romanegloo.wordpress.com/2012/03/29/generating-a-callgraph-by-using-doxygen-and-graphviz-13/

Another tool to quickly analyze code is Source Monitor. Allows a "statistic" approach to navigating the code. http://www.campwoodsw.com/sourcemonitor.html

With respect, how is this a question about Arduino?  The same question could be asked about almost any large program in C++.

Although there are programs who can automatically make some documentation (like doxygen), I haven't seen any software so far that can make USEFUL flowcharts or diagrams. The main reason is that such software does not know which are the important parts and which are not.
To do it manually:
Assuming your code contains multiple files, use an UML (Unified Modeling Language) application. Than if classes are used, you can easily port them to UML, otherwise assume each (.c) file is a 'class'.
By adding properties/fields and methods (functions) and drawing dependencies between the classes/files you get a good idea how everything works together.

this is not what he asked. he wants an automatically created flow chart

@Juraj ... true I will update my answer.


text:
Same output on displays with different I2C-addresses (AdaFruit library, ESP32)
I've got two displays hooked up to a ESP32 via I2C and I'm using the AdaFruit library. All handling display output is packed in a own library. As I was testing I only had one display set up and everything looked fine. Now, in my actual setup with two displays, I only get the output of the first display on both screens. The displays are running on the same I2C-bus, different addresses are set. I also ran a address/portscanner that confirmed the different addresses (0x3C and 0x3D).
I have used separate displays with the AdaFruit library in such a setup before, but only on an Arduino uno and without having code moved to own libraries. So I can't tell if the ESP32 or having multiple files is messing things up or I'm missing something.
Here are parts of code in the cpp-file I used to initialize the displays and some functions I call:
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#include <gfxfont.h>
#include <SPI.h>
#include "DisplayOut.h"
#include "Game.h"

    /* -------------esp32 Pin setup --------------------- */
    const byte displayData = 21;    // I2C SDA
    const byte displayClock = 23;   // I2C SCL
    /* --------------------------------------------------- */

// Define OLED
#define OLED_RESET displayData
Adafruit_SSD1306 display1(OLED_RESET);
Adafruit_SSD1306 display2(OLED_RESET);

/* some variables */

void DisplayOutClass::init()
{
    // Initialize each display with i2c-address

    display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);
    display1.setTextWrap(false);
    display2.setTextWrap(false);
}

void DisplayOutClass::scorePlayer1(int score1)
{
    display1.clearDisplay();

    if (gameMode == 2)
    {
        display1.clearDisplay();
        display1.setCursor(0, 0);
        display1.setTextSize(2);
        display1.setTextColor(WHITE);
        display1.print(playerName[player1]);
    }

    display1.setTextSize(4);
    display1.setTextColor(WHITE);
    display1.setCursor(getCenteredPosX(3, String(score1)), 24);
    display1.print(score1);
}

void DisplayOutClass::scorePlayer2(int score2)
{
    display2.clearDisplay();

    if (gameMode == 2)
    {
        display2.clearDisplay();
        display2.setCursor(0, 0);
        display2.setTextSize(2);
        display2.setTextColor(WHITE);
        display2.print(playerName[player2]);
    }

    display2.setTextSize(4);
    display2.setTextColor(WHITE);
    display2.setCursor(getCenteredPosX(3, String(score2)), 24);
    display2.print(score2);
}

/* some more Functions */

DisplayOutClass DisplayOut;

I didn't post the complete code or the header file, because it exceeds a few hundred lines. But this should show how the I2C-addresses are used. If necessary, I of course can post the rest of the code.
My next approach would be either trying the U8g2 library or trying start a second I2C bus. Since I already have a finished circuit board, so this would be my least preferred option.

Your reset pins are set to the number of the i2c address and you use the same reset pin for both displays? Did your read that you can make the reset pin -1 to not use it or share it with the arduino reset.

I agree with @Jot, reset pins must be separated: you are using the same pin (same define OLED_RESET), resulting reset the first display after initialized...

The displays each only have four pins: VCC, GND, SCL, SDA. So there is no reset pin. Setting OLED_RESET to -1 didn't work, neither did setting OLED_RESET to unused pins.

Adding false to the begin-methods display1.begin(SSD1306_SWITCHCAPVCC, 0x3C, false) and display2.begin(SSD1306_SWITCHCAPVCC, 0x3D, false) to disable reset didn't bring any progress either.

fwiw, i had to use a 2nd i2c line to get the esp32 to play nice. worked well and ended my frustration, but if there's a better way, I too am curious.

Try the new constructors (old ones are deprecated):
Wire.begin(21, 23); // SDA, SCL

Adafruit_SSD1306 display1(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);
Adafruit_SSD1306 display2(SSD1306_LCDWIDTH, SSD1306_LCDHEIGHT);

display1.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display2.begin(SSD1306_SWITCHCAPVCC, 0x3D);

Using this with "#define SSD1306_LCDWIDTH 128" and "#define SSD1306_LCDHEIGHT 64" just gives me errors and doesn't compile, although I overwritten the library with the one from the link to be sure to have the correct version.

Found the problem, was still using the constructor wrong. What dfid the trick was:
#define OLED_RESET -1
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display1(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
Adafruit_SSD1306 display2(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


text:
Issues with I2C and Wire.Available()
I am working on a project which requires communication from an Arduino Due (Master) and an FDC2214Q1 C to D IC (Slave), but there is some variability as to whether the code works or not depending on seemingly random variables.
I have narrowed the issue to the function I am using to read 2 bytes from the slave. The code is pretty standard, and is as follows:
// Read 2 byte from the FDC at 'address'
uint16_t FDC2214::read16FDC(uint16_t address) {

    uint16_t data;

    Wire.beginTransmission(_i2caddr);
    Wire.write(address);
    Wire.endTransmission(false); //restart
    Wire.requestFrom(_i2caddr, (uint8_t) 2);

    while (!Wire.available());
    data = Wire.read();
    data <<= 8;

    while (!Wire.available());
    data |= Wire.read();
    Wire.endTransmission(true); //end

    return data;
}

The code seems to get hung up sometimes on while (!Wire.available()) and if I simply remove that step, I never get the correct Device ID.
However, if I simply unplug the DUE and close the Serial Monitor and replug in and upload, it works. I just kind of upload and disconnect a few times and open and close the Serial Monitor and sometimes it works great, other times it gets hung up?
Any ideas what could be causing such and issue?
Code based on this library: https://github.com/zharijs/FDC2214/blob/master/src/FDC2214.cpp

Final code that has been working, removes need for While loop:
uint16_t FDC2214::read16FDC(uint16_t address) {

    uint16_t data;
        Wire.beginTransmission(_i2caddr); //queuing the slave address
        Wire.write(address); //queuing the register address/pointing regsiter
        byte busStatus = Wire.endTransmission(); //transmit all queued data and bring STOP condition on I2C Bus
        if(busStatus != 0x00)
        {
           Serial.print("Transmission Error....!");//transmissiion error wait here for ever
           while(1);
        }

        Wire.requestFrom(_i2caddr, (uint8_t) 2);     //this is looping code; when 2-byte has arrived, the loop terminates
        data = Wire.read();   //read the first byte from FIFO Buffer
        data = (data <<8)| Wire.read();   //16-bit data is formed
        Wire.endTransmission(true); //end
        return data;
}

how long are the wires? what value pullups are you using?

Currently do not have pull-ups as there is only one master/slave, but I realize maybe I should as a precaution. Will add some now, and let you know if that fixes anything. Thank you @dandavis

Hey @dandavis so I just added the pull-ups (1k) and it seemed they worked. But, sure enough, after a few sessions of opening and closing the Serial Monitor and unplugging/plugging the Arduino, I was able to reproduce the problem once again.

your code is not formatted properly ..... the two command lines after the while commands should not be indented ... the indentation implies that the two commands are inside the while loop .... they are not part of the while loop

@jsotola, this comment in no way helps me out, I understand how to format code, just thought it might be easier to emphasize the while loops I was referring to by tabing out the underlying code.

that is exactly what i am saying ... the tabbed code is NOT part of the while loop .... if you want to emphasize a section, then put in a blank line

Adafruit tells to avoid the Arduino Due. One of the reasons is the I2C bus. Can you use an other Arduino board? For example one of the MKR boards with a SAMD21 processor.
The Due has pullup resistors on the board for SDA and SCL which are too low in value. Sometimes the I2C bus with SDA and SCL works, but sometimes it does not work at all. Perhaps you are able to remove the pullup resistors at SDA and SCL from the board.
If possible use Wire1 with SDA1 and SCL1. Those have no pullup resistors at all, so you need to add 4k7 pullup resistors to 3.3V. When you use a library, you might have to change the library to use "Wire1" instead of "Wire".
You need to remove these, they are not doing something:
while (!Wire.available());    <- not doing something

Remove the Wire.endTransmission at the end.
Wire.endTransmission(true);   <- remove this
return data;

That library does not use the Wire library in a proper way.

The pullup resistors are 1k5 or sometimes 1k and are located in the upper-right corner, near pin 20 and 21. A value of 1k5 should be okay, when there are no other pullup resistors. When you board has 1k resistors, then I suggest to remove them.

Removing them is possible with a soldering iron and a big blob of solder. Check if the board is clean afterwards, for example with a magnifier. Avoid overheating your expensive Arduino Due board.
The I2C bus needs pullup resistors to work. A normal value is 4k7. Sometimes there are already 10k pullup resistors on a sensor module.
If the I2C has problems, start by using short seperate wires for SDA and SCL. When a cable is used for the I2C bus, then the cable is probably the problem and not the pullup resistors.

Thanks for the note, unfortunately I don't have any MKR boards, but I have some nanos that I can try out. I will swap to 4k7 pull ups as well, and remove the parts you have mentioned and give it a shot. I have read that the while(!Wire.available) is not necessary but figured it couldn't hurt (apparently it can). Will update either today or tomorrow the result of this! Thanks @Jot

Do not add extra 4k7 to SDA and SCL. There are already pullup resistors on the Due, which are too low in value. Adding 4k7 makes it worse. Only when using SDA1 and SCL1 requires to add (normal) pullup resistors.

Gotcha, I will remove them for the Due, but for testing on the Nano should I remove them as well? @Jot (also i have to run, but will update this ASAP tomorrow morning.)

The sensor is for 3.3v and the nano runs at 5v. I don't like that combination, unless you use a level shifter for sda and scl.

it was my understanding that the i2c on the Nano was 3.3V, but if it is not as you say, would it be possible to disable the internal pull ups and then simply use a 2k7 or 4k7 to 3.3V?

@JonathanA Nano: It is possible to turn off the internal pullup resistors after Wire.begin. The FDC2214 is damaged with a voltage above 5v and not at 3.6v as many sensors do. So with external pullup resistors of 4k7 to 3.3v, it might work for a test, but I still don't like it. Due: You need a soldering iron to remove the wrong pullup resistors. It is the smd component near pin 20 and 21.

I will spend my morning tomorrow on this. Will update you with what I find. However, on the Due I will try and remove the weak pull-ups and add my own externally. Will let you know! Thanks for your continued advice.

@JonathanA I have added a paragraph to avoid a cable. The onboard pullup resistors is a specific problem for the due, but there are many common problems for the i2c bus.

Thank you! I have posted the code that, for the moment, seems to have fixed my problem. I will, nonetheless, accept your answer as correct as it has been of great help! Thanks @Jot.

@JonathanA you still need to remove the line above the return (the last Wire.endTransmission). Read about it: https://www.arduino.cc/en/Reference/WireEndTransmission it should not be used after a call to Wire.requestFrom.

Let us continue this discussion in chat.


text:
SPI Connections to DAC
I'm hoping to construct a feedback loop for a laser using an Chipkit UC32 and an analog-digitial converter ( the one of I have is an AD5780 evaluation board). I've been reading through Digilint's  SPI library but I admit I am pretty lost.
( I believe this is on topic to Arduino because I am using an Arduino API. The micro-controller I use is basically an Arduino so I see no difference. )
I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?
Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

What does this have to do with Arduino? It seems to me that you have this UC32 which has a PIC32 microcontroller on it and you need to write a library for the AD5780 using the chip's SPI peripheral.

Also why would you write your own driver if Analog Devices has a reference driver at https://wiki.analog.com/resources/tools-software/uc-drivers/renesas/ad5780#driver_description where you only have to implement SPI_Init, SPI_Write and SPI_Read yourself using your board / platform's SPI lib? :)

@MaximilianGerhardt chipKIT uses the Arduino API. It's as Arduino as the esp8266 or teensy.

@MaximilianGerhardt Have you tried to use the AD Driver before? I'm here becauseI tried that and it seems broken. It requests files that aren't included. They don't seem to be useful but even if you remove those #include commands, it references a lot of undefined functions. Perhaps its just the missing file but seems unusable. If you have any experience with this, I could open another thread and try to fix it.

@AndrewHardy Sure, I'll download the lib and interface with the Arduino SPI class so that in theory you can drop-in the result straight away. I'll let you know if I encounter a problem. If the lib requires functions beyond that what they say, it's kind of a bad lib..

@AndrewHardy Done. https://github.com/maxgerhardt/arduino-ad57xx-driver

So there's something you're compiling or doing differently that I don't understand. When I hit Verify for your code, I get errors https://imgur.com/BKsIk2K of undefined references to commands in the Drivers. This is different than errors if I just don't have the file, so I don't know what they mean.

You must put the ad57xx_generic_driver folder https://github.com/maxgerhardt/arduino-ad57xx-driver/tree/master/lib folder in your Arduino's library folder for this to work. (This is originally a PlatformIO project btw) @AndrewHardy

No, that's not the problem. If it wasn't in the libraries folder, I would get an error at the #include<AD57XX.h> line. I have had to remove those files from the "include" directory to have Arduino recognize it. https://imgur.com/a/QVxW0hi This is my file structure currently

@AndrewHardy Then for some reason it's not compiling the cpp files. It finds the headers but doesn't compile in the implementation of it. Something is still wrong with the folder structure. Try to put all the sources and headers directly into one filder like shown in https://www.arduino.cc/en/hacking/libraries

@MaximilianGerhardt, https://imgur.com/a/WPskxYP I went away from this to work on some other things, but I'm back now. Hooking up the DAC, I get a sin function. It doesn't seem to be responsive to the numbers I change in the example code you gave. How would I go about debugging these sorts of things? I take this image is not what I am supposed to see.

I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

SPI is a communication protocol.  It uses digital signals, coupled with time, to transfer information.
To use DSPI you need to first define an SPI object
DSPI0 SPI;

From then on it's the same as using the Arduino SPI library.
Start it
SPI.begin();

Then transfer the correct commands (found in the DAC datasheet) to set the voltage of the output
digitalWrite(10, LOW);
SPI.transfer(0x43);
SPI.transfer(0x1A);
digitalWrite(10, HIGH);

The values there are just examples. The 10 is the chip select pin for the DAC, and the values used in the transfers (however many are needed) need to be found in the datasheet.
If you only want to use the pins associated with DSPI0 you can use the SPI library instead (which only supports one SPI channel - the uC32 has two), in which case it is identical to working with the Arduino SPI library.

Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

You don't. DACs are DACs and ADCs are ADCs. They aren't interchangeable.
For ADC functionality just use any of pins A0 through A11 and the analogRead() function.

thanks for responding! You've helped me before so I appreciate the patience. I've been reading for a while, so can I run some things by you? I didn't find anything in the Data Sheet, but what bytes I write are just getting bit_number = (Pos REF V - Neg REF V ) / 2^(18) and convert to bytes? There doesn't seem to be a command for the actual conversion either? From what I've read when I send bytes it automatically converts to an analog voltage and outputs it?

Secondly, do you think it is worth trying to get the AD Drivers running? The missing file is ior5f100le.h . Is this a standard Arduino library I'm missing? The driver has commands for reading data from the register too, which I don't quite understand the point of.

That DAC uses a 3-byte (24 bit) control protocol. Page 21 onwards in the datasheet describe the commands. You need to first send the correct commands to turn the DAC on (using the "Control Register"). Once on you send a value to a specific register (not a real register, so it's not listed with the registers), and toggle LDAC (either the pin or the register bit) to output that value.  I have never heard of ior5f100le.h. Probably something to do with a specific development board.


text:
Brushless Motor and Electronic Speed Controller Initialisation Issues
I have been trying to make a brushless motor, working in synergy with an electronic speed controller, to work, however, all I have been achieving is the motor vibrating at a specific potentiometer/throttle position.
The following is a description of my components, circuit setup, code and calibration approaches.

Circuit Schematic

In the code image, it should say pin 8 instead of pin 9.
One problem may be that the ESC is of a lower current and voltage level to that of the motor. I have been reading online that the ESC should have a current at about 10-20% higher than that of the motor, and a voltage of similar levels. However, to my understanding, this is to prevent any burnouts if operating at full voltage. In my case, the motor will be operating at 22V as full power (36V) is not required. I expected it to at least be turning, at a low speed, when 22V are supplied, which it is not.
Another issue I thought was that the initialization process I am undergoing is not correct, however, upon checking online and cross referencing to the instructions specified in the Hobbyking booklet they appear to be similar, so I do not think is an issue either.
Any advise or guidance would be highly valued.
Thank you!
The links in the screenshots are as follows,
1) https://www.ebay.co.uk/itm/Brushless-300w-6-5-Wheel-Tyre-Motor-Hoverboard-Swegway-Board-Replacement-Part-/292465000149
2) https://hobbyking.com/en_us/hobbyking-40a-esc-4a-ubec.html?___store=en_us&gclid=EAIaIQobChMIkvb39sq54AIVy53tCh3AhwPBEAAYASAAEgJ0RfD_BwE&gclsrc=aw.ds
3)https://cdn-global-hk.hobbyking.com/media/file/378561453X16958X28.pdf
4)https://docs-emea.rs-online.com/webdocs/13cc/0900766b813cc9bb.pdf

The fifth link is: https://dronesandrovs.wordpress.com/2012/11/24/how-to-control-a-brushless-motor-esc-with-arduino/

people are not going to read all of your post ..... when they realize that you posted pictures of text, then they move on ..... the circuit schematic is not a schematic ... it is a wiring diagram  .......... also, you have not asked a specific question


text:
28 BYJ stepper motor runs faster using delay() and little slower using millis(), why?
I'm working to develop a code for the stepper motor to use it in a project. And since using delay() isn't as efficient as millis(). So I first developed the code that use delay with 1ms delay between the steps which is the fastest I could do with this stepper motor.
Then I developed similar code using millis() with same 1ms delay but it didn't feel as smooth/fast as the one with delay() function.
So what's the reason for that?
These are the code:

With delay():
    void clockwise(void){
        digitalWrite(in4, HIGH);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, HIGH);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, LOW);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, HIGH);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, LOW);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, HIGH);
        digitalWrite(in1, HIGH);
    delay(1);
        digitalWrite(in4, LOW);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, HIGH);
    delay(1);
        digitalWrite(in4, HIGH);
        digitalWrite(in3, LOW);
        digitalWrite(in2, LOW);
        digitalWrite(in1, HIGH);
    delay(1);
}

With millis():
  void stepper_run_cw(void){
  stepper_step_cw(1,0,0,0,1);
  stepper_step_cw(1,1,0,0,1);
  stepper_step_cw(0,1,0,0,1);
  stepper_step_cw(0,1,1,0,1);
  stepper_step_cw(0,0,1,0,1);
  stepper_step_cw(0,0,1,1,1);
  stepper_step_cw(0,0,0,1,1);
  stepper_step_cw(1,0,0,1,1);
}

void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
  if (!stepper_run){
    digitalWrite(in1, m_in1);
    digitalWrite(in2, m_in2);
    digitalWrite(in3, m_in3);
    digitalWrite(in4, m_in4);
    stepper_start = millis();
    stepper_run = 1;
  }

  if(stepper_run){
    stepper_current = millis();
    if(stepper_current - stepper_start >= delay_time){
      stepper_run = 0;
    }
  }
}

why would you repeat digitalWrite(in1, LOW); five times in a row? .... you only need to run it one time  .... same for the other pins   ........... also, the if(stepper_run){ should be an else instead

@jsotola 1. How to run it one time? And in which function? The 1st or 2nd posted codes? 2. Got the tip about using else thanks.

How can the second function work at all? What if you enter in stepper_run_cw with stepper_run = 0 and millis not changing , nothing? stepper_step_cw call that does something is purely random, the one where millis changed form the last call to stepper_step_cw.

try using micros() instead of millis()

i just had a thought ..... i wonder if the order of the digitalWrite commands has anything to do with the speed difference .... one is 4321 and the other is 1234 ................ change the order in one of them ....... also put stepper_start = millis(); at the top of the if block

@jsotola yep the micros() works too, I can crank the speed even faster :) thanks for the tip.

Maybe for the second function you want something like this:
 void stepper_run_cw(void){
  stepper_step_cw(1,0,0,0,1);
  stepper_step_cw(1,1,0,0,1);
  stepper_step_cw(0,1,0,0,1);
  stepper_step_cw(0,1,1,0,1);
  stepper_step_cw(0,0,1,0,1);
  stepper_step_cw(0,0,1,1,1);
  stepper_step_cw(0,0,0,1,1);
  stepper_step_cw(1,0,0,1,1);
}

void stepper_step_cw(uint8_t m_in1, uint8_t m_in2, uint8_t m_in3, uint8_t m_in4, uint8_t delay_time){
  unsigned long temp, i;
  for (i=0;i<delay_time;i++){
    temp = millis();
    while (temp == millis){};//wait for millis to change
  }
    digitalWrite(in1, m_in1);
    digitalWrite(in2, m_in2);
    digitalWrite(in3, m_in3);
    digitalWrite(in4, m_in4);
}

This code is also avoiding the millis overflow issue if you run your board for a long time.
Still, apart for a improved timing, there is no gain in using millis(), you still have to wait for millis to change, you might want to use a timer interrupt to do the job in background.

The real gain when using millis() is that you aren't blocked in delay() and can react to inputs changing without needing to resort to interrupts.

Yes, that's my aim. Is not to use delay. Hmm I'm still considering to improve the function which uses millis(), it's working anyway, it just give a different result like littttle slower that's all. Otherwise it's works like a charm :)

After working on developing the function couple times, I got a way with this function and runs smoothly too :)
Hope anyone find it useful.
// this library is for the 28BYJ stepper motor

  #define in1 6
  #define in2 7
  #define in3 8
  #define in4 9

  // blink
  unsigned long blink_start_millis;
  unsigned long blink_current_millis;
  unsigned long blink_period = 100;

  uint8_t stepper_masks[] = {0x80,0xc0,0x40,0x60,0x20,0x30,0x10,0x90};
  int8_t s=0;
  uint32_t stepper_start;
  uint32_t stepper_current;
  uint32_t stepper_period;
  byte stepper_run;

  void blink_pin13(void);
  void stepper_step(uint8_t *mask, uint8_t delay_time, uint8_t dir);

  void setup() {
    Serial.begin(9600);// put your setup code here, to run once:
    for(byte i=in1;i<=in4;i++){
      pinMode(i,OUTPUT);}

    pinMode(13,OUTPUT);

  }

  void loop() {
   stepper_step(stepper_masks,1,0);
    blink_pin13();

  }

  void blink_pin13(void){
      blink_current_millis = millis();
      if(blink_current_millis - blink_start_millis >= blink_period){
      digitalWrite(13, !digitalRead(13));
      blink_start_millis = blink_current_millis;
    }
  }

  void stepper_step(uint8_t *mask, uint8_t delay_time, uint8_t dir){
    if (!stepper_run){
      for(byte i=6;i<10;i++){
        digitalWrite(i, 0<(mask[s]&0x80>>i-6));
      }
      if(!dir){s++;if(s>7)s=0;}
      else {s--;if(s<0)s=7;}
      stepper_start = millis();
      stepper_run = 1;
    }

    if(stepper_run){
      stepper_current = millis();
      if(stepper_current - stepper_start >= delay_time){
        stepper_run = 0;
      }
    }
  }


text:
How to read Output data from SPI connector using Arduino Uno?
I am having main controller circuit board that give the data such as ("HAI", "HELLO") to 5 pin SPI Connector mounted on the same board. In that 5 pin SPI connector  I could  connect separate circuit board which has SPI based 5 SEVEN segment LED  to see the output for e.g. ("HAI", "HELLO").
Pin configuration for 5 pin SPI connector on main circuit board.

Pin 1 -  VCC
Pin 2 -  GND
Pin 3 - CS (chip selection)
Pin 4 - CLK (clock)
Pin 5 - D IN (Data).

Everything working fine and also I can see the output data on the SEVEN-segment display such as "HAI" and "HELLO" through my naked eye.
But I need the same data to display in my PC/Laptop console so I used Arduino uno controller setup.
So I did connecting wire from Arduino controller to 5 pin connector of main controller circuit board.
Connections below.
Arduino controller                 Main controller ckt board
(Digital pins)                      (5 Pin connector)
PIN 7 (D IN) --------------------------->   PIN 5 (D IN)
PIN 6 (CS)   --------------------------->   PIN 3 (CS)
PIN 5 (CLK)  --------------------------->   PIN 4  (CLK)

I connected USB cable to my PC and I installed arduino driver and also configured COM PORT (COM5 my-case).
I opened  Hyper-terminal console in that I chosen COM5 and baud rate 9600. But still I did not get the output ("HELLO", "HAI")
on the console because the Arduino controller does not have source code for reading the output string("HELLO", "HAI") from the 5-pin SPI connector on main ckt controller board.
What I need exactly?

I need a source code that for reading the output from 5 pin connector through SPI and should display on my console.

Can anyone share the full source code for do that above operation ?

first wire it to SPI pis of Uno. then use SPI library in slave mode. the device will send  not only the text. it is possible it will send only the segment addresses with states

Need to start with the correct pins.
With Uno, SCK is 13, MISO is 12, MOSI is 11, and typically 10 is used for slave select.
To read from a slave device, some setup is needed, then the command is run. Here's a very simple example:
byte ssPin = 10;
byte incomingByte;
byte addressToRead = 0x00; // or what is needed, if needed.

void setup(){
Serial.begin(9600);
pinMode (ssPin, OUTPUT);
digitalWrite (ssPin, HIGH); // most devices expect a LOW for slave select
// the code in behind SPI.transfer may do this already, I put it in anyway as
// sometimes I use different pins.  10 needs to be an output for the
// Atmega to be the SPI bus master

SPI.begin(); // uses default values: SCK of 4 MHz, MSBFIRST, Mode 0 for
//              initial signal levels
}

void loop(){
digitalWrite (ssPin, LOW); // select the device
SPI.transfer (addressToRead); // may be needed for your device
incomingByte = SPI.transfer(0); // read a byte from the slave
digitalWrite (ssPin, HIGH); // deselect the device

Serial.print(incomingByte); // may need some manipulation to make this
//                             a printable character - see
//                             www.asciitable.com
delay(500); // keep from flooding the PC screeen
}