text:
Why use multiple filters output thousands value, use one or two filter can output normal value?
Problem
If the loop runs only one simulated pin and uses a filter, it will output normally (analog 1600~2200, filter 0~500), but creating an array to store multiple filtered simulated pin values will cause problems, and the output will be abnormal (10000~80000).

If analog read six sensors, and their value is 1600~2200.
It used the code below.
#include "EMGFilters.h"
#define SERIAL_TX_BUFFER_SIZE 4096 //修改串口接收缓冲区大小为2048
const int SensorInputPin[] = {A0, A1, A2, A3, A4, A5};
EMGFilters myFilter[6];
SAMPLE_FREQUENCY sampleRate = SAMPLE_FREQ_500HZ;
NOTCH_FREQUENCY humFreq = NOTCH_FREQ_50HZ;

void setup()
{

    for (int i = 0; i < 6; i++)
    {
        myFilter[i].init(sampleRate, humFreq, true, true, true);
    }
    Serial.begin(115200);
    Serial1.begin(250000);
    analogReadResolution(12);
}
void loop()
{
    long time = millis();
    int x[6] = {0,0,0,0,0,0};
    int analog[6] = {0,0,0,0,0,0};

    for (int index = 0; index < 6; index++)
    {
        //x[index] = myFilter[index].update(analogRead(SensorInputPin[index]));
        analog[index] = analogRead(SensorInputPin[index]);
    }
    while ((millis() - time) < 2)
    {
        delayMicroseconds(100);
    }
    Serial.printf("filter:%d %d %d %d %d %d analog:%d %d %d %d %d %d\n", x[0], x[1], x[2], x[3], x[4], x[5],analog[0],analog[1],analog[2],analog[3],analog[4],analog[5]);
    Serial1.printf("<%d,%d,%d,%d,%d,%d>", x[0], x[1], x[2], x[3], x[4], x[5]);
}

Change index<6 to index<2, and uncomment \\x[index] = myFilter[index].update(analogRead(SensorInputPin[index]));
It will be a normal output using two inputs and filters.

But changing index=0;index<2 to index=0;index<6 will be abnormal output.

If changing to index=3;index<4 or index=2;index<3...etc, it will be normal output:

Sketch:

XIAO MCU schematic in the HTML: https://files.seeedstudio.com/wiki/Seeeduino-XIAO/res/Seeeduino-XIAO-v1.0-SCH-191112.pdf
I don't have a sensor schematic.
Filter code: https://github.com/oymotion/EMGFilters/blob/master/EMGFilters.cpp
I hope each simulation output to look like the first Gif(normal output), what should I do to achieve this?

You need one filter per input...?

You didn't provide any context on what you are actually measuring, but I second Majenko with the guess, that you need one filter per analog input. Also I don't really understand your problem description. If this is because of the language barrier, maybe someone can help you, who speaks english better, and help with the wording of the question.

@Majwnko yes. Is there any way to solve this problem?

@chrisl I'm sorry, I may not be as fluent in English as my mother tongue. I hope each simulation output to look like the first Gif.

You currently use only one filter: myFilter. But you can define multiple filters in the same way and put them into an array for use in the for loop. Something like this: EMGFilters myFilters[6]; (define an array of 6 EMGFilters). In setup(): for(int i=0;i<6;i++) myFilters[i].init(sampleRate, humFreq, true, true, true);. And in the for loop: envelops[i * 6 + x] = square(myFilters[x].update(analogRead(SensorInputPin[x])));.

But I think you also need to think about what you are outputting. Currently you try to output the values of individual sensors in a new line each. The serial plotter interprets this as new datapoints of the same signal, though actually you have 6 data points, one for each signal. I think the Serial Plotter supports plotting multiple lines, when you print the datapoints in one line seperated by a space.

@chrisl I have tried to create a filter for the simulated output, but the output is still abnormal(The post has been updated and the picture has been uploaded). The loop function outputs normally only if it has only one line of instructionsquare(myFilter.update(analogRead(SensorInputPin[per input]))). I don't understand why only one line should output normally.

@chrisl I found using third analog input case error, what do you think is the reason?   I measured the third analog input separately and found no problems. It seems that as long as I use the third one, no matter what the third analog pin is, it producing thousands of values. The issue has been updated.

What Arduino board you are using? You are assuming that each integer is 2-byte long, this is true if you are using an Arduino Uno, but it will not be the case if you are using an STM32 or SAMD-based Arduino, for those, an Int is 4-bytes.

@chrisl Hello, I reconstructed the post.

@hcheung OK. I have been updated.

This is a bug in the filter library you are using. It has already been
reported (by you, maybe?).
As Majenko and chrisl suggested in comments, the crux of the problem is
that you need one filter per input channel. Using multiple instances of
EMGFilters seems like the obvious solution. Alas, the library keeps
the filter state in global variables, which essentially means your six
filter objects all reference the same actual filter.

Yes. It's my Issue. How do I prevent referencing global variables of the same filter? Need to reference "EMGFilters1.h","EMGFilters2.h"...etc?

@C.SH.K: No. You should fix the library, or wait for the authors to fix it. If you want to do it yourself, just turn the filter state into instance data. C.f. my comment to your issue.

@C.SH.K: Or you may use the branch from this pull request.

Thank you! Solved the immediate problem!

Image Image2After using your file, some pins have a strange place, some emG output tens of thousands of values, some normal output. Before, with the raw filter code, it would print like thisBefore index=0;index<1...etc

Oh. Just bad sensor contactThe sensor AREA I bought is too large, so it is not easy for the dry electrode to fully contact the skin when touching the arm, which is prone to baseline drift.


text:
Joystick reading erroneous values
Under normal operation, the value of a joystick's ADC range on my board is from 0 to 1023 (10-bits). However, my graph for either axis is not continuous. Rather, there is more than one min and maximum for both axis. I am running this thread on a MSP432P401R however the code isn't any different than an Arduino.
int jumpFlag;
int backwardsFlag;
int forwardsFlag;
int selPin = P5_1; //Select digital pin location
int xOutPin = A14;
int yOutPin = A13;

void setupPlayerActions() {
  pinMode(selPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(selPin),jumpISR,RISING);
  //pinMode(xOutPin, ); //Analog X pin setup
  //pinMode(xOutPin, ); //Analog Y pin setup
}

void jumpISR() {
  Serial.println("Jump Detected!");
  jumpFlag = 1;
}

void loopPlayerActions() {
  int x_adc_val, y_adc_val;
  int leftThreshold=50,rightThreshold=900;
  float x_volt, y_volt;
  x_adc_val = analogRead(xOutPin);
  y_adc_val = analogRead(yOutPin);
  x_volt = ( ( x_adc_val ));  /*Convert digital value to voltage */
  y_volt = ( ( y_adc_val));  /*Convert digital value to voltage */
  if (x_volt < leftThreshold){
    Serial.println("Move Backwards");
  }
  else if (x_volt < rightThreshold){
    Serial.println("Move Forwards");
  }
  Serial.println("X_Voltage = ");
  Serial.print(x_volt);
  Serial.print("\t");
  //Serial.print("Y_Voltage = ");
  //Serial.println(y_volt);
  delay(100);

  //delay(250);
}

The graph goes to zero for all positive x and y integers however it briefly reaches a maximum past a small value on the -x and -y axis then sinks to about ~420. What could be causing this?

Re “if (x_volt < rightThreshold)”: do you mean if (x_volt > rightThreshold)?

@EdgarBonet will not change the fact the graph of the potentiometer is not linear

Can you show the graph?

it could be a problem of analogRead implementation or the ADC itself. for example for AVR it is recommended to wait a little or do a dummy reading between consequent readings on the same ADC.

A 10 bit ADC may not have 10 bits of resolution for a given sample.  It might only have 5 or 6 bits due to random noise and other factors.  Consult the chip manufactures specifications / recommendations if you need a specific number.
What can be done?

If response time is not an issue, consider averaging the ADC reading.  A common coding practice is to use an exponential moving average.
Consider a better ADC.  Many times a dedicated ADC chip (not integrated into a processor) will have better specifications.

For more in depth reading this NXP (aka: Motorola, Freescale) application note discusses "How to Increase the Analog-to-Digital
Converter Accuracy in an Application".

source: Stack Exchange

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

sort: votes


text:
How can I detect a disconnected pin?
I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed.
I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND?
Please bear in mind that I'm pretty new to all of this.

Please state whether these pins are going to be used for input or output. If output, what are they driving? eg. LEDs. If input, what is the device you are reading from?

