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

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

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

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

DHT22 code:
#include <SimpleDHT.h>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

https://thinger.io

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

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

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

dht dht22;

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

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

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

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

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

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

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

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

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


text:
Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno
I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?

At the very least for questions like this provide hot-links for the part's circuit diagrams. Most engineers who answer questions here would just design what is needed and so mentioning shields is probably not helpful without links.

https://store.arduino.cc/usa/arduino-wifi-shield

I am using below 3 parts: https://store.arduino.cc/usa/arduino-wifi-shield, http://wiki.seeedstudio.com/Seeeduino_v4.2/ https://github.com/Protocentral/ADS1292rShield_Breakout

As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).
Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.
In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the tops of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.
I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).

source: Stack Exchange

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

sort: votes


text:
Relay with mechanical fallback
In my circuit I have a relay that will turn on some light bulbs this is my circuit:

The switch over the 5V is in fact my Arduino. A HIGH will turn on the relay and a LOW will turn it off.
This is working fine, but because of security measures I need to add a mechanical switch to be able to turn on and off whenever needed. This is the circuit I'm using for this configuration:

This circuit also works fine, the lamp is turned on and off by changing either switches but the Arduino loses track of the status of the lamp. The only thing it knows is if the relay is on or off.
Is there a simple way to tell when the lamp is on?

Maybe you should replace your ON/OFF switch with a three way switch: ON/OFF/AUTO, where AUTO means Arduino-controlled.

@EdgarBonet I’m sorry, how? I’m mixing AC and DC and I’m not seeing how can I do that

Slap a current transformer over the AC line?

Is it enough to add an input to the arduino to override the programming? Or does it really need to be an electrical override?

@ratchetfreak what do you mean by "override the programming"? I just want a safe way to check if the lamp is on. I'm open to any suggestion that will keep the arduino and the switch working together

Connect the mechanical switch to an Arduino input pin. Then in you code, turn on the relay if the switch is turned on (or your other condition is met).

Searching "ac line monitor optocoupler" showed some interesting results, though I have no experience with these devices. Alternatively any way to monitor the second switch (maybe use double pole) may work as well.

If you add an optical sensor appropriate for the lamp (UV, IR, visible light?) and add a test line to your code, the Arduino would "know" if the light is on. Your second circuit could remain as presented, while the sensor would provide a status of the light.
If the light failed for an unknown reason, the code for your Arduino would not know the difference between that and a manually opened override switch.

This should work. But I’m not inclined to use this solution. I’m placing one Arduino (esp8266) per room. Meaning each board will have at least: 1 temperature sensor, 1 humidity sensor and 1 output for the relay. Adding another component to the board would be a little difficult. I would prefer a logic circuit over this solution.

I got the terminology wrong in my comment. My suggestion is not to use
what is commonly called a “three way switch”, but instead a single pole
triple throw
switch. This is
not available in the schematic editor, so I had to improvise. Imagine
that the switch labeled “SP3T” below has three contacts on its left
side:

simulate this circuit – Schematic created using CircuitLab

The top contact connects to nothing: this is the OFF position
the middle contact connects the controlled circuit with the relay:
this is the AUTO position where the Arduino is in charge
the bottom contact closes the controlled circuit: this is the ON
position

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


text:
Arduino Obstacle Avoidance (Problem)
I am having a problem. I designed obstacle robot with ultrasonic sensor. But the problem i'm facing is one that no one discussed ever. I kept on searching it on internet and found no solution for it. So, i decided to ask it here:
Firstly, I used one ultrasonic sensor to avoid obstacle alongwith servo motor using newping library. But it failed badly due to an elevation of the sensor so it doesn't detect any lower height object.
Second time, i used three ultrasonic sensors to check for the side's obstacles and front obstacle as well. In most of the cases what no one ever showed in video there are some places and times when it get stuck (due to design and even sonar limitation).
What i want to do is to add some features to the code that can detect stuck motor or stopped robot at one place. Once detected this condition it moves backward and turn the other way if again stuck then move backward and turn the other way.
I hope i could make you understand the problem i'm facing. I'll appreciate the solution and it may help others to find solution for it. I don't know how to attach the code here (it may create mess for the reader). So, please tell me if i need to send or attach here. Thanks.!

you could add bump sensors(switches) so that it it bumps into an object, it can back up and turn the right way(depending on which sensor is hit).   Think about humans, how do we get around if we cant see?

hint: a robot will get stuck in some places because it always reacts the same way to a particular sensor input


text:
How to get separate BPM readings from two pulse sensors using one Arduino
Here is the code I used to get BPM from pulse sensor.
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most
acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground
Library.

//  Variables
const int PULSE_SENSOR_COUNT = 2;
const int PulseWire = A0;
const int PulseWire2 = A1;
const int LED13 = 13;
int Threshold = 550;

void setup() {
  Serial.begin(9600);
  pulseSensor.analogInput(PulseWire, 0);
  pulseSensor.analogInput(PulseWire2, 1);
  pulseSensor.blinkOnPulse(LED13);
  pulseSensor.setThreshold(Threshold);
  if (pulseSensor.begin()) {
  }

  void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".

    if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
      //Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
      Serial.print("BPM1: ");                        // Print phrase "BPM: "
      Serial.println(myBPM);                        // Print the value inside of myBPM.
    }
    delay(20);                    // considered best practice in a simple sketch.
  }

I wish to separate display the BPM that get from A0 wire and A1 wire. Serial could print something like this: BPM1(A0):75, BPM2(A1):80.
I don't know how to do that, can anyone help me with it?

Your sketch does not compile. What libraries are you using?

I am using PulseSensorPlayground Library. And I just added the library code on top

Could you please make it clearer what you are trying to achieve. I suggest you reword your last paragraph. Perhaps a picture would help.

Change "#define USE_ARDUINO_INTERRUPTS true" to "#define USE_ARDUINO_INTERRUPTS false".

If, instead, your Sketch does not use interrupts to read PulseSensor data, your Sketch must instead contain the following two lines, in order:
#define USE_ARDUINO_INTERRUPTS false
#include <PulseSensorPlayground.h>

Source: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h

thank you, but I am still struggling on how to print different BPM

The next line of code you are missing is on line number 146: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/src/PulseSensorPlayground.h. Please read all the comments in PulseSensorPlayground.h. Let's make sure we are looking identical libraries.

Have a look at this sketch: https://github.com/WorldFamousElectronics/PulseSensorPlayground/blob/master/examples/TwoPulseSensors_On_OneArduino/TwoPulseSensors_On_OneArduino.ino

Thank you very much! I solved the problem now. And thanks for being patient with me, I am really new to Arduino.