I am not really sure if I should use them as an input or output. The idea is that it triggers a software event and not a physical event (hardware). All I really need is a signal to the computer (though USB for now) that says that the cable is disconnected.

The way to do this, since there is no digital value in between HIGH and LOW, is to actively create a signal on the pin you can recognise.  Note that if the signal coming in to the pin is a datastream (a sequence of HIGH and LOW) that runs all the time this may not work reliably, but it's good for things like buttons and other simple sensors.
Any signal on a wire has a drive strength.  This is basically how powerful the signal is and how good it is at overriding other things happening on the same wire.  It is closely related to the output impedance of the source (what is sending the signal).  For things like buttons and switches that is basically the value of the pullup resistor used.
To actively sense if a pin is disconnected or not you need to temporarily connect it to a known signal level at the same time as it's connected to the wire (or not connected if it happens to be not connected).  This known signal level has to be of a weaker drive than the source signal by several orders of magnitude.  This ensures that if you try superimposing your test signal over the incoming signal the incoming signal swamps out the test signal and you don't see it at all.  For instance, if your source has 10KΩ impedance (say a button with 10KΩ pullup resistor) then a test signal with source impedance of 1MΩ would be suitable.
Each pin to be tested can be connected to its own 1MΩ (in this example) resistor, and those resistors are all connected to the same extra IO pin:

In this example pin D2 is the test pin, and pins D4-D7 are your inputs.
So under normal circumstances pin D2 is set as an input and completely ignored.  When you come to test the pins, though, you set it as an output.
You then set D2 to be HIGH and read each of D4 through D7.  Any that read as HIGH are candidates for being not connected.
You then set D2 to be LOW and read the pins that read HIGH before.  Any that now read as LOW are disconnected.
You then set D2 back to being an input again so it doesn't interfere with normal operations.

If you just want to know if current is flowing in a wire you can use what is called a shunt resistor.  This is a small resistor (maybe 1Ω) that is placed in-line with the wire and you measure the voltage (using Arduino analog inputs) at both sides of the resistor.  The voltage dropped across the resistor is directly proportional to the current flowing through it thanks to Ohm's Law:

I=V/R

For instance:

If the voltage read by A1 should be 5V (the voltage the wire is connected to) and the voltage read by A0 should be 4.93V, the voltage dropped by the resistor would be 5-4.93 = 0.07v.  With the 1Ω resistor the current would be 0.07/1 = 0.07A, or 70mA.
With the wire at OUT disconnected there will be zero current flowing since there is no circuit.  So re-arranging the formula above we can prove that we can tell it's disconnected.
If I=V/R then V = RI.  Therefore V = 1Ω × 0A = 0V.  So the voltage dropped across the resistor would be 0V, so A0 and A1 would be equal (discounting any noise). A0 and A1 would both read 5V.  Similarly, if the wire IN was disconnected instead then A0 and A1 would both read 0V.
For sensing higher currents you use a smaller resistance, and for sensing smaller currents you use a larger resistance - this allows for a voltage drop to be generated that is within a suitable range for the sensitivity of the ADC doing the reading.  For the Arduino that's a 10-bit ADC, so it can sense (with a 5V VREF) 5/1024=4.882813mV per LSB.
Note that if you are working with voltages above that at which the Arduino operates you will need to separate or otherwise scale those voltages.  There are special devices designed especially for this task called high side current shunt amplifiers.  They also allow you to use a smaller resistance than you would otherwise need which is less intrusive to your circuit (less voltage drop).

Alternatively, if this is a digital input, you can just use a pull-up or pull-down resistor to give the input pin a default value. Let's say you use a pull-up resistor to make the default high. Then you connect a low cable to this input so that the input reads low. Now, if the cable goes high or if it is disconnected, you get a high value in the input pin.
I know this was not quite what you were asking but maybe such a solution could help with your original problem. In my case, I have a flame detection module that gives low output by default and turns high when there is a flame. I don't want to miss the flame because of my cable disconnecting, so I use a pull-up resistor that will make the input high not only when there is a flame, but also when there is a disconnection. This way I make sure that I don't miss a fire because of the sensor cable disconnecting.

You can connect all pins through a 1M resistor to a rail. Once in a while you set all your outputs to inputs and toggle the rail HIGH and LOW, if the inputs are HIGH and LOW in the sequence you toggled the rail, there is no wire. The same question was asked at Arduino Forums so read this thread.
This question's answer was provided by johnwasser@forum.arduino.cc.

Thank you, but this looks way more complecated than it should be for my purpose. I am not using any external devices and/or sensors. What I am looking for is a way to detect if current is flowing from 5V to GND (cable connected) or not (cable disconnected).
You could think of it as a weird electronic necklace that will make sound once it is disconnected. Now how do I determine when to make the noise?

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


text:
Servos stop after a while in case of 8 servo motor control
I recently purchased 10 units of MG996R servo motor and the 16 channel 12-bit PWM/Servo driver from Adafruit for a small project. I confirmed that all of my servos are functional and that my code is correct. My issue is that there seems to be a limit on the number of servos I can run. With 4AA batteries, I can power about 3 of the MG996R servos. Starting with the 4th one, they stop moving. I supposed that the current drawn from the servos is high, so I tried powering the servos by providing two 4AA batteries in parallel (8AA). This appeared to have increased the number of servos I can run. But after a few minutes, the servos stop responding and I have to disconnect the power for a while before the servos respond again. I read on Adafruit that I may need to add a capacitor to the PWM/servo drive if I have multiple servos. Is this my problem or I just need to provide more power? Why do the servos seem to respond initially but stop moving after a while? Thanks in advance.

If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.
However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

Not enough power.
Something is overheating.
Code problem.

Use a decent transformer with more than enough amps to power your motors.
Use your nose, does something smell hot?  If you use your fingers you will get burnt!
We can't fix invisible code.

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


text:
Stepper motor just oscillates with arduino and L293D
I am trying to control my stepper motor using arduino duemilanove, with L293D as H-bridge. I use a NEMA 17, stepper motor 42BYGH-036B I have used both the default example program from arduino IDE, and also from; http://www.electronicshub.org/stepper-motor-control-using-arduino/
But in both cases, The motor just oscillates, without going for rotation.
The following is the connection, I have been using;


text:
Ultrasonic sensor showing weird reading
When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below
#include <NewPing.h>
#include <AFMotor.h> //import your motor shield library

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
AF_DCMotor motor2(2, MOTOR12_8KHZ);

int distance;

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

void loop() {
  delay(50);
  distance = sonar.ping_cm(); // start the scan
  delay(20);
  if (distance < 2) {
   Serial.println("Close Obstacle detected!" );
   Serial.println("Obstacle Details:");
   Serial.print("Distance From Robot is " );
   Serial.print(distance);
   Serial.print( " CM!");// print out the distance in centimeters.
   delay(10);
   Serial.println (" The obstacle is declared a threat due to close distance. ");
   Serial.println (" Turning !");
   motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
   motor2.run(BACKWARD);

}
  else {
   Serial.println("No obstacle detected. going forward");
   delay(15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
   motor2.run(FORWARD);
  }
}

Test code for sensor which worked:-
#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Tell me whats wrong here

Motor Shield used below
Wiring of sensor is connected to Arduino below the shield

replace the whole  if-else loop with Serial.print(distance); .... what does it print now?

The NewPing library returns zero when there is no echo detected. And 2 cm may be too short. If I remember correctly, this is the minimal distance that these sensors can detect.

yes i tried serial.print and showed some reading. But now it goes to 1000cm :|

Try with
unsigned int distance;

Instead of
int distance;

It could also be the motor shield that is using the same pins as your ultrasonic sensor.

Thanks but it didn't work. Using serial.print() instead of distance variable helped.

And your sure that your motor shield is not conflicting ? What make/model is it ?

its like the one in dk electronics. Now again the sensor is showing 0cm so i think you are right. I have done sensor wiring under the shield so is that a good method?

Not sure about the wiring without seeing it. What I would recommend is trying your sketch without the motor shield.

I tried the test code without motor shield and it worked but doesnt work with motor shield on it.

According to this schematic pin 11 and 12 are used by the motor shield: https://forum.arduino.cc/index.php?action=dlattach;topic=211225.0;attach=71519

You could try using A0 and A1 for the sensor. In theory should work. If not you will need to use an Arduino with more I/O like the Arduino Mega 2560

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


text:
How to publish on Pubnub with node mcu?
I have node mcu and i am trying to use the example code on github and pubnub blog to send a msg as an experiment but can't figure how to do it.
I used 2 example as the reference - https://github.com/pubnub/arduino , https://www.pubnub.com/docs/arduino/data-streams-publish-and-subscribe
Here is the code which i have. I modified it to include some libraries and my API keys. Let me know what changes i have to make:-
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

String pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
String subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";
String pubchannel = "sec-c-NmFiYjliODYtMTc3Mi00YTMzLTg0OWMtMDgzYjE2ZGUwNzg5";

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Error:-
node_mcu_test_code:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

node_mcu_test_code:54:14: error: 'class PubSubClient' has no member named 'stop'

     sclient->stop();

              ^

exit status 1
no matching function for call to 'PubNub::begin(String&, String&)'

what is subchannel? pubchannel?

#include <PubSubClient.h> - why? no demos or docs say you need to do that

 is what I found in old forums so put that just for checking. I specified sub and pubchannel with API key. If not like that then how to do it.

is what I found in old forums so put that just for checking don't add things without knowing what they do

also, you've not declared a variable called subchannel ... yet you try to use a variable called subchannel ... which is why you get an error that states error: 'subchannel' was not declared in this scope - because it isn't

How to declare subchannel? Is it the name of channel which we subscribe or secret API key? I tried putting subchannel name but didn't work. My channel name is 'Demo Keyset'

The pubchannel and subchannel can be defined as any values in char variable.
Here is the right code:-
const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

Then the error disappeared


text:
Does direct port access interfere with PWM?
I think I've scoured the SE for questions about PWM, and fast digitalWrite etc, but I didn't see this point addressed.
I need to use direct writes to some digital pins. Some of the pins on the port are using analogWrite/PWM, though not the pins I'm accessing digitally.
In the digitalWrite function the Arduino core checks to see if PWM is in use and disables it if a digital write is attempted. Since the pins here are isolated -- no digital writes to PWM pins -- is this a needed step?
The reason I ask is that when accessing a port directly, as in PORTD |= (PORTD & mask) | somebit, you are in fact writing to the pins being used for PWM, you just aren't writing changed bits.
Am I overthinking this? Is it 'PWM-safe' to use direct port outputs on the neighbor pins?

Hint: Why not use a library for that? For instance, https://github.com/mikaelpatel/Arduino-GPIO

@MikaelPatel - I'll look at that, thanks. I don't expect there to be any magic there, but I'm always happy to be surprised.

A timer interrupt will be periodically toggling the PWM bit and might do so between your port read and port write.
The easy solution is to turn off interrupts during the read/modify/write portion of your port update sequence. This could cause a stretched PWM cycle. If you don't turn it off, you'd just glitch the PWM - creating an extra, short cycle. Which one is worse for your PWM recipient?
A better solution might be to to watch the port for the PWM bit to change, then jump in right afterward and make your port update. You could do his in either a blocking or a non-blocking manner.
Update:

Watching the PWM bits seems as if it would be fairly slow, which
  somewhat defeats the purpose of the direct port writes.

Yes, it's less than ideal. There's a tradeoff here. Can your PWM consumer tolerate the potential occasional glitch, instead?
To be complete, there are a number of motivations to use direct I/O:

Smaller code;
Less I/O skew with multiple I/Os, or zero skew if the I/Os are in the same port;
Less execution time on a time-critical path;
Precise output timing;

among others. Those software solutions won't help much in any of those cases.
Can you reassign your output to another pin on a different port, avoiding the whole problem? That might be better than any of the "solutions". Adding hardware might accomplish the same thing - perhaps moving just the PWM to an ATtiny, for example.
Update 2:

This seems so baked into the structure of the Arduino... does
  digitalWrite() itself actually overcome this?

It "addresses" it - overcomes it? As is so often the case, "that depends".
Here is the the source-code to digitalWrite() from: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino /wiring_digital.c (on a Mac; the top-level folder or two will be different on Windows):
void digitalWrite(uint8_t pin, uint8_t val)
{
    uint8_t timer = digitalPinToTimer(pin);
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    volatile uint8_t *out;

    if (port == NOT_A_PIN) return;

    // If the pin that support PWM output, we need to turn it off
    // before doing a digital write.
    if (timer != NOT_ON_TIMER) turnOffPWM(timer);

    out = portOutputRegister(port);

    uint8_t oldSREG = SREG;
    cli();

    if (val == LOW) {
        *out &= ~bit;
    } else {
        *out |= bit;
    }

    SREG = oldSREG;
}

Notice that the interrupts are saved and restored around the read/modify/write of the port register. So digitalWrite() already addresses the possibility. This method will stretch one phase of an occasional PWM pulse by a few microseconds.
Alternatively, ignoring the possibility of a collision and having one occur, seems more severe: the pulse could be begun or ended prematurely. This occurrence will take longer - the rest of the disturbed phase - to get back in sync.
So the criterion for how to manage x becomes "Which way has the lesser - or more tolerable - consequence for your PWM consumer?"

That makes sense, thanks. Watching the PWM bits seems as if it would be fairly slow, which somewhat defeats the purpose of the direct port writes. I'm going to have to think about which of the alternatives is worse, as you ask.

Thanks for the update. I am indeed going for minimum skew. I can't change the ports used, they're part of a shield. Since these PWMs are 95-99% on, I think the risk of glitching is low enough that I'll just bang through. Curious, though. This seems so baked into the structure of the Arduino... does digitalWrite() itself actually overcome this?

Nice information. I can see that cli() and friends would be somewhat safer, and in fact knowing that PWM is in use removes the need to save and restore the SREG (interrupts must be on). I also guess that if the PWM is at 97% there's only a 3% chance that ignoring interrupts will introduce a meaningful glitch. Sigh. I guess I'll experiment once I have all the hardware.


text:
Procedure for changing frequency of Nano or similar
I need to get interrupts at one of three specific rates: 1920, 2000, and 2400 per sec, at a fairly high precision (~10 ppm). I've asked about this on Electronics but I think here might be more appropriate.
I can't use the standard 16MHz with internal timers, since 16MHz / 2400 (for example) gives 66666.666... counts.
I would use an external standard, but I don't seem to be able to find one that fits the need. Something small and precise at 48KHz / 96KHz etc would be fine.
Alternatively, I could swap the crystal / resonator for one running at 18.432MHz, which divides evenly by those freqs and shouldn't tax a 328p. Can I even do that on a Nano, or some clone / comparable, with the required 10ppm?
-- extra removed --

Sure you can swap the crystal. The maximum is 20MHz, so 18.whatever is well within the capabilities. You'll have to adjust the board settings to match of course (F_CPU).

Whoo, 10 ppm, quite a challenge! Did you consider the initial precision, the influence of temperature and voltage/current, drift, ageing? You might need something better than a simple crystal, for example an oven-controlled crystal oscillator.

Oh, and of course the jitter due to different numbers of clocks for instructions, leading to different interrupt latency.

@thebusybee - I know 10ppm is asking a lot. If I could find a reasonably priced TXCO at 48 or 96 KHz in a small package I'd do that for sure. As for jitter, a small amount is OK in exchange for longer-term (~30 msec) accuracy.

You could use a TXCO of higher frequency and divide it. -- All this seems to call for a more hardware based solution, perhaps a CPLD or FPGA. Why do you need such an accuracy?

You could use an internal timer.
You are using interrupts, and you are probably aware that interrupt
handling inevitably incurs some jitter. Thus, if you do not mind an
extra single CPU cycle of jitter, you could reconfigure the timer on
each interrupt in order to control the average interrupt period.
Here is how I would do it, with Timer 1 running in normal mode (CTC mode
would require an extra operation):
// Interrupt period in units of 1/2^16 CPU cycles.
// For 2.4 kHz, that is 16000/2.4*65536 = 436906666.666...
uint32_t interrupt_period = 436906667;

ISR(TIMER1_COMPA_vect) {
    // Update the timer for the next interrupt.
    static uint32_t accumulator;
    accumulator += interrupt_period;
    OCR1A = accumulator >> 16;

    // The periodic task goes here...
}

void setup() {
    // Configure Timer 1.
    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS10);    // clock @ F_CPU
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt
}

void loop(){}

Here, accumulator is a 32-bit extension of the timer's output compare
register. The upper 16 bits are copied into the actual timer
register, whereas the lower 16 bits ensure that the accumulated
error never exceeds one cycle.
This way of updating the timer should only take about 2 µs per
interrupt. It is a constant time operation, so it doesn't add extra
jitter to your task, other than the single cycle of jitter induced by
rounding to the next edge of the CPU clock.
There are a couple of caveats though:

This can only work on an Arduino clocked off a crystal (e.g., a
Micro). Those clocked off a ceramic resonator (Uno...) would be too
unstable in frequency to meet your 10 ppm requirement.
Even though a crystal is more than stable enough to meet your
requirement, it is unlikely to be accurate enough. You will then need
to calibrate it, e.g. by outputting a PWM signal (analogWrite())
into a frequency meter. Then adjust the variable interrupt_period
according to the measured clock frequency.

Edit: I added the timer configuration to the code, and here comes an
explanation of how this code works.
Think of the timer as a digital alarm clock. It measures time in units
of CPU cycles instead of hours and minutes. It rolls over every
216 cycles instead of every 1440 minutes. But it is
otherwise a regular alarm clock. It has two alarms called “COMPA” and
“COMPB”, but you only need one. In order to perform a periodic task, you
turn the alarm on and, every time it rings, you advance the alarm time
by the required period. That is, you set:
new alarm time = previous alarm time + task period
Note that the addition has to be computed modulo the roll-over period of
your clock : 1440 minutes for a regular alarm clock,
216 cycles for the timer. Thankfully, the arithmetics on
unsigned numbers do this automatically.
Now, lets say the task period is 43 minutes and 35 seconds,
but the alarm can only be set with a resolution of one minute. What you
can do is compute the “ideal” alarm time on paper (this is the
accumulator variable), and truncate it to the resolution of the clock
when setting the alarm. If you start at 00:00:00, you will compute the
next ideal time to be 00:43:35 and set the alarm to 00:43. When it
rings, you add the period to the previously computed time, you get
01:27:10, and you set the alarm to 01:27. Etc. Here is the list of the
alarm times as computed and as actually set on the clock:
computed  set
───────────────
00:00:00  00:00
00:43:35  00:43
01:27:10  01:27
02:10:45  02:10
...

Note that, even though the limited resolution of the alarm setting
creates some jitter, the average task period is still exactly
43 minutes and 35 seconds.
The code I wrote above does exactly the same. The “ideal” alarm time is
computed as a fractional number of CPU cycles, written down in binary
fixed point, with 16-bits on each side of the radix point. In hex, it is
1A0A.AAAB CPU cycles. The computed alarm times are multiples of this
period, whereas the times actually written to OCR1A are the same
truncated to an integer:
computed   set
───────────────
1A0A.AAAB  1A0A
3415.5556  3415
4E20.0001  4E20
682A.AAAC  682A
...

Thanks much for this, but, sorry, I don't get how it works. I gather there's some initial setting up of the counter that you don't show? It seems that we're outputting wildly variable values to OCR1A: 1A0A, 3415, 4E20, 682A etc. What's going on?

@JimMack: See expanded answer.

Very nice. I knew that somehow I should implement Bresenham's algorithm to average away the error, but I couldn't see a way to do it. I'll ask another question based on this, to try to solve another issue.


text:
Addressable LEDs using SM16704
I've been asked to interface with some LED strips that use SM16704 pixel chips.
A site search here doesn't show any mentions of this chip, so I wonder if anyone knows if they're compatible with the more common ones like WS281x and can be addressed using FastLED or other library?
Edit:
Here's the datasheet for the -PB version of the chip. I can't find one for a plain 16704 but I don't think the protocol is any different.

the timing is quite different ... you could rewrite the library

The best data I can find says that this chip / protocol is compatible with the WS2813 and should require only a minor tweak, if any.


text:
When does a pre/post increment occur?
Editing here to clarify. The headline asks the question but the example given was not ideal. This was a more general Q than about the example code.
Compilers have sequence points, places where you can be assured that the equations have been evaluated etc and no lingering effects will occur: the compilation is stable. When I couldn't test the original example I went looking for theory, and came across SE/SO posts where there was some discussion about issues like:
   int a = 1;
   int b = a++ - a++ + a++;

What would you expect the values of a and b to be after this? It turns out it hinges on whether the arithmetic operators are sequence points. Apparently this was not well settled in early versions of C, and in other languages (like Java) the results may differ yet again.
I now understand that an expression like (item++ > max) contains no sequence points -- the > operator does not trigger evaluation, but assignment operators and some arithmetic operators do.
//================================
Original Q:
I've read several Qs here concerning x++ vs ++x but I don't see this specific case. I'm still something of a C novice here.
Do these two code fragments do the same thing?
  // assume itemNum == maxItem on entry

if (++itemNum > maxItem) itemNum = 0;

if (itemNum++ > maxItem) itemNum = 0;

I gather that when the increment takes effect depends on the occurrence a 'sequence point' but I don't know if the comparison creates such an inflection.

why don't you just write a short sketch that prints out the value of itemNum and ++itemNum, then itemNum and itemNum++

@jsotola - Didn't have any platform to test on. As I comment elsewhere, this is more a question about what constitutes a 'sequence point' - about when the ++ occurs than what ++ is.

Both ++x and x++ increment the value of x. The difference is whether you evaluate the value of x in your expression (formula) before or after incrementing it.
int x1 = 0;
int y1 = 0;

int x2 = x1++; //Post-increment: Move current value of x1 (0) to x2, THEN increment x1
int y2 = ++y1; //Pre-increment: Increment y1. Then move the NEW value of y1 (1) to y2.

In the above, x2 will be 0, and y2 will be 1.
The same logic applies to your if expression. If you use pre-increment, your if statement makes its decision on the new value after incrementing it.
If you use post-increment, the if statement makes its decision based on the value before it's incremented.

I do understand the concept of pre/post ++, it just wasn't / isn't clear to me what constitutes a 'sequence point' which forces the increment to occur. This apparently has changed with different versions of C.

I am not aware of any differences in the handling of pre and post increment/decrement operators in C. Where are you getting that information?

There are several discussions here on the topic. Here's one: https://stackoverflow.com/questions/4865599/post-increment-with-respect-to-sequence-points

@JimMack But where is the description of how it's different in different versions of C?

Look at the discussion under https://stackoverflow.com/questions/4445706/ This is about C++, not C, but it's where I got the notion


text:
How to read the busy flag on LCD?
I have a standard 16x2 LCD screen and I have it hooked up to my Arduino UNO via a I2C backpack (4-bit mode).
Since I want to learn about the lcd at a lower level I’ve decided not to use the LCD library and instead use the Wire library.
I have writing to the LCD working fine so now I want to understand how to read from it. I thought trying to read the busy flag was a good start.  (I currently delay() after to the LCD which seems to be the most popular solution).
According to the LCD documentation it requires that the RS bit be set to 0 and RW bit to 1. I have a attached the code below.  For some reason it always reads 0x2.
I also read the busy flag right after writing to the screen and it always screws up every other letter.  E.g. if I write 'k' twice to the screen, the first 'k' shows up fine, but the second time it becomes a 'f'.  I am suspecting writing to the LCD before reading is screwing up the data processing.  If I don't attempt to read the flag, all the characters show up correctly.
Here is the code.  Any help would be appreciated.  Thank you!
#define ENABLE (1 << 2)
#define BACKLIGHT (1 << 3)

#define READ (1 << 1)

byte readReq = BACKLIGHT | ENABLE | READ;
Wire.beginTransmission(0x3F);
Wire.write(readReq);
Wire.write(readReq & ~ENABLE);// write 1st nibble
Wire.write(readReq);
Wire.write(readReq & ~ENABLE); //write 2nd nibble

Wire.endTransmission();

Wire.requestFrom(0x3F, 2);

while (Wire.available() < 2) {}

byte firstNibble = Wire.read(); //always reads 0x2
byte secondNibble = Wire.read(); //always reads 0x2
Serial.println(firstNibble, HEX);
Serial.println(secondNibble, HEX);

What is this I2C backpack thing you are using?

Not the exact model, but something like this: https://goo.gl/images/ftHFNx

Does it have the same chip on it?

It is a PCF8574AT


text:
ESP32 USB HID/MIDI library (not the BLE one)

I couldn't find any library to use an "old" ESP32 (not the new ESP32-S2) as an HID connected physicaly to the Usb port (not over BLE pairing) to send keystrokes to the PC ...
Is there any solution? Any code example, so far?
Thanks in advance!

it is unclear what you are asking ... MIDI is used for musical instruments

Esp32 doesn't have usb.

@jsotola i am trying to send keystrokes to the PC by plugging the (old) ESP32 on to the Usb port