text:
No potential across output of H-bridge
I’m working on a robot with a club at my school. So far, our team has an H-bridge shield (https://www.freetronics.com.au/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.WwI9omh_WEc) to drive motors in a toy tank. The H-bridge is powered by 6 AA batteries and the arduino is powered through the H-bridge shield with these batteries also.
 When everything is connected up and  code uploaded to make the motors run forward, nothing happens - the motors don’t run. So far to debug, I’ve used a multimeter to check the voltages being output to the H-bridge from the arduino controller. These are all as expected. I’ve touched the motors to the positive and negative terminals of the battery and they run as expected. Lastly, I’ve substituted the H-bridge shield for a known working one. This did not fix the problem. I disconnected the motors and tested the voltage being output, which measured as +6V for both terminals of the motor relative to the negative terminal of the battery as well as relative to the ground pin. I also disconnected the jumper powering the arduino from the H-bridge shield and instead powered the arduino from my laptop. This did not fix the problem either. This seems completely contradictory. Any ideas on what the problem could be? Thanks so much ❤❤

Do you have a separate power supply connected to the shield? If not did you connect the jumper to power the motor from the Arduinos Vcc?

Measure the current going to the motors when connected to the shield vs when directly connected to the battery. Either your supply breaks down or you don't have the supply connected (see @Gerben comment). It would help if you draw a schematic of your exact setup  (all conncections) using either pen&paper or the schematic tool when editing the question.

here is the schematic .... looks like you require jumpers in JP1 and JP2 for enabling the data pins

It sounds either (i) like your motor driver is broken or (ii) your code does not operate the H bridge properly.  Check which digital outputs pins of the Arduino control the H bridge and make sure that they do not short out the H bridge.
If you want to try another H bridge, this one is suitable for your application: https://www.pololu.com/product/2990 .  I have worked with this before and it's very easy to use.


text:
Weird sketch size/memory/compiler (?) related issue (hanging, RX led on)
Also posted at: https://forum.arduino.cc/index.php?topic=549672.0
is there anyone who experienced similar problem or knows a solution to it?
The problem is that after uploading the code Arduino Pro Micro hangs (and RX led is constantly on).
The problem occurs instantly after turning on the microcontroller even if I put "delay(10000);" at the begining of the code trying to see at which point the error occurs.
The problem can be "fixed" by adding 'Serial.print("aa");' at random place within the code...
Which results in the following output during upload:
Sketch uses 18318 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1814 bytes (70%) of dynamic memory, leaving 746 bytes for local variables. Maximum is 2560 bytes.

Suprisingly, using 'Serial.print("a");" instead does not fix the problem. It results in the following output during upload:
Sketch uses 18314 bytes (63%) of program storage space. Maximum is 28672 bytes.
Global variables use 1810 bytes (70%) of dynamic memory, leaving 750 bytes for local variables. Maximum is 2560 bytes.

It seems very weird to me that adding serial print instruction with certain length (at seemingly random place) can solve such problem...
Another circumstance which seems to be solving the problem is commenting out one of the 2 lines (does not matter which):
sprintf(at_cmd, "AT+NAME%s\0", bluetoothName);
sprintf(at_pin_cmd, "AT+PIN%s\0", pin);

It's a spaghetti code so I doubt anyone will analyse it but just in case if anyone wanted to check it for some more or less obvious characteristic (e.g. F()/eeprom/memory extensive use or something...) then here it is: Hastebin - link
I'm using "Arduino Pro Micro 5V" and Arduino IDE 1.8.5 with "Arduino Leonardo" board setting

You should make more use of PROGMEM for your string constants.  Use the _P variants of the string library functions.

You may want to look up how to use PROGMEM, That will let you move your arrays and global string literals to program space instead of taking up RAM

Does the only occur after uploading a new sketch or also after pressing the reset button or power-cycling?

Thanks for suggestion, but what do you guys think about the potential cause of the problem which I described?

@Gerben It happens after unplugging and plugging it back too. Not only after uploading.

Most strange hangings are caused by lack of RAM or buffer overruns. Using PROGMEM will help if it's the former that is the cause. It may also help you find where a buffer overrun is while you refactor your code.

Also asked here: http://forum.arduino.cc/index.php?topic=549672.0

Your description of the fault that goes away with some random print statement placed anywhere smacks of a buffer overrun somewhere in your code.

@Delta_G Wouldn't the code at least run until that overrun moment in such case? That's why I tested "delay(10000)" at the begining of setup function and realized it was not executed at all.

No.  An overrun causes undefined behavior.  That means it could fail at boot or when it gets to a certain line or it could make little demons fly out from your nose.   Anything goes with undefined behavior.


text:
Using TTGO TS 1.0 TFT display
I'm trying to use the TTGO TS 1.0 display with a demo app from a different source. The demo app wants the following to be configured:
#define PIN_NUM_MISO 17     // SPI MISO
#define PIN_NUM_MOSI 23     // SPI MOSI
#define PIN_NUM_CLK  5      // SPI CLOCK pin
#define PIN_NUM_CS   26     // Display CS pin
#define PIN_NUM_DC   17     // Display command/data pin
// ** If you want to use them, set them to some valid GPIO number
#define PIN_NUM_RST  0      // GPIO used for RESET control

According to the TTGO readme the following wiring is used:
CS:16
DC:17
SDA:23
SCK:5
RST:9
My guess is:
PIN_NUM_MISO ?
PIN_NUM_MOSI 23
PIN_NUM_CLK  5
PIN_NUM_CS   16
PIN_NUM_DC   17

How to update the demo app to match with this? Reset is optional in the demo and there is 1 additional pin there as well which I can't figure out...

Sounds like your demo code is for an SPI screen, but you have an I2C screen.

Maybe silly question, can this be used somehow say, with a software I2C to SPI adapter?

You can re-write your demo code to use I2C instead of SPI. There's no such thing as a "software I2C to SPI adapter"

Although, looking at the code that's in that repo it may in fact be uni-directional SPI (MOSI and SCK but no MISO, which is quite common).

If it is, as I think it may be now I have dug into the code a little, simply an SPI interface with no MISO (which is quite common for TFT screens) you just map the pins 1:1 and ignore MISO.

PIN_NUM_MISO => Ignore
PIN_NUM_MOSI => SDA
PIN_NUM_CLK => SCL
PIN_NUM_CS => CS
PIN_NUM_DC => DC
PIN_NUM_RST => RST or Ignore

If the demo code insists on there being a MISO pin you can just assign that to any unused GPIO pin. You don't need to connect it to anything.
The majority of TFT and OLED driver code only ever writes to a screen and never reads from it, so MISO is not needed to actually control the screen.

Unfortunately the display doesn't work with this config. Which doesn't necessary mean the answer is wrong, I'll try to confirm it somehow.


text:
Can the TimedAction library be used to call functions of an object
Currently to use TimedAction for a function a program would look like so:
#include <TimedAction.h>
void functionX();
TimedAction funtionTimed = TimedAction(1000, functionX);

void setup()
{

}

void loop()
{
functionTimed.check();
}

void functionX()
{
 //run function
}

My question is say I have an object class with some functions I would like to use with this TimedAction library. How would this be written?

You can't. The TimedAction class doesn't support the function prototype required for your undefined class (it has to match your class, so can't be written).
You have to call a normal function which then calls the class function, or you have to have your class function as static so it doesn't include the class in the function prototype.
class foo {
    public:
        static void runMe() {
            // blah blah
        }
};

TimedAction funtionTimed = TimedAction(1000, foo::runMe);

However, TimedAction is pretty simplistic and you don't really need it.  You can just write a function to only run every so often:
class foo {
    private:
        uint32_t _runMeTimestamp;
    public:
        void runMe() {
            if (millis() - _runMeTimestamp < 1000) return;
            _runMeTimestamp = millis();
            // blah blah
        }
};

foo myFoo;

void loop() {
    myFoo.runMe();
}

Those two lines of code, plus a variable to store the timestamp in, are all you need to make a function run at periodic intervals.

Thanks, yes I had been using it to call a normal function which then calls the class function, was just curious if I could reduce redundancy

Protip: You can re-write the library to use std::function instead of raw function pointers. You can then use lambda expressions or std::bind to call into a member function of a particular object. This would be the C++ way to do it.


text:
Sensor to measure distance on inverted pyramid filled with maize
I'm struggling with the following problem:
I have an inverted pyramid, supported in four points, filled with maize up to 600KG.
I want to keep track of the level of maize inside the inverted pyramid.
I've thought about using a load cell but this can be expensive and I need a cheap solution to implement. I also thought about using a sensor centred on top of the inverted pyramid.
The problem here is that I really dont't know what kind of sensor can be used to get correct values.
Can ultrasonic sensors give me bad values? The pyramid form is tricky...
PS: Theoricly can mill be too reflective and influence the result of measures?
I'm sorry for the English :P. I'm still learning.
If anyone can help I really appreciate.
Best Regards

About what size are we speaking here?

are you talking about the whole ears of corn or just the seeds?

The pyramid has 1.80 m of height and at the top (inverted pyramid)  is 2m.

@jsotola It's just the seeds to be ground (milled?).

i am guessing that the "inverted pyramid" is a funnel, so there is a discharge port on the bottom .... i wonder if a large rubber ball would "float" on top of the seeds ... if it does "float", then you could monitor its position somehow, but you would have to keep it out of the discharge port

other thought ... some type of a pressure sensor placed near the bottom of the container

@jsotola Yes. It's a funnel and at the bottom have a discharge port.
Floating is possible but with this mechanism when I will fill the pyramid I need to put the rubber ball at the top and after that start... And I'm trying to get a full automatic fill. I think that with this solution I can get some troubles right?

@jsotola I forgot to mention but the container can hold up to 600KG.

Maybe a laser time-of-flight distance sensor (as the ones you can get in a hardware store) is working here. Though I'm not sure, if the maize is a good reflector for the light. Can you try out, or is this theoretical for now?

@chrisl I'm trying to understand the behaviour of the suggested sensor and could be possible with that. And Yes I can do some experiments. Have you any reference of the sensor? Could be a VL53L0X?
Did you know if the surface of corn seed can disperse the laser beam and get wrong values?

Yes, this seems to be a reasonable choice. You can by a breakout board on amazon for it. And it would perfectly fit your range. I think you don't need a precision of 1mm, so the error due to the non-optimal reflective surface of the maize may not be a problem at all. But this is something you have to try. I don't have experience in measuring my distance to maize :D The sensor is interfaced with I2C and I'm sure there are some libraries for it out there in the internet

optical sensors may fail because of the amount of dust that would collect on the sensor or on a window used by the sensor

@jsotola good point.

i just googled grain level sensor and got this http://www.rhinohydeproducts.com/products/grain/bin-level-sensors/  .... it indicates that it is a capacitive sensor .... no idea how it would work

look at the top leftmost one on this page ... https://www.binmaster.com/products .... there is a mechanical drawing on the website

The surface of corn is hard enough to reflect sound from an ultrasonic sensor. It reflects from fabric, skin and of course, plastic, and corn fits into the realm of reflectivity.
An Arduino with an ultrasonic sensor may scatter a good bit of the reflection, but some of it will get back to the receiver in sufficient condition to be registered.
The components necessary to test this are low enough cost to suggest a prototype. A simple pail or bucket filled with the grain and attached to a rope and pulley will give you distance information, and that would be for a relatively small surface area.
Ultrasonic sensors typically have a minimum distance and of course, a maximum distance. If your concern is for both full and empty conditions, dual sensors placed a sufficient distance apart with suitable range considerations are likely to work. The code would be written to avoid cross-pulse readings, which is likely to be trivial, as these devices operate at the speed of sound.
Lasers are point devices and may not necessarily reflect to the sensor for reading.
I have constructed a DME (distance measuring equipment) that displayed passing vehicles within a range of ten feet (~3 meters) down to slightly less than three feet (<1 meter) with good results. There was tremendous lag in the reading, but that's due to code ignorance, not hardware problems. I suspect the depth finder is not going to have much lag in determining its value to this application.

And dust can give me bad values?

I'll bet if you have enough dust to make visibility difficult, it would give you very short readings on the ultrasonic or none at all. It's not out of the question that the ultrasound would be absorbed by small enough dust particles. I'm aware that some grain silos have explosion danger due to dust.  The cost is still low enough to justify a test build, even if only in breadboard form.

You can let the sensor "sense" 20 times and let your Arduino figure out the average.
More on Using the HC-SR04 Ultrasonic Distance Sensor with Arduino.
Maybe the ultrasound also scares rodents. I am using IR sensor Sharp GP2Y0A02YK which reaches from 20-150 cm

Hi Gerrit and welcome to SE.Arduino! This is a bit of a link only answer. If the link dies, then your answer will not be terribly useful. Please consider editing your answer and quoting/including pertinent information from your link in your answer. Please take a look at the tour and How do I write a good answer. Also, take a look at other high voted answers, in order to get an idea of the standard required.


text:
Trying to read the current position of a flex sensor and store it as a variable? NANO ATmega328p
I am trying to write a code to read the current position of a flex sensor when a button is pushed and use that data to pulse a piezo. I set it up to read the flex sensor and to alarm when it gets 100 or below, that works! So what I want to do is integrate a button where you push it to set the current state of the flex sensor and then when its moved and is less than the number logged when the button was pressed then it alarms. I used to write in Basic and quick basic and am now (many years later in life) trying to learn C and am struggling. I'm using a NANO ATmega328p - here is my code so far:
int flexSensorPin = A0;//analog pin 7= tiny2=A1
const int Piezo = 3; //digital pin 3 = tiny0
const int inPin = 2; // Push Button to set current Bend Status
void setup() {
  pinMode (Piezo, OUTPUT);
  pinMode(inPin, INPUT);    // declare pushbutton as input
  Serial.begin(9600);
}
void loop() {
  int val = 0;
  val = digitalRead(inPin);
  int flexSensorReading = analogRead(flexSensorPin);
  Serial.println(flexSensorReading);
  if (flexSensorReading < 100) {
    Serial.println("Alarm! Set Angle Exceeded");
    digitalWrite(Piezo, HIGH);
    delay(100);
    digitalWrite(Piezo, LOW);

  }
  delay(250);
}

And what is your specific problem in writing the code? You already read the state of the button pin and the analog voltage of the flex sensor. Use an if statement, where you set a variable to the analog value, if the button was pressed. Then replace the 100 in your first if statement with this variable.

And two other things for when you have done this: For the button to be responsive you should ditch those delay() calls and use non-blocking code (refer to the BlinkWithoutDelay example of the Arduino IDE). And then it might be necessary to debounce your button. For this you can find plenty tutorials on the web.

Also depending on your wireup you might want to use INPUT_PULLUP instead of INPUT if you don't have an external pull-up resistor attached to your button input. (https://www.arduino.cc/en/Tutorial/InputPullupSerial)

Also the TimedAction library (https://playground.arduino.cc/Code/TimedAction) will help you to periodically flip the piezo output (if an alarm needs to be triggered) every 100ms. You thus get rid of the delay() calls and your button will become more responsive. For button debouncing, you can also use the Button library (https://playground.arduino.cc/Code/Button).

You will need to add this at the start of your code.
int LoggedPosition=100;

Change this line
if (flexSensorReading < 100) {

To this
if (flexSensorReading < LoggedPosition) {

and add this at just before the delay, at the end of the loop() function
if(digitalRead(inPin)){
    LoggedPosition=flexSensorReading;
}

I entered that code but it appears to reset the value to a new value every time its flexed so you keep flexiing until the value exceeds the flex sensor. it's like what I want sort of. but not.. I want it to set the value of the current position when the button is pressed or when powered up then use that value as the "boundary" point where if that's met or exceeded then the alarm sounds and continues to sound until the button is pressed to reset the value or the flex sensor is moved to the "safe" position.

I think your button gives a low voltage to the pin, when pressed. It's a bit counter-intuitive, but that is the only thing that could cause this behaviour.You will need to change if(digitalRead(inPin)) to if(digitalRead(inPin)==0).  Check if this works.


text:
Utilizing two different serial ports simultaneously on a due
I am trying to understand how the serial ports are configured on the due board. Please correct me if i'm wrong, but to my understanding, the due has:

Four separate serial ports ("serial", and "serial 1-3"), each with SX and TX pin functions
A USB port paired with serial, simultaneously sending and receiving data from the serial function via USB protocol

I'm currently sending MIDI data over serial1 with the required baud rate of 31250. I want to configure another serial function (assumingly with a different baud rate to match the IDE serial monitor) in order to monitor Serial.print messages simultaneously for debugging.
In setup():
Serial1.begin(31250);  //MIDI baud rate
Serial.begin(115200);

and then, in a for loop i want to monitor each value i in the array loop1[i]):
Serial.print(String(loop1[i]) + " ");

However, i can't seem to make it work... My question is, is it possible to transmit the MIDI data via serial, in parallel with serial.print data with a separate serial function?

you should show your code. didn't you forget Serial.begin()?

Added some code

You can't use MIDI on Serial and use Serial.print at the same time. You can though use MIDI on Serial1 and use Serial.print at the same time (or Serial2 etc).

I am using midi on Serial1. Tried different variations of sending MIDI on Serial2, combined with Serial.print, Serial1.print or Serial3.print. No luck though...

Then there must be something else fundamentally wrong with your sketch.

Yeah, i have now been able to use Serial and Serial1 simultaneously. Your feedback answers my original question. Will look more into the function that i want to debug.


text:
CMDmessenger library
I am trying to use the CMDmessanger library on my Arduino uno, and am facing an issue.
My issue starts right from the ArduinoController.ino example.
When i send the frequency command
3,1;

The led starts blinking correctly, once per second.
But when I send a wrong command (basically a command without an argument)
3;

The led just stops blinking. The state of the led depends on which state it was in when I sent the command.
I realised that, when I send the wrongly formatted command, it takes the frequency as 0.
Is there any method by which I can make sure that the command is received in the right format, before it is executed? Ideally I would love it if there is a method to know how many arguments were received, and I could call the readBoolArg, or other equivalent functions to retrieve the argument data.
I am planning on using this library for quite a few projects, and I don't want to be in a situation where things went wrong because there was not formatting check.
Thanks in advance.

For some extra context, I am a developer at Inventrom Pvt Ltd and developing a library for interfacing the Bolt WiFi module with the Arduino
Here is a link  if anyone is interested.

The example code uses cmdMessenger.readFloatArg(); (source) to read an argument.
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();
  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

That function will set ArgOk to false if there was no next argument.
float CmdMessenger::readFloatArg()
{
    if (next()) {
        dumped = true;
        ArgOk = true;
        //return atof(current);
        return strtod(current, NULL);
    }
    ArgOk = false;
    return 0;
}

Thus you should try to use public function
bool isArgOk();

/**
 * Returns if the latest argument is well formed.
 */
bool CmdMessenger::isArgOk()
{
    return ArgOk;
}

of the CmdMessenger object (which will return ArgOk) to check if the read argument was okay. You could e.g. modify the code as follows
void OnSetLedFrequency()
{
  // Read led state argument, interpret string as boolean
  ledFrequency = cmdMessenger.readFloatArg();

  //Did we just read garbage because the argument wasn't there?
  if(!cmdMessenger.isArgOk()) {
      //Using Serial might be a bad idea because that cmdMessanger operates on the same Serial stream.. but you get the idea.
      Serial.println("You didn't supply a correct argument! Error.");
      return; //goodbye
  }

  // Make sure the frequency is not zero (to prevent divide by zero)
  if (ledFrequency < 0.001) { ledFrequency = 0.001; }
  // translate frequency in on and off times in miliseconds
  intervalOn  = (500.0/ledFrequency);
  intervalOff = (1000.0/ledFrequency);
  cmdMessenger.sendCmd(kAcknowledge,ledFrequency);
}

Thank you. I didn't realise that's how the isArgOk function worked.


text:
What will happen if I set ARef to 3.3V and try to use adc connected to 5V
What will happen, if I try to measure voltage higher than ARef?
For example, my ref is 3.3V, and I try to measure 4.5V. Will it damage adc?

Somewhat similar to my question: https://arduino.stackexchange.com/questions/43459/can-i-connect-a-voltage-higher-that-the-1-1v-bandgap-voltage-to-an-adc-pin

I am using internal VREF 1.1V and measruring throuht a 1Mohm to 3.3V and a phototransistor is connected to GND. If no light is present, I read the value ADC of 1125bit. What is far strange because the maximum is 1023 with zero included.
So I would say it may not damage the chip but creates strange behaviour. A voltage divider is recommended.

The datasheet of the Atmega328P does not give a direct answer to this, but

Single ended channels that exceed V REF will result in codes close to
  0x3FF.

(Datasheet Chapter 24.5.2)
sounds, as it would not destroy the ADC, but only result in a value very close to the maximum. I also found another side, where this is also stated. They linked to the Arduino forum, where a similar question is handled in this thread.
So all in all it should be save to provide more than the reference voltage at the ADC pins, as long as it does not exceed the supply voltage (for the UNO 5V).

As Majenko pointed out in his answer, the datasheet states, that it is safe to provide VCC+0.5V at any pin (except for reset). I just wasn't sure, if this can easily be applied to this special hardware, but it seems, that it can.

Contrary to what @chrisl says, the datasheet does give a direct answer to this:

Voltage on any Pin except RESET with respect to Ground: -0.5V to VCC+0.5V

So when running at 5V anything up to 5.5V is safe - regardless of what VRef has fed into it.
The VRef just sets the range of the ADC when comparing the incoming voltage to a DAC generated voltage, so anything over the VRef voltage will just read as "max" (1023).

As I understand this, the part you quoted does not say anything about the influence of special hardware, that is connected to the pin. For example: If you provide the ADC with the internal reference voltage of 1.1V, you must not connect a different voltage to the pin, or the ADC can be destroyed due to the short. With this reasoning I assumed, that your quote is not a direct answer for this specific case.

That is incorrect. The VRef is what it says - a reference voltage. That is all. It is compared to the incoming voltage through a comparator. It doesn't care if the incoming voltage is above the reference voltage.

@chrisl If you have a 30cm ruler and you try and measure a piece of string that's 50cm long it doesn't break the ruler. All you can say is that it's at least 30cm.

I hang at this sentence from chapter 24.5.2 of the Atmega328P datasheet: "If the user has a fixed voltage source connected to the AREF pin, the user may not use the other reference
voltage options in the application, as they will be shorted to the external voltage." Do I misunderstand something here?

@chrisl Ah, you're talking about something completely different. Nothing to do with anything the OP asked. That's just a warning against a misconfiguration whereby you can select two reference voltages at once, which is bad (and poor design on Atmel's part...).

Ok, I wasn't sure how reliable this statement is, when the voltage on the AREF pin matters on a misconfiguration. Something like when they have bad design there, why not also in another part on the same pin. I will edit my question to point to your answer

It helps to understand how an SAR ADC works and what the role of the VRef is.


text:
Removing and using programmed Atmega 328 of Arduino UNO on customised PCB
I am a newbie. I would like to kno whether the original Atmega328 on Arduino Uno, programmed with my own sketch, can be removed from an Arduino Uno board and used  on my customised PCB?

Do you have the PDIP throughhole or a SMD package version? Sure it's possible, you're just moving the chip around. If you have the support circuitry (clock-gen, power, reset lines,..), there's no reason why this shoudln't work. See https://www.youtube.com/watch?v=8i-2xKcDCzM

Yes, it can. Your board will need to provide +5v and ground, a reset signal, and a crystal for the chip's programmed clock frequency (unless you reprogrammed it to use its internal clock). The power and clock signals will need filter capacitors. You can even re-program it on the board with an FTDI (USB-TTL Serial) cable.
There are lots do-it-yourself instructions to build an Arduino board, which is a good place to start, even if what you eventually want is a larger system board with an Arduino integrated into it. This is one I can vouch for; I built Mr. Alves' Version-1 as my only Uno-like board and have been using it for several years.

Yes. Just need a few components:
10K reset pullup resistor.
0.1uF or 100nF ceramic caps:
1 to bring in DTR signal  from an FTDI Basic if you plan to reprogram the '328P, or to have a serial interface for debugging
1 on the Aref pin for analog voltage reference decoupling
1 on the VCC pin
1 on the Avcc pin. Avcc also connect to Vcc.
Crystal and two 22pF caps as noted already, or a 3-pin resonator, at 16 MHz.
Alternately, you can use the internal 8 MHz circuit for the clock, but the clock source fuses will need to be re-Programmed (using a Programmer).
If you will using a Reset switch, then a diode across the 10K pullup resistor (cathode to the 5V supply, anode to the Reset pin) can also prevent any high voltage glitches on the Reset signal from looking like a High Voltage programming pulse and making the chip look hung up as it waits for the programming sequence to begin.

Yes  I did it. Making the board was not so difficut but took quite some time to solder all the components the others mentioned (chrystals,capacitors, resistors and connectors. However,I found the Nick Gammon site very useful, particularly for the programming
part.http://www.gammon.com.au/forum/bbshowpost.php?bbtopic_id=123


text:
Merging of two functions
This is my Arduino code that checks the water Level of two different water reservoirs via 2 water Level Sensors A and B:
#define Water_Level_A 5;
#define Water_Level_B 6;

boolean Water_Level_Check_A(){
boolean Result = digitalRead(Water_Level_A);
return Result;
}
boolean Water_Level_Check_B(){
boolean Result = digitalRead(Water_Level_B);
return Result;
}

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

void loop() {
if (Water_Level_Check_A() == LOW){
--> Water Pump A
}
if Water_Level_Check_B() == LOW{
--> Water Pump B
}

What's the best way to simplify this code so that I only need one Water_Level_Check function so that the distinction between A and B and Water_Level_A and Water_Level_B is made within the function and the loop part looks like this:
void loop() {
if (Water_Level_Check_(A) == LOW){
--> Water Pump A
}
if Water_Level_Check_(B) == LOW{
--> Water Pump B
}

How about giving the function the pin number to read from as a parameter? In this case you would write if(Water_Level_Check(Water_Level_A) == LOW)

I think what you're asking for is something like this:
boolean Water_Level_Check(uint8_t level_pin){
   boolean Result = digitalRead(pin);
   if( level_pin == Water_Level_A ){
      // manage pump A here
   }
   else if( level_pin == Water_Level_B ){
      // manage pump B here
   }
   else {
      Serial.println("Water_Level_Check: unknown pin number.");
      // or some other way of dealing with a bad-pin-number bug.
      return -1;
   }

   return Result;
}

for the level testing function, which will simplify you loop function to:
void loop() {
   (void)Water_Level_check(Water_Level_A);
   (void)Water_Level_check(Water_Level_B);
}

The (void) expression before each call is a "cast to void", telling the the compiler to consider the function's boolean return value to have been intentionally "voided", i.e. you intended not to read it, and not to give an error message.

Functions like
boolean Water_Level_Check_A(){
   boolean Result = digitalRead(Water_Level_A);
   return Result;
}

Are really overcomplicated. You're just calling one function and returning that value, so it can be simplified to
boolean Water_Level_Check_A(){
   return digitalRead(Water_Level_A);
}

Or just the expression
digitalRead(Water_Level_A)

whenever you need it.
So all you're doing is calling digitalRead() on a pin number and check if the result is low. If you really want to move this to a different function then you could give it the pin number argument and directly invert the result so that a true from this function means that some action needs to be done.
boolean Water_Level_Check(int sensorPin){
   return !digitalRead(sensorPin);
}

And then call it as
void loop() {
   if (Water_Level_Check(Water_Level_A)){
       //--> Water Pump A
   }
   if (Water_Level_Check(Water_Level_B )){
       //--> Water Pump B
   }
}

The boolean Water_Level_Check_A() I'm using in my code also includes the Powering On and OFF of the Water Level Sensor. That's why I used the function in the first place. The code here is just the minimal example for my question on how to change A and B in the function. The return !digitalRead(sensorPin) looks cleaner than my approach :-) Thanks


text:
PC Fan Speed Control
I am working on a project to blow air gently through a number of pipes and variable speed. I would like to use a standard PC case fan and have control of whether the fans are on/off and also what speed they spin at. My hope is to attach temperature sensors later and eventually blow are depending on the temperature.
It appears that PC fans on 3-wire and 4-wire systems provide variable speed by changing input voltage ranging from 3-12V  (linear voltage regulator) or with PWM set to 3.3V or 5V. Furthermore, it looks like inexpensive products exist to split/copy a single signal to multiple fans (see here).
I am hoping to control 4-8 fan speeds, as independently as possible while using as simple/standard a case fan as possible. What is the best way to drive PC case fans using the Arduino?
Reference: https://en.wikipedia.org/wiki/Computer_fan_control

You can use a PWM breakout board, like the ones normally used for servos. Something like this from Adafruit

4 wire fans are best because you don't need any drivers, just a PWM output, and they can report RPMs. You might want to up the PWM frequency from uno speeds to avoid "kick noise", but that's it.

To put the comments into an answer:
You can drive most PC fans (which have at least 3 pins) with any PWM source and change their speed through the duty cycle. The Arduino Uno itself has 6 PWM channels. If you want to control more fans, you have to use an extra chip, that provides PWM. You can use the breakout board from Adafruit, but also any other external PWM chip (they are often marked as servo drivers, since servos use PWM signal too).
The speed of most fans can also be changed through providing a different input voltage, but this is not intended for direct variation. Instead this is normally used to set the speed interval, in which the fan should run. For example some PC fans have extra adapters, which lower the supply voltage to let them run more silent. For short term variation you should definitely use PWM. If your fans are too fast at their nominal voltage, you can provide them with a lower voltage permanently.
As dandavis pointed out, the 4th pin is usually connected to a feedback loop. They provide a defined number of pulses per full rotation, so that you can really measure the speed, instead of just estimating. When you don't need this functionality both kinds of fans (3 pin or 4 pin) are good for you.

Since the fan linear voltage regular usually goes up to 12V, and the breakout board from Adafruit says it will only support 6V vcc+, what do you think about going with this https://www.adafruit.com/product/1455 that says it can go up to 17V?

Yeah, thats good. It has enough outputs, is cheaper and fits to your voltage. I would use it

note that 3pin PC fans don't support PWM, they report RPM with the 3rd wire. the 4th wire is the PWM control. That's a bummer because 4pin fans cost more, but they are still cheaper/simpler than rolling your own PWM fan controller or even using a mosfet+dioide and all that. You can feed the 4th pin 3.3v for the PWM.


text:
wire up usb to pins rather than on board usb socket
I have an uno r3 clone in an enclosure and one of these usb ports on the enclosure.
It's pretty tight in there so I was wondering if there was a way to bypass the usb port on the board and plug it in directly to the pins.
So do something like plug the usb into the outer port on the enclosure and then cut off the usb end and plug the wires directly into the board rather than using the onboard arduino usb port.
The group of 4 just above the i2c seems promising but couldn't find much on it.
Thanks for your help.

Have you looked at alternative (smaller) arduinos such as the mini?

Solder the wires to the underside of the usb socket. Option two; place the uno ne’er the edge of the enclosure and have the original socket stick out (you may have to desoldering the power jack to get it close enough to the side of the enclosure. Option three; get an uno clone with a micro usb jack instead of a regular B.

I did consider the mini and nano but attatching it to an enclosure is a little tricky. I have some pcb risers for the uno which fix perfectly and it is very secure in the enclosure. I'll give the underside a go first, removing the whole pcb block on the uno will be difficult.

You will have to (optionally) desolder the existing USB socket and solder the wires to the pins where that socket was on the board. It connects directly to the pins of the CH340G surface mount chip (rectangular one by the USB socket) and soldering wires to those pins would be tricky.

Thanks for your help Majenko and Ratchet. I'll just desolder the usb port then.

The USB actually goes through the 16 pin chip that will translate the USB to serial to the RX and TX pins. None of the external sockets or plated through holes are connected to the data lines of the USB port.
You are better off soldering the wire to the pins on the connector itself. Or try and find a proper wire with the correct connectors.


text:
why of 2 identical micro-controllers, only one can connect to a given device?
I am working with 2 identical (Arduino) Adafruit Feather M0 Bluefruit LEs. Only one of them can connect to a Universal Windows Platform app running on a  Windows 10 machine. The other connection fails with Unreachable status.
I am only trying to connect with one MCU at one time. Both MCUs are loaded with the same program which resets the Bluetooth Unit. Both MCUs can connect to an Android app. Neither board appear damaged.
Why could a UWP app be able to connect to one board but not another?

Other than a software issue, there is no reason it shouldn't work. Only thing may be identical Bluetooth names or ids. Clear the device from windows and try again.
I have some cheap Bluetooth obd 2 readers that all use the same Bluetooth mac address and name. I have to delete one from my android phone before adding the new one to connect to it.

They have different addresses but the same name. The one that couldn't connect was paired (through the os) to the computer. It could connect after unpairing. I experimented by pairing the other. It could no longer connect if the other had been connected.

Yep, and that's because sometimes the app or system looks for the name and sometimes the Mac address and sometimes both. Unique everything solves that. Same thing with a pair of cheap bluetooth speakers. Change the name and it starts working.


text:
Long term connection between Arduino and computer
I am looking to make indicator lights for my computer to indicate things such as system load, IO usage, et cetera, using an Arduino and NeoPixels.  I would like to just plug it into my computer, and have some custom software connect to it and send it the data it needs as my computer runs.
The part I am having trouble with is figuring out how to connect the Arduino to the computer in a way that is consistent in the long term.
I have had issues with the Arduino switching which /dev/ttyAMC* port it is assigned, so I looked for options other than the USB serial.  The only other way seems to be USB, as that is the only common general purpose port these days.
This is where my problem lies.  People don't seem to be doing this sort of thing, or at least they don't post about it.
The Teensy can act as a USB HID, but the raw HID feature hasn't been updated in almost a decade, the host side code is based on deprecated libraries, and it seems oriented more for Teensy to computer transfers.
There doesn't seem to be any consumer level USB interface chips available, either.
I found V-USB, which seems like a solution to my problems, in fact someone even used it to do basically what I want to do.  However, I would still need to learn the library.

So, my question is what is the recommended way of interfacing between a computer and Arduino in the long term?  Is USB support really necessary, or have I just overthought the entire thing?

You don't want to use V-USB if you can get an Arduino with a native USB interface (in which case you would use LUFA).

@IgnacioVazquez-Abrams By Arduino with a native USB do you mean something like the Arduino Zero/Due?

Those do have native USB, but they don't use LUFA. I was thinking more like the Leonardo or Pro Micro.

You should check out chipKIT - it has the best usb stack in the industry (I know, cus I wrote it ;) )

And this is me using it for something similar to what you want: https://hackingmajenkoblog.wordpress.com/2017/05/19/adding-an-oled-to-my-computer/

I think the easiest option may be to keep the USB (ACM) link, so you
don't have to do anything special on the Arduino, and try to figure out
a way to identify the correct device on the computer side.
On Linux, providing consistent device names for specific peripherals is
normally the job of udev. You could add your own udev rule to create a
symbolic link for your Arduino every time you plug it in. Then, your
custom software would always open /dev/neopixel-monitor, which would
be a symlink to the proper /dev/ttyACMx device.
Actually, you may not need write your own rule. I took a look at the
udev rules installed by default on my Ubuntu 16.04 and found a file
named /lib/udev/rules.d/60-serial.rules meant to populate the
/dev/serial/by-path/ and /dev/serial/by-id/ directories. Then I
plugged in my Arduino Uno R3 and saw the symlink
/dev/serial/by-id/usb-Arduino__www.arduino.cc__0043_93140364233351E00101-if00
automatically created, which right now points to ../../ttyACM0. In
this name, 0043 is the USB device ID of the Uno, and the following
alphanumeric sequence looks like a serial number. The if00 looks like
an interface number, and may vary (it won't, se Majenko's comment).
The link name should
be a good way to uniquely identify that particular Arduino.

I have a file that makes /dev/boards/arduino/uno1 etc for all my boards. It's a rather massive file (I have a lot of boards), but it's very very useful.

The rule for that one: ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0001", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", MODE="0666", GROUP="plugdev", SYMLINK+="board/arduino/uno1"

Oh, and the interface number (if00) will always be 0 for an Arduino. It's the USB interface in the config descriptor. There's 2 interfaces, but one is a master and the other a slave (that's how CDC/ACM works), and interface 0 is the master in the descriptor. The only way to get the interface to change is to reprogram the ATMega16U2 with a different firmware.

By the way - the command udevadm info -a /dev/ttyACM0 is useful when crafting udev rules.


text:
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
When I try to compile the following code in Arduino ,I get the error "expected initializer before 'void'".How can I get the code to work?
const int LED = 9;
const int BUTON = 2

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

void loop() {
  if (digitalRead(BUTON) == HIGH);
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}

This is actually not an Arduino related problem. Everybody that gets into physical computing should have some basic knowledge in C/C++ and the compiling of such code. Using an Arduino on top of that adds complexity and is more difficult to debug if something does not work as intended. So I hereby encourage you to take some tutorials in writing C/C++ to get a feeling of all the traps that lurk at you along your journey.

You are missing a semi-colon after const int BUTON = 2
Each expression should be terminated with a semi-colon.  Your code should look like this:
const int LED = 9;
const int BUTON = 2;

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

void loop() {
  if (digitalRead(BUTON) == HIGH)
  {
    digitalWrite(LED, HIGH);
  }
  else
  {
    digitalWrite(LED, LOW);
  }
}


text:
How to control Neopixel LEDs in parallel?
Imagine a collection of LEDs (Neopixel or otherwise) labeled 2 through 12. There may be more than 11 LEDs, so repeat numberings are allowed. I want a simple way to control them from a single Arduino based on their label. So e.g. I should be able to implement a function whose arguments are a label value and an RGB value, and which turns all LEDs of that label value to the given RGB value. Most importantly, the solution has to be order-independent; that is, I should be able to re-wire the LEDs (or equivalently, scramble around the hex labels) in any manner, and still have everything work without rewriting any code. (For context, my goal is to make a custom Settlers of Catan edition, where the labels on each hex light up when their die value is rolled.)
I know I can't just use Neopixels out of the box, since the addressing depends on the order in which they're wired. So I assume I need to hack together a way for each LED to "know" its label, wire them all in parallel, and then write a custom library to . But I have no idea how to get each LED to know its label without having an entire Arduino for each LED, which would take up way too much space. (I'd like to fit everything in roughly the volume of a typical Catan hex label; think 2-3 quarters stacked together.)
I'm fairly comfortable with Arduinos, but I'm an electronics noob. Is it possible to reprogram the Neopixel controller? Or is there a tiny logic board I can hook up to a Neopixel or dumb LED that would do the job? Anything else I'm missing?

Neopixels are generally wired in a sequence. Can you please clarify how you are planning to wire these ones up?

How do you plan on connecting the tiles (electrically)?  You could just have a 12 pin connector on each of the sides of the tiles (actually 14 as you’d need Vcc and Gnd too). Or have a small micro controller, like an attiny85 on each tile and a regular rgb led. And control them over for example I2C.

what does this mean? based on their label

each LED to "know" its label .... they do not know .... the LEDs accept the first 24 bits after it is reset, and passes any other bits to the next LED ... after a reset, the second LED does not get any data until the first LED has "absorbed" the first 24 bits .... it is like a bunch of people and a deck of colored cards where each person takes a card from the top of the deck (each card represents a 24bit color)

Nick, that's part of the question. They need to be swappable in the way that regular Neopixels aren't. So e.g. wired in parallel.

jsotola, yes, I know. That's why I said "I know I can't just use Neopixels out of the box".

@Gerben, thanks, that's super helpful -- I didn't know about the ATTiny85, and that sounds like the tiny logic board I was looking for. If you want to write that as an answer (with any other tips or thoughts you have), I'd be happy to mark it as the solution.

it makes no real sense to do a hardware solution to a software problem ......  scramble around the hex labels you can do that in an array with the LEDs connected in series ..... i think that you will still have to do that with each LED separated ......... please draw two or three diagrams of the iterations of the LED labels (how they change from one roll of the dice to the next roll)

It will not be easy to “re-wire the LEDs [...] and still have everything
work without rewriting any code.” Those LEDs are not that smart, and the
only way to address them is by the order in which the color data is sent
through the data line.
What you can do, however, is write the code is such a way that rewiring
requires only a minimal change in the code. I would use an array to
map the LED indices to their labels. Something like this:
const uint16_t LED_COUNT = ...;

// Map LED indices along the strip to hex labels.
const uint8_t ledLabels[LED_COUNT] = {
    2, 2, 2, 2,  // LEDs 0 to 3 are labeled "2"
    8, 8, 8, 8,  // LEDs 4 to 7 are labeled "8"
    // etc...
};

Then, assuming your LED strip is declared as follows:
const uint8_t LED_STRIP_PIN = ...;
Adafruit_NeoPixel ledStrip(LED_COUNT, LED_STRIP_PIN);

the “function whose arguments are a label value and an RGB value, and
which turns all LEDs of that label value to the given RGB value” can be
quite easily written:
// Turn all the LEDs sharing that hex label to the given color.
void setHexColor(uint8_t label, uint32_t color)
{
    for (uint16_t n = 0; n < LED_COUNT; n++)
        if (ledLabels[n] == label)
            ledStrip.setPixelColor(n, color);
    ledStrip.show();
}

Now, if you rewire the strip, you just need to update the ledLabels
array and recompile. If you can manage to send that information to your
Arduino while it's running (a serial connection, an IR link, an SD card
inserted in an appropriate socket, whatever...), then you could even
have a procedure where the Arduino updates the array itself. Obviously
the const qualifier should then be removed. But you now have to devise
a way to “tell” the Arduino about your wiring.

The data wires of individually addressable LEDs of various descriptions are typically wired as a daisy chain, with each LED driver having input and output for the data (and clock). Each LED driver will then manipulate the signal it sends onward to trick the next LED into thinking it is the first in the chain.
Most libraries to drive them can easily have a few 100 LEDs it can driver at a time depending on available RAM.


text:
Problem in bootloading my ATmega32U4 chip
I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per
https://www.arduino.cc/en/Tutorial/ArduinoISP
 and I followed this instructions:

Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).
Upload the ArduinoISP sketch.
Wire your Arduino boards..
Select the item in the Tools > Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.
Select the Arduino as ISP in the Tools>Programmer menu.
Use the Burn Bootloader command.

But I am getting the error message as
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I am using 16Mhz crytsal oscillator along with 22pf
What might be the problem?

Did you include the 10uF capacitor?

If you are developing your own board there are a number of things which can go wrong, although the problem is usually very simple and bootloading will be easy once you fix the bugs.
Possible hardware problems are:

You have bad solder joints / connections.  Even if you think the solder joints are good, try reflowing them again
ISP leads are too long - can lead to data corruption during bootloading
Pins are not correct.  E.g. are MOSI and MISO the correct way around?
Reset pin needs a pullup resistor

Most likely, you have some sort of hardware problem.  Post your board layout (or at least schematic) and we can look at it.  If you have a pro micro board to hand (if not, buy one one ebay or similar), try bootloading that and see whether your procedure works.

tanq...I will do your suggestions


text:
generate two phase-shifted PWM pulses triggered by frequency-divided external signal with Arduino uno?
I have a 4kHz pulse as trigger and I need two phase-shifted PWM output with divided frequency from arduino uno.
Now I've managed one PWM output using the following code:
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
  }
}

As suggested by Majenko♦, I tried using Timer1 lib, but the phase shift is always 15us, regardless timer1 period.
#include <TimerOne.h>

int cnt = 0;

void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  Timer1.initialize(10000);
  Timer1.attachInterrupt(ISP_T1);
  attachInterrupt(digitalPinToInterrupt(2), ISP_INTx, RISING);
}

void loop() {

}

void ISP_INTx() {
  cnt = cnt + 1;
  if (cnt >= 4) {
    digitalWrite(3,(digitalRead(3)^1));
    cnt = 0;
    Timer1.start();
  }
}

void ISP_T1() {
  digitalWrite(4,(digitalRead(4)^1));
  Timer1.stop();
}

Shift should be arbitrary value between 0-1 x period (depends on divider)
Adjustable duty is preferred but not necessary.

Phase shifted by how much?

0-1 x period, which depends on the divider (integer)

So you want a variable phase shift then? That makes it harder.

For this question, fixed phase shift is fine. I can listen serial port on loop function and reassign registers later.

If you can live with a fixed duty cycle of 50%, then you could set Timer 1 to mode 4 (CTC with TOP = OCR1A), put both outputs into toggle mode, and use OCR1B to control the phase shift. No interrupts, no involvement of the CPU once the timer is set up. The tricky part would be selecting between the phase shifts φ and φ+π. For that, TCCR1C could help.

I think your first example is very close. What about:
int cnt = 0;
void setup() {
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(2, INPUT);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
}

void loop() {

}

void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 4) {                           //divide by 8
    cnt = 0;
  }
  switch(cnt){
    case 0: digitalWrite(3,HIGH);break;
    case 1: digitalWrite(4,HIGH);break;
    case 2: digitalWrite(3,LOW);break;
    case 3: digitalWrite(4,LOW);break;
  }
}

Assuming a uniform input frequency, pin 3 will be 90 degrees out of phase with pin 4. You could make this adjustable if you don't mind a larger divider by expanding the switch/case to eg 6 or 8 steps.
You could get more steps by triggering on rising and falling edges (although that may not give uniform phase if the incoming PWM is not at 50% duty cycle.

If I understand correctly, it uses timer0 for interrupt and CPU for counting.

No, it doesn't. The interrupt is an interrupt. Timer0 is a timer.  At the moment you just have an external interrupt triggering an ISR which adds to a variable and toggles an output.
Timer0 is used to drive millis() and delay().
What you need to do is set up a timer (not Timer0 since it's already reserved) which will time out with a period equal to the time difference of the phase shift.  Start it in your existing ISR (when the output is toggled), and in the timer's ISR stop the timer and toggle the second output (or set it the same as the 0° output).
You may find the TimerOne library helpful for this.

But why timer0 functions doesn't work with attachInterrupt ?

timer0 has nothing to do with attachInterrupt.

link  here it says 'Inside the attached function, delay() won’t work and the value returned by millis() will not increment'.

That is correct. the Timer0 ISR won't run while the INTx ISR is running. But that has nothing at all to do with your question, so why are you asking?

I tried setting up Timer1, but the shift is always 15us.


text:
Minimum value I2C-pull up resistor for arduino
I'm trying to determine the minimum value of pull resistor for Arduino Uno
The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)
For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.
But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.
So whats the minimum value of pull-up for arduino?
(also my slave has 0,4 Vol for 20 mA IOL)

I don't follow what you're asking. What's this "0,4 Vol" and what relevance does 20mA have to anything?

They come from the datasheet of arduino UNO

I get the feeling you are regurgitating values you read without understanding what they mean and the context they are used in. I still don't know what this "0,4 Vol" is.

And the concept of "minimum pullup" for I2C is meaningless.

Please check: http://www.ti.com/lit/an/slva689/slva689.pdf. I need to determine the minimum pull-up value. The maximum pull up value depends on the max bus capacitance

Why do you think you need to go to such lengths? Just stick to the recommended range of pullups unless you have a specific reason for using something else (2.2k - 4.7k).

My capacitance is high. About 800pf. I need to reduce the pull-ups

You need to do the same calculation for all the devices on the I2C bus.

What is the slave? Another Arduino uno? Just one slave?

The full datasheet of the atmega328p can be found here: https://www.microchip.com/wwwproducts/en/ATmega328P.
It is called "ATmega328/P AVR MCU with picoPower Technology Data Sheet".
In section "32.7 Two-Wire Serial Interface Characteristics" in table 32-10 on page 372 it shows different voltage levels for the input.
On page 110 it says: "When the TWEN bit in TWCR is set (one) to enable the 2-wire Serial Interface, pin PC4 is disconnected from the port and becomes the Serial Data I/O pin for the 2-wire Serial Interface. In this mode, there is a spike filter on the pin to suppress spikes shorter than 50 ns on the input signal, and the pin is driven by an open drain driver with slew-rate limitation".
I wrote here before that the i2c (the twi hardware inside the microcontroller) did not use the digital pin hardware. However, the i2c pins can still sink a lot of current. Thanks to @Berkay for noticing the same behaviour of the sink current as a normal digital pin.
According to the datasheet the atmega328p of the Arduino uno might not use the digital pin hardware for i2c. It is not known if the same mosfet circuit is used with the same (large) sink current. Perhaps the chip uses a similar mosfet circuit with added slew rate for the output and added spike filter for the input. Perhaps the same mosfet of the digital pin is used after all.
In the Arduino sketch, calling Wire.begin turns on the dedicated i2c hardware in the atmega328p chip. The sink current and voltage levels are according to the i2c specifications.
As you can see in the i2c tutorial by Nick Gammon, the Arduino can sink more than 3 mA.
When the pullup resistors are too low, for example for a sink current of 4 mA, the Arduino uno can handle that, but the slave might not.
When all the pullup resistors are combined, the required sink current can be calculated. The maximum is 3 mA to meet the i2c specifications. To compensate for wire capacitance the i2c bus speed can be lowered.
The i2c bus is not ment to go into a cable, it is not ment for long wires. A cat6 cable is 46 pF/m. That means your 800 pF is for 17 meters cable? That is not what the i2c bus is for. It is for 17 centimeters. The rule of thumb is maximum 50 cm for a normal 100 kHz to 400 kHz i2c bus.

I think you’re not right. The arduino i2c pins can sink up to 20 mA with max VOL 1V. Thats also what you see in the link. Arduino can easy sink 10 mA

This means that the images you see in the link; confirm that arduino is just using digital pin hardware for I2C

By sinking 10 mA, the 'low level' lift till 0,5V. That's acceptable according the I2C spec. (VIL is 1,5V for communication). Pull-up R is about 500 ohms

@Berkay thanks, I have changed my answer a lot. According to the datasheet the digital pin is disconnected. But that can be done before the output stage. However, a i2c bus is for a maximum sink current of 3 mA. You should fix your problem in an other way, perhaps with RS485.

I2c 3ma is a typical value for most of i2c devices. There are some devices who can sink much more like 20mA. Why should i use 3mA  for my calculations then?

It’s the driver of device that need to sink this current. There are plenty of buffers who sinks 30ma for i2c

Also like you see here; http://www.gammon.com.au/forum/?id=10896&reply=5#reply5 It's not a problem to sink 5mA to 10mA

This comes from official spec: "If higher drive devices like the PCA96xx Fast-mode Plus or the P82B bus buffers are
used, the higher strength output drivers sink more current which results in considerably
faster edge rates, or, looked at another way, allows a higher bus capacitance. Refer to
individual component data sheets for actual output drive capability" https://www.nxp.com/docs/en/user-guide/UM10204.pdf P56

The Arduino uno can only do normal 100 kHz to 400 kHz i2c bus. It does not have those extras with higher strength. It is not just the driver that needs to sink the current, the sda and scl are two-way signals. Most sensors do not mess with scl, but an Arduino board as a slave does keep the scl low for clock pulse stretching. Please modify your question and add a lot more information about your project. You need something else to communicate through that long cable that you don't tell us about.

I dont have long cable (max 2m) but a lot of devices. The frequency is 100 kHz. I dont want to go faster. I just wanted to say, like you see in the gammon link, the arduino can sink much more than 3mA. Also my slaves can sink much more. In that case, there is no need to limit your pull-up resistor for 3mA. I can use much lower pull-up for highter current, and for more capacitance.

Like you see here: https://www.nxp.com/docs/en/user-guide/UM10204.pdf P47; also 6mA can be used for 400 kHz. You can lower this frequency to 100kHz and still use 6mA.

@Berkay thanks, do I have to change my answer? Can you tell what devices are they? How many devices? Is that a single cable of max 2 meters or 2 meters to every device? Do the devices have so much capacitance, that is very weird. I still would like to know so much more. The 3 mA is specified as a minimum, but some sensors can not do more, because 3 mA is all that is needed to meet the i2c specifications. Therefor a normal i2c bus is stuck to 3 mA maximum. With processors as i2c slaves, you can go for a higher sink current.

Thanks for your answer. No you don't need to change anything. Classic devices are indeed max 3 mA, but there are plenty of devices with higher capability. I will accept your answer. Have a good day!

I assume you want to work out the minimum value for a pullup resistor that will give a voltage below VIL for an IO pin in open-drain mode.
That is not a simple task, chiefly because you don't know the ON resistance (RDSON) of the low-side MOSFET in the chip.
It's possible to come up with a rough estimate (see here) though.
With VIL of 1.5V and maximum current of 40mA that's an estimated theoretical resistance of 1.5/0.04 = 37.5Ω.
Note: this is just an estimate based on the absolute maximum and DC Characteristics values from the datasheet.
So if we take that value as actually true you can work out the upper half of a voltage divider that would result in 1.5V coming out. There's two ways of doing that - using the resistance or using the current.
Taking the resistance R1=R2(Vin/Vout-1), 37.5 x (5/1.5-1) = 87.5Ω.
If you want to do it with the current (40mA "absolute maximum"), then R=V/I = (5-1.5) / 0.04 = 87.5Ω.
However, that comes with a big caveat.  The IO pin, while it can, for short periods, sink 40mA, it's not designed to do that for long periods. For that 25mA is the recommended maximum. So a resistor should be chosen that keeps the current below 25mA.
Assuming 37.5Ω for the MOSFET resistance, and 25mA through it, that gives a voltage drop across it of 0.94V (well below VIL). The upper resistor in that divider would then be (5-0.94)/0.025=162.5Ω
So to sum up:

The absolute minimum resistor would be 87.5Ω
The recommended minimum resistor would be 162.5Ω
The resistor you would choose to use would bear no real relationship to those values since you would normally choose something more sensible, like 3.3kΩ unless you wanted to run the I2C bus at insanely high speeds or with massive load capacitances.

You really don't need to know the theoretical minimum. You know the maximum already, and all you really need to know is "is the value I'd like to use safe for the IO pin" - i.e., does it draw less than 20mA?
For that you can ignore all the other values. All you care about is your resistance, the Vcc voltage, and the resultant current.
For instance, for a 900Ω resistor with 5V across it you get 5.6mA. You know for a fact that you can never have more than 5.6mA regardless of the resistance of the MOSFET - it can only go down from there.
5.6mA is below the recommended maximum of 20mA, so you're perfectly safe with that resistor.

Thanks but in the I2C-spec, they do the calculations with VOL and IOL. and not VIL.

http://www.ti.com/lit/an/slva689/slva689.pdf

VOL is only quoted at 20mA (I should have used 20mA above not 25, but that's a minor difference). You notice the figure of 0.9 for VOL in the datasheet is the same (near enough) as the final value I calculated above (0.94)...?

The official datahseet, does the calculation not with RDSON. But just simple by VOL and IOL

All are related.

It really doesn't matter what the minimum is, anyway, because you'd be insane to go so low. You should be focussing more on what the maximum is for your capacitance.

Also that is a TI document which assumes values quoted from a TI device's datasheet.

My capacitance is 800pf. So in standard modus, my MAX resistance is about 1.5K. I wanted to use something like 900 ohms

What frequency are you running the bus at?

Standard, so 100 kHz

I make it 1475.27kΩ maximum. A quick test: ignoring the IO pin's values completely, does your chosen resistor value with 5V across it result in less current than the IO pin can handle? I=V/R=5/900=5.6mA - so yes, 900Ω is fine for the IO pin.

But is it stable? I mean, is the drop over the "transistor in the I/O" low enough?

Since it's way below 20mA the answer is yes. Otherwise 20mA would not be 20mA.

The drop needs to be less than 0,4-0,5 volts

The drop doesn't "need" to be anything. The drop is a function of the current through the MOSFET. At 20mA the datasheet states that is no more than 0.9V. So at 5.6mA it will be considerably lower.

If it needs to be anything, it needs to be below lowest VIL for the peripherals.

And where are you getting this 0.4-0.5v range from anyway?

For reliable transfer; it needs to be below VIL. This is 0.3*VDD or 1,5. It suggested that this needs to be lower than 0,5V ( taking 1V margin)

That's a massive margin. A little overly cautious I would say. However, if 20mA is 0.9V, then 5.6mA is 0.9*(5.6/20)=0.25V. More than enough margin for anyone.


text:
Need help with using LED matrix with pushbuttons
I am building a small project that uses a pair of 8x8 LED matrix (driven by the MAX7219), a pair of SG90 servos, a HC-SR04 ultrasonic sensor, a 16x2 LCD (Hitachi HD44780 driver), some push buttons and all controlled with the Arduino Uno. All the components are powered using another usb port on my pc.
When I tried intergrating all the compenents, I noticed the LED matrix does not light up at all. I've decided to combine serveral basic code samples to test their interaction with eachother, where i noticed the use of pinMode to declare my pins for the push buttons will cause the LED matrix to stop working. Removing the section using // will get the led matrix(s) to work again.
Does anyone have any experience with this issue and can explain to me what causes this conflict? I've tried going through the LedControl documentation on the arduino page and I still could not understand what causes this issue.
/*

test build for debug

log:

LED Matrix : test code added, no issues
LCD Display: test code added, no issues
Sensor: test code added, serial clashed with LED Matrix. Working with disabled serial, Main build still not resolved.
Servo: test code added, no issues
Buttons: test code added, LED Matrix no longer light up. issue appears to be at the (pinMode) section when declaring buttons as inputs.

*/

//buttons

#include <Button.h>

const int positiveButtonPin = A1;
 int positiveButtonState = LOW;

const int negativeButtonPin = A2;
 int negativeButtonState = LOW;

// servo library setup
#include <Servo.h>
Servo servo1;
Servo servo2;

// lcd setup
#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 10, d5 = 9, d6 = 8, d7 = 7;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

//led matrix library setup
#include "LedControl.h"
LedControl lc=LedControl(2,1,0,2);  // Pins: DIN,CLK,CS, # of Display connected
unsigned long delayTime=200;  // Delay between Frames

// sensor setup
const int trigPin = 6;
const int echoPin = 5;
long duration;
int distance;

// led matrix arrays (test with 2 formats)

byte invader1a[] = {0x7C,0x7C,0x60,0x7C,0x7C,0x60,0x7C,0x7C};

byte invader1b[] = {0x78,0x7C,0x66,0x66,0x66,0x66,0x7C,0x78};

byte invader2a[] =
{
  B00100100, // First frame of invader #2
  B00100100,
  B01111110,
  B11011011,
  B11111111,
  B11111111,
  B10100101,
  B00100100
};

byte invader2b[] =
{
  B00100100, // Second frame of invader #2
  B10100101,
  B11111111,
  B11011011,
  B11111111,
  B01111110,
  B00100100,
  B01000010
};

void setup() {
  // put your setup code here, to run once:

//button setup
{
//  pinMode(positiveButtonState, INPUT);                    //         <----------------- THIS CAUSES ISSUE WITH LED MATRIX
//  pinMode(negativeButtonState, INPUT);
}

// servo setup
  servo1.attach(4);
  servo2.attach(3);

//sensor serial test code
// sensor setup
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
//  Serial.begin(9600);                                         //     <----------------- THIS CAUSES ISSUE WITH LED MATRIX, DISABLED

    //led matrix setup
  lc.shutdown(0,false);  // Wake up displays
  lc.shutdown(1,false);
  lc.setIntensity(0,2);  // Set intensity levels
  lc.setIntensity(1,2);
  lc.clearDisplay(0);  // Clear Displays
  lc.clearDisplay(1);

    //lcd hello world code
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");

}

//  Creating array strings

void sinvader1a()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0,i,invader1a[i]);
  }
}

void sinvader1b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(0,i,invader1b[i]);
  }
}