The ESP32 doesn't have USB. You can't do USB communication. All it has is (like the UNO) a USB to UART interface chip. Unlike the UNO this is not programmable (more like a cheap Chinese knock-off UNO clone in that respect).
You would need to couple it with a microcontroller that has USB and program hat to be your USB interface and communicate with it over some other communication medium, such as UART or I2C.


text:
Current Draw for LED Projects
I am working on a project with LED strips that would consume 12V and 20A. The problem is that the household wall outlet limitation is 15A, and 20A current draw would potentially start a fire. I have been searching for tutorials of large current LED project, and none of them really addresses the current draw problem.
I found an adequate power supply. It is Meanwell RSP-320-12. http://www.mouser.com/ProductDetail/Mean-Well/RSP-320-12/?qs=Uzd%2Fwh%252bZzhBChmc2p7rgKQ%3D%3D.
How can I make it work with a 15A wall outlet limitation?
Thanks in advance!

When you say 15V in your last sentence, do you actually mean 15A?

only if you used a linear power supply, which nobody uses for hi-power LEDs...

Drawing 20A on 12V means 240W which on 110V is 1A and a bit (a bit more once you consider efficiency of the conversion).
The spec sheet of the power supply you linked says that it will draw 2.7A max on a 115V input.
The power supply will convert the high voltage low amps into low voltage high amps.

The power outlet is either 110V AC or 230/240V AC. Ignoring modern Switch-mode power supplies, to convert the power outlet voltage down to 12V, you first need to step down the voltage (using a transformer) and then rectify the AC voltage to DC voltage.
Working backwards, to get 12V DC you need: 12 x square_root(2) = 16.97 V AC.
A transformer can step down AC voltage. For example it can step down 110V AC down to 16.97 V AC.
The formula for an ideal transformer is:
V x i (primary side) = V x i (secondary side)

And using this to find the current draw on the primary side:
110 x i (primary side) = 16.97 x 20 (secondary side)

i (primary side) = 16.97 x 20 / 110

i (primary side) = 3.08 A

So if you have an outlet that provides 110 V AC then an ideal AC-DC converter would draw 3.08 A.

12Vp-p is 8.485Vrms, not 16.97Vrms. You need to divide, not multiply.

@Majenko you are correct for a bridge rectifier circuit, however my calculations are correct for a full wave rectifier. http://www.sowter.co.uk/rectifier-transformer-calculation.php

People still use those...? For that matter, people still use transformers...?!


text:
LCD is not printing strings, only integers with Arduino
As mentioned in the title I'm facing a problem in printing strings in the LCD. It's printing actually weird characters.
#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);

  lcd.print("hello, world!");
}
void loop() {

 lcd.setCursor(0, 1);
  lcd.print(millis()/500);
}

You can find the output of the LCD in the picture below:

You've goofed up the hardware side.

Agreed - it certainly hasn't initialized properly - it's in 16x1 mode not 16x2 mode, which means the 16x2 instruction never got through, so most likely you have your data lines in the wrong order.

And that looks like some pretty shoddy soldering. That's a good example of go home and do it again.

Whenever I use an LCD display I make sure to use the I2C backpack.  It takes actual effort to hook it up wrong if you use them.  So if this were me, I would desolder all those pins and get one.
Here is a good description of how they work:
https://learn.adafruit.com/i2c-spi-lcd-backpack/overview

Exactly my thought. It is possible to do the wiring and protocol yourself, but it will require a lot of pins and probably cause you some headaches.


text:
Serial.print() is slower than it should be
I'm trying to use Arduino as a DAQ but the Serial.print() is not working as fast as I expected. How many bits are sent if you are using a int, because if I use a uint8_t, it's taking the same amount of time? How I could improve the speed of the Serial.print()? I'm already working at 115200 baud.

What does it mean "slow" how many ms?

Its take about 204 us and  its supposed to go less than that but know I know it's sending ASCII so it's sending more bits than I thought.

How many channels are you acquiring? See my modified answer for more comments

I'm already taking samples at  50 kHz and the resolution is enough and Im acquiring data from all 6 analog pins. And what version of "timerone.h" is better?

Please see https://github.com/mikaelpatel/Cosa/blob/master/examples/Benchmarks/CosaBenchmarkDataLogger/CosaBenchmarkDataLogger.ino this might give some hints on how to boost the performance.

What Arduino board are you using? 50 kHz sample rate is much higher than AVR based Arduino boards can achieve. Typical peak performance is 9 K samples per second (10 bit).

if the outbound serial buffer is already full, serial.print and serial.write will wait for there to be space. Does it run faster if you call Serial.flush() beforehand?

I need a sample rate of 6 kHz

OK, so that means you need to sample and send every 1/6000 seconds (167 µs).
I have a lengthy discussion about the ADC hardware. Amongst other things is a table of conversion times for the different ADC prescalers, assuming a 16 MHz clock:
Prescaler
    2    * 13 * 1/16E6  = 0.000001625 (  1.625 µs)
    4    * 13 * 1/16E6  = 0.00000325  (  3.25  µs)
    8    * 13 * 1/16E6  = 0.0000065   (  6.5   µs)
   16    * 13 * 1/16E6  = 0.000013    ( 13     µs)
   32    * 13 * 1/16E6  = 0.000026    ( 26     µs)
   64    * 13 * 1/16E6  = 0.000052    ( 52     µs)
  128    * 13 * 1/16E6  = 0.000104    (104     µs)

If you go for maximum resolution (10 bits) you need a prescaler of 128, which takes 104 µs. The number of conversions you can do a second (taking the inverse of the above) is:
Prescaler  Conversions/sec
  2           615,385
  4           307,692
  8           153,846
 16            76,923
 32            38,462
 64            19,231
128             9,615

You also need to take into account the transmission time. At 115200 baud you can transmit one byte every 1/11520 seconds (86.8 µs) so therefore two bytes (16 bits) would take 173.6 µs.
If you sample then transmit you will therefore take, per sample:
104 + 174 = 278 µs

This is too slow if you want to achieve it inside 167 µs.

You can sample asynchronously (in the background) so you transmit one sample while taking the next one, but you are still limited by the transmission speed of serial, so it would still take 174 µs per sample.
In fact, fiddling with the prescaler isn't really the issue here because the serial transmission time is the limiting factor.
Forget about the ADC and how it works for the moment. At 115200 baud you can't transmit 2 x 6000 bytes per second. That is simply because the maximum is 11520 bytes per second.

Actually, the serial library (of course I'm speaking about the hardware one) sends the data asynchronously, in the serial ISR. So serial transmission and main loop (with the ADC acquisition) can be considered as two "parallel" tasks. So the sample time will be max(104,174), so 174us. Of course there is a bit of overhead (go to ISR, exit from ISR, perform ISR) but as a first approximation the sample rate here is not the sum of the two, but the highest

You are quite right, of course! (What was I thinking when I wrote that?) - still we are both in agreement that the limiting factor is the baud rate. The Arduino hardware is capable of faster baud rates, I'm not sure about the receiving side.

By not using Serial.print?
Serial.print will format the number as a string of ASCII characters. The number of characters depends on the size of the number. Yes, that is very wasteful.
If you are sending values between 0 and 255 (uint8_t) you can just send the raw value as a single ASCII character, since there are 256 of those.
Serial.write(myVal);

For anything greater than 255, i.e., you want to send an int or uint16_t then you will have to come up with some better way. You can't send one byte for the full value, so you would have to send it as two bytes:
Serial.write((myVal >> 8) & 0xFF);
Serial.write(myVal & 0xFF);

HOWEVER... how do you know which byte coming in is which? It's very very easy to get out of sync and not get the right values when you read the data in.  So you need some way of "packetizing" the data so that you know "This is a correct set of values".  Just how you do that is entirely up to you - do you just wrap each pair of bytes in a special set of other bytes? Nah - that becomes as wasteful as Serial.print. Instead it's better to buffer up a batch of values and send them as a block with just a few extra bytes to define the packet.
One example of doing that is my ICSC library. Take a look at it and you can see how you can craft a packet to send lots of data as one stream of data.

In fact, I'm using 10 bits in the analogread() but I can't give up that resolution in orde to get more speed.

The 10th bit is usually just quatisation noise, so you only have 9 bits of real information. So you would in fact only be losing 1 bit of information by going from 10 to 8 bits.

Serial.print sends the ASCII representation of the data. So:
uint8_t data8 = 102;
uint32_t data32 = 102;
char datastring[] = "102";
Serial.print(each_of_the_previous_data);

each of these are sent exactly in the same way, i.e. three bytes ('1', '0', '2', so 0x31 0x30 0x32).
This, as you noticed, is highly inefficient. What I suggest you is to send them in binary mode, so
uint8_t *convertToByteArrayLittleEndian(uint8_t *buffer, int32_t val)
{
    uint8_t i;
    for (i = 0; i < 4; i++)
    {
        buffer[i] = val & 0xFF;
        val = val >> 8;
    }
    return buffer;
}
uint8_t *convertToByteArrayBigEndian(uint8_t *buffer, int32_t val)
{
    uint8_t i;
    for (i = 0; i < 4; i++)
    {
        buffer[3-i] = val & 0xFF;
        val = val >> 8;
    }
    return buffer;
}

uint8_t supportArray[4];
uint8_t data8 = 102;
uint32_t data32 = 102;
char datastring[] = "102";
Serial.write(data8); // Sends 0x64 = 100
Serial.print(convertToByteArrayLittleEndian(supportArray,data32),4); // Sends 0x64 0x00 0x00 0x00
Serial.print(convertToByteArrayBigEndian(supportArray,data32),4); // Sends 0x00 0x00 0x00 0x64
Serial.print(datastring); // Sends 0x31 0x30 0x32

I had to use an helper function to convert from int to byte array, since Serial.write does not support directly an int. You can choose if you want to send the data in big endian or little endian format.
As you can see, in binary mode the amount of data exchanged varies.
Just three more things.
1) you probably can go higher in frequency (maybe 1Mbit/s) with the serial. Just try it out
2) If you decide to use binary mode, maybe you will need some synchronization (i.e. a start byte) to ensure you are not listening a stream from a "middle" point. There are various techniques (prevent use of some bits in the stream, use some forbidden values and escape it)...
3) If you want to go faster, I suggest you to switch peripheral. For instance use SPI (of course you won't be able to use a common USB-UART interface, but you can create a native USB dongle with an SPI interface to get the connection)
EDIT:
According to other info from the OP:
The data is 10 bits. Let's split it into two 5bits data, so we can use the upper 3 bits for sending sync info (to understand which byte comes first). The required rate is 6kHz.
I made some calculations, and it looks like that you can use this code:
#include "TimerOne.h"

bool timerHasBeenTriggered = false;

void setup()
{
    Timer1.initialize(167);         // initialize timer1, and set a 6kHz frequency
    Timer1.attachInterrupt(callback);
    Serial.begin(#HIGHER_THAN_115200#);
}

void callback()
{
    timerHasBeenTriggered = true;
}

void loop()
{
    int16_t val = analogRead(ANALOG_PIN); // takes 104us
    Serial.write((val & 0x1F) | 0xA0); // Send lower 5 bits, upper 3 set to 101
    Serial.write((val >> 5) & 0x1F); // Send lower 5 bits, upper 3 set to 000
    while (!timerHasBeenTriggered);
    timerHasBeenTriggered = false;
}

Here the loop has an execution time of around 104us (serial calls just store the values in a queue). The vast majority of the time is spent acquiring from a channel.
I used a timer to trigger the next acquisition so it can be more precise (and the millis() function is useless, since you want to trigger it 6 times per millisecond).
From the PC you will receive two bytes. The first one is in the form 0b101XXXXX, the second 0b000YYYYY. You will only have to

wait for a byte starting with 101
save the other 5 bits (XXXXX)
get the next byte and check it starts with 000
the data will be just the concatenation of the two 5-bits chunks: YYYYYXXXXX

Note that the limiting factor of the timing is the analogRead function. If you want to go faster (or to acquire from multiple channels) you will need to change the ADC clock prescaler. This, however, will make your ADC frequency higher than 200kHz, which is not recommended (you will get less precise data).

But if I do all of that it should be done for each sample? I need a sample rate of 6 kHz and I'm not really sure if is that posible.

6 kHz only, or 6 kHz times 6 pins?

What do you mean by "each sample"? you will be able to acquire from just ONE analog channel, since EACH analog reading takes about 100us. Moreover serial baud rate needs to be higher than 115200, since with 115200 you will be able to send two chars in 174us, which means 5.7kHz. It doesn't matter how much faster, since sending and reading are performed in parallel..

If your signal of interest is of short-enough duration, you might get by by collecting the data into memory, then dumping it at whatever speed you can. If you're using an Uno or other AtMega328 based Arduino, the RAM size, and therefore, your buffer, will be quite limited. Storing the first value as int and subsequent values as one-byte differences can help.
An on-board memory device, like an FRAM, could buffer 8K or 32K bytes (or half as many ints).
Or the same differences technique can be used to send one-byte binary differences and improve your sample transmission rate. It's easy to get out of sync, though. This won't be too reliable for continuous or long data streams.
Otherwise, you're just baud-bound. How fast can you drive the serial output and the receiver still be able to keep up? You're pushing the edges of what the device can do. It's an interesting problem and possibly fun to solve, but I'm reminded of the old adage about alligators and needing to drain the swamp! :)

Some benchmarking of Serial.print() and comparing to clib functions (itoa/ltoa) might give some insight. First, printing int and long int with DEC base using Arduino core Print functions (Arduino IDE 1.6.7, Arduino Mega2560).
Serial.print(12345, DEC): 240 us
Serial.print(12345678L, DEC): 388 us

Second, use HEX base.
Serial.print(0x1234, HEX): 204 us
Serial.print(0x12345678L, HEX): 384 us

Third, use the AVR clib functions to convert number to a string and then print the string. 10 and 16 base.
Serial.print(itoa(12345, buf, 10)): 104 us
Serial.print(ltoa(12345678L, buf, 10)): 240 us

Serial.print(itoa(0x1234, buf, 16)): 80 us
Serial.print(ltoa(0x12345678L, buf, 16)): 240 us

Cheers!

Below is the test sketch:
void setup()
{
  uint32_t start, stop, us;
  char buf[16];
  Serial.begin(9600);

  start = micros();
  Serial.print(12345, DEC);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(12345, DEC): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(12345678L, DEC);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(12345678L, DEC): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(0x1234, HEX);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(0x1234, HEX): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(0x12345678L, HEX);
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(0x12345678L, HEX): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(itoa(12345, buf, 10));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(itoa(12345, buf, 10)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(ltoa(12345678L, buf, 10));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(ltoa(12345678L, buf, 10)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(itoa(0x1234, buf, 16));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(itoa(0x1234, buf, 16)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

  start = micros();
  Serial.print(ltoa(0x12345678L, buf, 16));
  stop = micros();
  us = stop - start;
  Serial.println();
  Serial.print(F("Serial.print(ltoa(0x12345678L, buf, 16)): "));
  Serial.print(us);
  Serial.println(F(" us"));
  Serial.flush();

}

void loop()
{
}

The clib itoa/ltoa are regarded to be relative slow and there are proposals to improve performance. Please see, for instance, this bug report.

The bug report is interesting, but it looks to me like a speed/size trade-off: bigger code and faster execution. It is quite common on AVRs to optimize for size instead.


text:
How to get the MAC address of an Ethernet shield, if it is not printed on it?
Help me to find out how to connect an Ethernet shield over the internet using a LAN cable. I have tried many times but I'm not getting a MAC and IP address.

The MAC address is written to the Ethernet Controller.  The IP address can be given by DHCP or static in which it is also written to the Controller.

Have you read "Getting Started with the Arduino Ethernet Shield" and the "Arduino Ethernet+SD" section of Lady Ada's Arduino Tutorial?

If you do not have a MAC address then you have to make one up.  There are a couple of rules and regulations about what a MAC address can be, but most of the time you can just make one up:

It must be unique on your network
There are a set of prefixes that are reserved for special purposes:

The lowest bit of the first byte must be 0
The second bit of the first byte must be 1

You can read more about it here: https://en.wikipedia.org/wiki/MAC_address
Once you have provided a MAC address and physically connected it to the network then you need an IP address and netmask.  There are two ways you can get the IP address and netmask:

Through DHCP - For example your home internet router would provide the IP address for you.
By allocating your own. This must be within the range of your network's IP addresses, typically something like 192.168.0.x where x is between 1 and 255.  The IP address must be unique on your network.

The netmask, again, can be given by DHCP, otherwise you will have to enter the netmask of your network, typically 255.255.255.0
Then to access the internet itself you need to provide (or be provided with through DHCP) the address of the internet gateway and possibly a DNS server address. On a home network they are typically the address of the router, which may well be 192.168.0.1 or something similar.

Specifically, it is setting the second lowest bit of the highest octet to 1 which indicates a locally administered or "made it up yourself" address.


text:
Detect how long a push button is being pressed?
I would like to detect how long the state on/off is going on for. Is there a way to do that? I would like to do that for two reasons:

I would be able to make a very simple toggle button. (I know about the other way with the old value and new value).
I can make the button being pressed for a long time be like a return button.

Anyone got any ideas?

You would need to use millis()

This needs a combination of patterns.
First, the button pin needs to be debounced. This can be done with the "blink-without-delay"-pattern where the button pin is sampled with a low period (40 ms in the example code below).
Second, a simple state-machine is needed to keep track of the button state but also if the return button action function, doReturnButton(), has already been called.
The button is assumed to be connected from GND to pin4. The button action function, doButton(), is called when the button is pushed (goes LOW).
const int buttonPin = 4;
const unsigned long debounceInterval = 40;
const unsigned long returnInverval = 400;
bool buttonState = true;
bool returnButtonState = false;
unsigned long buttonDownMillis = 0L;

void doButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doButton"));
}

void doReturnButton()
{
  Serial.print(buttonDownMillis);
  Serial.println(F(":doReturnButton"));
}

void setup()
{
  Serial.begin(57600);
  while (!Serial);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
  unsigned long currentMillis = millis();
  static unsigned long previousMillis = 0L;

  // Check if it is time to sample the button pin
  if (currentMillis - previousMillis >= debounceInterval) {
    previousMillis = currentMillis;

    // Did the button change
    if (digitalRead(buttonPin) != buttonState) {
      buttonState = !buttonState;

      // Was the button released
      if (buttonState) {
        returnButtonState = false;
      }

      // Was the button pushed
      else {
        buttonDownMillis = currentMillis;
        returnButtonState = true;
        doButton();
      }
    }

    // Check if button was pushed and time for return action
    else if (returnButtonState) {
      if (currentMillis - buttonDownMillis >= returnInverval) {
        returnButtonState = false;
        doReturnButton();
      }
    }
  }
}

What does the code do?

It samples the button pin with a debounce interval.
If the button state changes:
a. High to Low it calls the doButton() function and captures a timestamp. It also allows detect of return time interval.
b. Low to High. Return time interval is not allowed any more.
It checks if the return time interval has elapsed and if so calls the doReturnButton() function. The detect is then not allowed any more.

The doButton() function is called when the button is pushed (transition high to low), only once. The doReturnButton() function is called if the return time limit exceeds and the button is still low. Both are only called once per push (transition high to low).
To avoid the multiple transitions that occur when a button is pushed a debounce time period is used. The can also be done in hardware with a RC-circuit.
With some abstraction it could be rewritten as:
#include <Timemark.h>

Timemark debounce(40);
Timemark buttonHold(400);

const int buttonPin = 4;
bool buttonState;

void doButton()
{
  Serial.println(F("doButton"));
}

void doReturnButton()
{
  Serial.println(F("doReturnButton"));
}

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("started"));
  pinMode(buttonPin, INPUT_PULLUP);
  buttonState = digitalRead(buttonPin);
  debounce.start();
}

void loop()
{
  if (debounce.expired()) {
    bool currentState = digitalRead(buttonPin);
    if (currentState != buttonState) {
      buttonState = currentState;
      if (buttonState) {
        if (buttonHold.expired())
          doReturnButton();
        else
          doButton();
        buttonHold.stop();
      }
      else {
        buttonHold.start();
      }
    }
  }
}

This also demonstrates the callback on the release of the button. The Timemark class hides all the time intervals, expire calculations, etc.
Cheers!

Isn't this just making a toggle button?

It calls doButton when the button is pushed and doReturnButton if the button is still pressed after a time limit.

Ah sorry I just got to understand the code better hang on.

I am genuinely sorry but can you please explain each part of the code? it would really help me understand it as well as broaden my knowledge of arduino.

On a long press, you will doButton() and doReturnButton(). I do not thing this is what the OP wants, although the question is not clear on this regard.

I avoided that as it actually adds some complexity to the "state machine". The "callback" has to be delayed for the return button interval. From an UI point of view the button feedback becomes "sluggish". It is a bit like mouse click and double click. You get both events and the application has to add logic on top of that. But it is a good point!

You could get a slightly more responsive UI – and not really more complicated – by calling the “short press” callback on the button release event: that's when you know it was actually a short press.

I am so sorry. For some reason, I did not get the notification of the comments and that the answer changed. I believe this is what I was looking for. Thanks!

I've just seen your updated answer with a Timer class. This would certainly provide a terrible user experience. If you tell the user that, for performing some action, a long press is needed, he will typically press the button and hold it down until he sees the action is taken. But your code waits for the user to release the button... which leads to a dead lock. I've previously commented that the release event is the best time to fire the “short press” callback, but that does not apply to the “long press”.

@EdgarBonet Please feel free to edit the code. The idea was to illustrate different approaches not the ultimate correct version. The last approach was callback on release which what typical GUI events click/doubleClick do. Other GUI events are mouseDown and mouseUp. But again I can only agree that this is not the perfect user experience for push buttons.

Note the time the switch is pressed (with millis())
Note the time the switch was released.
When the switch is released calculate the difference. If it is a "long" time do one thing, otherwise do something else.

But won't millis() just detect how long the program was running?

@Jack Think about it. You're not looking at millis() directly, but at the difference between two consecutive calls.


text:
Trying to run two simultaneous loops that do the same task with different delay cycles
I'm trying to control a pellet stove auger motor in such a way that I can use a toggle switch to do High/Low (H/L) - so the way that I have it now is:
 void setup() {
   // initialize digital pin 13 as an output.
   pinMode(13, OUTPUT);
   pinMode(12, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(12, HIGH);
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(2850);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(11250);

Which is just LED on/off but it also controls another relay that controls the blower motor - what I'm trying to set up is a H setting that would be the 2850 delay-ON - and then have say: pin 11 have a delay-OFF of 7000, and have pin 13 still resetting to the delay-ON of 2850.
What I mean is:

loop A: pin12 on -delay 2850 pin12 off -delay 11250
loop B: pin13 on -delay 2850 pin13 off -delay 7000

I saw and tried the code for 'multi-blink' - as the one I use is pretty much modified 'blink'.
Any assistance would be awesome - I run the one I show above now, on my pellet stove and it was recently -31.4 and worked like a charm, but I'd like to be able to have a high/low option.
PS: I also have a coffee roaster control project as well... help on that one is always appreciated as well.

Just out of interest... -31.4°C or -31.4°F? Although they are pretty much close, and damned cold either way!

This seems to be the perfect example for the simple scheduler:
#include <Scheduler.h>

const int pinA = 12;
const int pinB = 13;

void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Scheduler.start(setupA, loopA);
  Scheduler.start(setupB, loopB);
}

void loop()
{
  Serial.print(millis());
  Serial.print(F(":pinA="));
  Serial.print(digitalRead(pinA));
  Serial.print(F(",pinB="));
  Serial.println(digitalRead(pinB));
  delay(1000);
}

void setupA()
{
  pinMode(pinA, OUTPUT);
}

void loopA()
{
  digitalWrite(pinA, HIGH);
  delay(2850);
  digitalWrite(pinA, LOW);
  delay(11250);
}

void setupB()
{
  pinMode(pinB, OUTPUT);
}

void loopB()
{
  digitalWrite(pinB, HIGH);
  delay(2850);
  digitalWrite(pinB, LOW);
  delay(7000);
}

Cheers!

Pretty amazing that only a couple of hours ago and now I have a written variant to try, which I tried something similar on the uno before, the code available at arduino for "multi-blink" but it wouldn't compile, but then i saw it said you needed a due, but not an uno to run it, but so didn't mess with it all that much, it made sense, but wouldn't run, and I failed to copy the error, but i'll def try running this, with pins of course, is there any reason it wouldn't run on a mega as well? The uno is busy keeping me warm, but I have a mega here, so I'll try that first

The Scheduler library above (lhttps://github.com/mikaelpatel/Arduino-Scheduler) can be used with more or less all Arduino boards. It gives the illusion of running multiple sketches in the same sketch.

I'm sorry man, i'm pretty sure i'm a dunce at this point - i tried all the ways i could find to include that and a different one as well, library, but still was unable to compile it = i don't get it, my understanding is that the code you posted would work with the library listed added - i'm certainly feeling shame in admitting I clearly don't know how to add a library to a sketch - help please.

Installing a library in Arduino is hard (at least the first time). Start by downloading the ZIP file from https://github.com/mikaelpatel/Arduino-Scheduler. Locate the "libraries" folder in the Sketchbook (or Arduino folder). Unzip the Arduino-Scheduler-master into the "libraries" folder and rename the folder Scheduler. Restart the Arduino IDE and you are ready to go.

It definitely doesn't help that the pc i'm using to code/try to code with is a 2012 hp $250 laptop that, as someone that has used computers since 1986+/- , is the WORST computer ever - tried upgrading to win10 from 7 - which was working fine, but i suppose i'm a bit of an early adopter , then, no touch pad at all, ditched the thing for a bit and just used phone, then needed to program the A unit to make the pellet stove work, so tried again, now, my touch pad does work, but, if you use the keyboard there is a oh, one to 1.5 sec delay before the touchpad works again - not stellar equpiment,

oddly, the first time i tried it was a zip, and i put it where it was supposed to go - i do try to follow directions most of the time (and do also mock those that don't), then i tried the rest of the options that were made available - i finally got it to say there was a , that was unexpected or some similar error, then pc was rebooted before getting the error copied - at this point... i don't get why it wont compile, it seems all the files are where they should be and the code makes sense, but...

WARNING: library Scheduler claims to run on [sam architecture(s) and may be incompatible with your current board which runs on samd] architecture(s).

The Arduino Simple Timer library (and other similar timer libraries) are made for exactly this kind of application. Your setup() routine calls the SimpleTimer library, naming a callback-function and how often it should get called. Your loop function must then call timer.run() reasonably frequently (where
reasonably frequently" depends on the timing accuracy and jitter tolerance of your application). timer.run() will call each of your callback-functions at its appropriate time. You write the callback-functions to do whatever you need them to do when the timer calls them.
There are one-shot timers and repeating timers - it sounds like your application could one of each per LED: One that fires periodically, to to call a turn-on-LED12 function every (ON_TIME_12+OFF_TIME_12) ms, and a one-shot that calls a turn-off-LED12 function, started by the turn-on-LED_12 function for (ON_TIME_12) msec. Same for LED13, ( ..., etc.)
Your loop function is free to do whatever else, as long as it calls timer.run() frequently enough that your application can meet its timing requirements.


text:
3-5v micro stepper connected to A4988 driver does not move and makes whirring noise
I am kind of a newbie when it comes to stepper motors so I am hoping I am not asking any stupid questions.
I am trying to run a 3-5v micro stepper motor (PM15S-020-SKH4) using a Pololu A4988 stepper driver. I know the driver isn't originally meant for low-voltage stepper motors but I had some lying around and from what I understand it should not be a problem as long as the pot-value is set correctly.
Now I've identified the coils on the stepper motor and connected everything with an 12V power supply, Arduino Uno, 100uF capacitor as described in the Pololu schematic. I couldn't find the current specification for the stepper motor but if my calculations are correct with 5V / 30 Ohm it should be 160 mAmp so per another calculation I've set vRef value for the pot-meter to 0.160 * 0.4 = 0,064
The code I run on the Arduino is;
#define PIN_DIR 1
#define PIN_STEP 3
#define PIN_ENABLE 5

void setup()
{
    pinMode(PIN_DIR, OUTPUT);
    pinMode(PIN_STEP, OUTPUT);
    pinMode(PIN_ENABLE, OUTPUT);

    digitalWrite(PIN_ENABLE,LOW);
}

void loop()
{
    digitalWrite(PIN_DIR,HIGH);

    // 20 pulses of 18 degrees should make one full rotation
    for(int i = 0; i < 20; i++)
    {
        digitalWrite(PIN_STEP,HIGH);
        delayMicroseconds(500);

        digitalWrite(PIN_STEP,LOW);
        delayMicroseconds(500);
    }

    delay(1000);
}

When running the above code, the shaft is harder to move compared to a disconnected motor so there is resistance between the coils what should indicated that they are powered. But when running this the only thing the motor does is make a whirring noise and struggle/tick when I try to rotate it with my fingers.
I have tried multiple of the same type motors and drivers but all yield the same result.
I have a feeling I am overlooking something very obvious but I have no idea what, or am I being a complete idiot trying to combine the Pololu A4988 and the PM15S-020-SKH4?

Maybe your current is too low?

I have tried to increase the vRef on the pot-meter in ranges from 0.1 until even 1 (where to motor got really hot) but all with the same result.

Any chance you mixed up the pins and are toggle the direction or enable but not the step?  Are both coils truly connected?

I have given up on trying to get this to work and switched to a servo. I have hooked up the setup to a NEMA17 stepper motor (with alterations to the current) and it works fine. I have tried the small stepper motor in many, if not all configurations and I just can't get them to work.


text:
Arduino Uno board works but Arduino Uno + Wifi is not being detected
When I connect my Arduino Uno board it instantly detects the board and shows it in the list. But when I connect my new Uno + Wifi board it doesn't detect it. I also manually selected Arduino Uno Wifi but it still gives me the message
Error uploading check if the selected board is currently available
How can I fix this?
This is the one that's not working:
Arduino Uno + Wifi
While this one I got does work:
Arduino Uno

Is it a genuine Uno?

I editted my question to contain the exact products. The power source inputs are different I don't know if that could have anything to do with it?

Install the USB drivers (CH340G). It's a cheap Chinese clone.

and the DIP switch must be in USB to Atmega setup

Possible duplicate of My Arduino isn't showing up on my computer. What should I do?

What you have there is a cheap Chinese clone. It uses the cheap CH340G USB chip instead of the proper ATMega16u2 that real Arduinos use.
Install the right drivers and it should start working.

Thank you this worked! But I just wonder, what's the downside of using the cheap clone?

They have a habit of dying easily. But they're cheap to replace.


text:
esp32, platformio A fatal error occurred: Packet content transfer stopped (received 8 bytes) *** [upload] Error 2
When i try to upload code to the esp32 the following error shows up in the command line:
A fatal error occurred: Packet content transfer stopped (received 8 bytes).
I use platformio in VScode the platform.ini file looks like this:
    [env:esp-wrover-kit]
    platform = espressif32
    board = esp-wrover-kit
    framework = arduino
    upload_port = COM4
    monitor_speed = 115200

Here's the code i'm trying to upload:
#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println("init");
}

void loop() {
}

It's an esp32-wrover-dev from freenove. When i unplug it and plug it back in it starts to write random stuff to the serial monitor, when i attempt an upload it stops but it also gives me the error above.

For anyone wondering, i found out it means that there's some kind of disconnect between the computer from which your uploading and the file system. Essentially, the esp32 is broken.

Reducing upload speed to 11520 worked for me.

Definitely not necessarily. I've just removed the joystick (which is consuming power from the USB TTL thus ESP32) and then it worked fine. So remove external power consumers and the upload will succeed.

I had this error when trying to upload a sketch from Arduino IDE to a TTGO T-Display, found that I could resolve this by changing the upload speed from the default of 921600 to 115200.
After doing that it uploaded just fine with no issues.

I was able to resolve this issue by detaching jumpers that i had connected to the GPIO 12/13 pins during upload.
After uploading they can be attached again.
See this github issue: https://github.com/espressif/arduino-esp32/issues/2415

Hi all I found I got this error because my FTDI adapter was in 3.3V mode, not 5V as soon as I set it to 5V the issue was resolved and it programmed fine. One more thing to check before you scrap your ESP32.
Mick

so an est32 should be powered with 3.3 V. 5 V will damage it.

Hi I was using the CAM module which has pins marked as 5V so maybe dont do that if powering the IC direct. Apparently it has less issues at 5V. Thanks.


text:
Do I need to connect a capacitor to AREF if using internal reference? _BV(REFS0)

This is from the Atmega328p datasheet. But I see no mention of it in practical examples.
So when I'm setting up the timer for ADC with:
ADMUX = _BV(REFS0);

Should I add the cap? Or might it be already there on the arduino's hardware? Also what value is advised? 100nF?
Thanks in advance!

According to the datasheet:

The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

So you can but you don't have to. It all depends on how good you want your ADC results to be. 99% of the time it's pointless since what you're reading isn't that accurate, but if you want to add a capacitor anyway then sure, go right ahead.
What value capacitor? Well that very much depends on what kind of noise you want to achieve more immunity from. The lower the value the higher the frequency it will help protect you from. You may want to combine multiple capacitors in parallel if you're in a very noisy environment, such as 1nF and 100nF.

Thanks for clearing that up! I'll test it out and see if it improves anything or not.