void sinvader2a()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2a[i]);
  }
}

void sinvader2b()
{
  for (int i = 0; i < 8; i++)
  {
    lc.setRow(1,i,invader2b[i]);
  }
}

void loop() {
  // put your main code here, to run repeatedly:

//servo test code
    // servo attach
    servo1.attach(4);
    servo2.attach(3);

     servo1.write (120);  // change angle here below. adjust until it looks like it's looking at user
  servo2.write (90);
  delay(250);
  servo1.write (90);
  servo2.write (120);
  delay(250);
// servo detach to reduce noise
servo1.detach();
servo2.detach();

// led matrix test code
    sinvader1a();
    delay(delayTime);
    sinvader2a();
    delay(delayTime);

    sinvader1b();
    delay(delayTime);
    sinvader2b();
    delay(delayTime);

    //lcd hello world code
    // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);

//sensor test code
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;

// no longer useful due to disabled serial
/*
if (distance<1000){
Serial.print("Distance: ");
Serial.println(distance);}
else {}
*/

}

please reduce your code to the minimal amount of code that still exhibits the undesired behaviour.

Consider the basic USB port is only required to supply 500mA.  It should be expected that a computer, to protect its self, would reduce the USB voltage if this current limit was violated.  2. All Arduino libraries are not compatible with one another.  Unless the library author was kind enough / thorough enough to document what hardware is used, the only way to tell is to look at the library source code.

You also did not specify which Arduino you were using.

It appears you are attempting to use the hardware UART for both talking to your MAX7221 or MAX7219:
LedControl lc=LedControl(2,1,0,2);

And for talking to, maybe, the SDK's serial monitor:
Serial.begin(9600);

There is only 1 UART on the Atmel processor used on an Arduino Uno.  Consider using a larger Arduino / processor where there are more UARTs on the processor.  Be aware that it may be necessary to re-write the library to use the alternative hardware on larger processors.
Also, there is an error in your code and it is causing you to think about it incorrectly:
The lines:
pinMode(positiveButtonState, INPUT);
pinMode(negativeButtonState, INPUT);

...interfere with the LED matrix because they are changing pin zero from a UART Receive to a GPIO Receive.  Likely you meant to type:
pinMode(positiveButtonPin, INPUT);
pinMode(negativeButtonPin, INPUT);