Proportional water flow control I've been looking at water flow control with Arduino and I'm finding a huge difficulty in managing to do an 'analog' control on water flow. The mainstream solution seems to be the well known solenoid valve, however those seem to be binary (full flow, no flow), and I'm looking for a more variable answer.

Is it possible to get middlegrounds with solenoids? Maybe actuating them with less voltage or amperage will cause it to partially actuate? If not, does anyone know of embedded solutions using servos or steppers maybe?

Is it possible to get middle grounds with solenoids?

No.  The solenoid will be all or nothing.  If you have used a magnet, you have seen that the force decreases rapidly with distance.  As you move something closer, it will typically snap to a magnet at one point.  The same thing happens in a solenoid valve: once you apply enough voltage to start motion, the motion will complete.

Side note: that is actually a common trick to saving much power with solenoid valve.  You might apply 12 V to actuate, but then you can reduce the voltage very low (maybe 2 V or lower) and the valve will still say actuated.

So if you want flow, you need a flow control valve.  A common 1/4 turn ball valve will provide the fractional flow you seek.  You should be able to hook a servo or gear motor to that.

A typical ball valve will not provide a constant change of flow with angle.  That means the change in flow between the first 5 degrees opening will be large while the last 5 degrees of motion will have little effect.  If the application is not critical, that would be fine.

If you want more precise flow control, valves are made with a particular cutout in the ball that makes the flow control more linear.  You can get a commercial type valve with motor attached in cost range of 100 $US.  For hooking up to an Arduino, a Belimo flow valve (one example vendor) only seems appropriately named

These are commercial type valves used to control water in heater systems and such.  They take a 0 - 10 V input signal as control and will rotate the vale.  The keyword search is "motorized flow control valve" and that will find you many.  These are not exotic, you will find many in all sorts of sizes.  You may even find from a local plumbing supplier where you can pick one up at will call.


Is it possible to have long wire connections from an NodeMCU to a servo motor or button? For my proyect, I need to conect my NodeMCU to a servo motor as well as a push button, the thing is, the distance from the NodeMCU and both components has to have a distance of around 6.10 meters (or 20.0131 feet), I dont know if it is possible to do this connection, I worry if the pwm signal or the voltage would drop by the time it reached either component. I havent been able to try this because I dont have long enough cables to do the connections. In the case that it would be possible, what type of cable should I use and should I add something extra to the circuit to make it work better? Thanks.

A push button won't be a problem. That is a very simple change in resistance from open circuit to a few ohms. You just need a low enough resistance to force the voltage coming through weak internal pullup resistor down to ground. It looks like 22 gauge wire has about 52.7 ohms / 1000 meters.
I don't think 6 meters of 22 gauge wire will be a problem for a 5V PWM signal either. If it's a very electrically noisy environment you might want to use shielded or twisted pair cable, but it seems unlikely that would be needed.


What is the Vin Pin for? I always asumed it was a different option to power the board, but it seems to act more like a 5V supply. What then is the difference between this pin and the 5V pin?

The Vin pin serves the same purpose as the barrel jack.  The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.

Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.

If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin.  It's not safe to use that power for anything since you could damage the 5V regulator if you do.

The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).


Arduino Smoothing does not work as expected I using the standard example of smoothing:

/*
  Smoothing

  Reads repeatedly from an analog input, calculating a running average and
  printing it to the computer. Keeps ten readings in an array and continually
  averages them.

  The circuit:
  - analog sensor (potentiometer will do) attached to analog input 0

  created 22 Apr 2007
  by David A. Mellis  <dam@mellis.org>
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Smoothing
*/

// Define the number of samples to keep track of. The higher the number, the
// more the readings will be smoothed, but the slower the output will respond to
// the input. Using a constant rather than a normal variable lets us use this
// value to determine the size of the readings array.
const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = A0;

void setup() {
  // initialize serial communication with computer:
  Serial.begin(9600);
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  // subtract the last reading:
  total = total - readings[readIndex];
  // read from the sensor:
  readings[readIndex] = analogRead(inputPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }

  // calculate the average:
  average = total / numReadings;
  // send it to the computer as ASCII digits
  Serial.println(average);
  delay(1);        // delay in between reads for stability
}

to calculate power consumption for a load which changes it's value frequently (sometimes it stops and the consumption goes down to couple of watts).

My only modification of the above code is to pass a calculated power (V*I) value to it instead of the analogRead(inputPin);. The input value for the power calculation works fine because without this code I get the exact good values for power. I have also increased the numreadings from 10->100 and probably will needed to be increased a lot more since I need the average for 1 minute.

There are 2 major issues with this code:

1, When a constant load is attached, which let's say draws 500W the value generated by the code is floating around 312W and never reaches 500.

2, When the load is disconnected it and the current power consumption is 1-2watts standby this code jumps to -312W. I could cast it to be an unsigned integer on the first place but that's not really a good solution.

Anyone knows how to fix this?

Thanks

Yes, change the variable type to something that can hold larger numbers, because now adding up 100 measurements will overflow your variable.


PIR sensor and sleep (interrupt) on Mega2560 So I was starting to gain some knowledge on the PIR sensor and how to let the Arduino 'sleep' while there is no movement detected by the PIR.

I found the following code somewhere and looked fairly simple. So  I thought I would give it a try and grabbed my Mega2560, a LED and a PIR sensor.

While it was seeming to work at first sight, the Arduino is doing the opposite from what I was expecting. It turns off the LED and the Arduino when there is movement, instead of turning off the Arduino when there is NO movement. As I said before, it is doing pretty much the inverse.

Probably an easy solution, but can't figure it out on my own.

The code:

#include <avr/sleep.h>

int wakePin = 2;                 // pin used for waking up
int led = 13;

void wakeUpNow() {
}

void setup() {
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    digitalWrite(led,LOW);
    sleep_mode();            // here the device is actually put to sleep!!
    // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    digitalWrite(led,HIGH);
}

void loop() {
  sleepNow();     // sleep function called here
}

Thanks in advance.

EDIT

Adapted the code to the following and seems to work now. When motion is detected by the PIR it turns on the LED on pin 13; when no motion is detected, the LED is turned off.

Two questions still remain:

1) How can I be sure that the Arduino really sleeps now?

2) When the Arduino just entered sleep, it takes a couple of seconds (+/- 6s) before it can pick up another motion. Can I get a faster detection or another 'sleep' or 'powersave' method that lets the Arduino react faster to motion?

#include <avr/sleep.h>

const int wakePin = 2;                 // pin used for waking up
const int led = 13;

int wakeVal = 0;
int wakeState = LOW;

void wakeUpNow() {

}

void setup() {
  Serial.begin(9600);
  pinMode(wakePin, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  //attachInterrupt(0, sleepNow, LOW); // use interrupt 0 (pin 2) and run function wakeUpNow when pin 2 gets LOW
}

void sleepNow() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();          // enables the sleep bit in the mcucr register
    attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
    sleep_mode();            // here the device is actually put to sleep!!
}

void disSleep(){
  // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP
    sleep_disable();         // first thing after waking from sleep: disable sleep...
    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
}

void loop() {
  wakeVal = digitalRead(wakePin);
  if (wakeVal == HIGH){

    disSleep();

    digitalWrite(led,HIGH);
    delay(1000);

    if (wakeState == LOW){
      Serial.println("Motion detected");
      wakeState = HIGH;
    }
  }
  else{
    digitalWrite(led,LOW);
    delay(1000);

    if (wakeState == HIGH){
      Serial.println("Motion stopped - Going to Sleep Mode !");
      wakeState = LOW;
      delay(1000);

      sleepNow();     // sleep function called here
    }
  }
}

This is a problem with the Arduino Mega board. On the Mega, D2 is not INT0 as it is on the Uno. It's INT4. There's a footnote in the spec sheet that says only level interrupt is supported. That means you can't use RISING, FALLING or CHANGE. Your only choice is to use LOW. So the Arduino will be woken up when the motion turns OFF, not on. That's why it's backward. If you use an Uno instead of a Mega, you can use RISING and it will work as you think it should.


Can I power a 9g servo from an arduino nano with USB power only? I want to run a 9g servo off of the pins from an arduino nano board, using only the 5v USB connection.

The servo specifically is a SG90, which I have measured a stall current of ~250mA - I don't intend to stall it, just have it run with almost no load

I am not sure which pins to power it off of from the arduino itself - do I use the VCC or the +5v? does it matter which ground I use? should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something? does the arduino nano negotiate to get more than the default of 100mA from a USB power connection?

The max current of the Arduino-Nano 5V Pin is 200mA. So if you draw more than that it might damage your Arduino.

Here is an interesting summary regarding the Maximum Ratings of the Arduino Nano: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

  The 5V pin of the arduino is not connected through the
  microcontroller. As such, it can source significantly more power. When
  you are powering your arduino from USB, the USB interface limits your
  total power consumption to 500 mA.

So yes, it actually seems you can draw 250mA out of the 5V PIN.

  do I use the VCC or the +5v?

You use +5V, because VCC is for powering your Arduino with an external Power Source. It allows you to use up to 7-12V (recommended), or up to 6-20V (limits).

  does it matter which ground I use?

Doesn't matter

  should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something?

A breadboard makes it easier for you, to test your circuit. But you can do it without if you like. Then you possibly have to solder some connections

See also the offical Arduino Page for the Nano.


Arduino - Turn on LED when Potentionmeter is used I'm very new to the Arduino/Microcontroller-world, so please be patient :)

I have 4 potentiometers and I want my LED to blink up, when one of these is beeing used.

So far., so good.. the potentiometers are sending singnals to my inputs A0-A3. In the code I read and buffer the values of send to the inputs, so when a new value is recieved (potentiometer is beeing used), the funcion blinkLED() is beeing triggered:

int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] = {0, 0, 0, 0};

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

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(potiValues[i] != potiValuesTmp[i]) {
            // NEW VALUE RECIEVED - MAKE OUTPUT
            Serial.println("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.print(potiValues[i]);
            blinkLED();
        }
        potiValuesTmp[i] = potiValues[i];
    }
}

void blinkLED() {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
}

It somehow works on the emulator circuits.io, but I'm not sure if I did it right(?) Maybe someone could have a look and tell me, what to improve?

But my main question is:
When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

When the function blinkLED() is triggered, there is this delay,.. does the whole loop()-function wait, too?

Yes, when you call a function it doesn't return until it is done, and delay is blocking.

You can rewrite a bit like this:

int ledPin = 13;

int pin[] =             {A0, A1, A2, A3};
int cc[] =              {20, 21, 22, 23};
int potiValues[] =      {0,  0, 0, 0};
int potiValuesTmp[] =   {0, 0, 0, 0};

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

unsigned long lastFlash;
int flashesToGo;
const unsigned long flashTime = 50; // ms

void loop() {
    // READ EVERY PIN
    for(int i=0; i<=3; i++){
        potiValues[i] = map(analogRead(pin[i]), 0, 1023, 0, 127);
        if(abs (potiValues[i] - potiValuesTmp[i]) > 3) {
            // NEW VALUE RECEIVED - MAKE OUTPUT
            Serial.print("Pin ");
            Serial.print(pin[i]);
            Serial.print(" - ");
            Serial.print("Value: ");
            Serial.println(potiValues[i]);
            flashesToGo = 10;
            potiValuesTmp[i] = potiValues[i];
        }
    }

   // flash LED if required

   if (flashesToGo > 0)   // need more flashing?
      {
      // is it time to toggle the LED?
      if (millis () - lastFlash >= flashTime)
        {
        // toggle LED
        if (digitalRead (ledPin) == HIGH)
          digitalWrite (ledPin, LOW);
        else
          digitalWrite (ledPin, HIGH);
        // remember when we did it
        lastFlash = millis ();
        // count down
        flashesToGo--;  // one less flash
        } // end of time for another flash
      }
   else
     digitalWrite (ledPin, LOW);  // ensure LED off

}

What this does is add to the main loop a few lines of code that toggle the LED after a certain time is up (50 ms currently). It counts down the number of toggles from a desired starting point (eg. 10) until they are all done. This means that the LED will flash without blocking.

Each time you detect a new analog reading the number of flashes is reset back to the maximum.

I modified your test for if the analog reading changed to be:

if(abs (potiValues[i] - potiValuesTmp[i]) > 3)

I found that without that, the LED flashed continually because the readings were slightly different each time (eg. 51, 52, 51, 50) which would probably just be error in the ADC reading.

With that change, it doesn't count as "changed" unless the reading changes by 3 (you could make it more, or less than that).

  I want the LED to blink up just once - when I turn one of the potentiometers

In that case change:

flashesToGo = 10;

to:

flashesToGo = 2;

That is one HIGH and one LOW (one flash in total).


Burn smell from arduino uno I have did something stupid.. I connected 10K Ohm potentiometer at its maximum value PARALLEL with a LED. The positive long leg of the led to arduino 5v and the negative leg to the GND.
After giving arduino 5v from USB Mobile Charger ( Output: 5V , 1A ) I smelt a burn and quickly removed the charger from the outlet.
I waited a few hours and connected the arduino ( without any components ) to the charger again. and the arduino worked. I then connected it to the PC and uploaded the blink sketch of the on-board led and it worked !
Then I uploaded a sktech for blinking led on other pins and it worked also !

My question is:
1) What is damaged on the board ?
The smell is near the regulator but I'm not sure if it's from the regulator itself or just a component near it.

2) Can it be safe to still using the arduino board on USB Power or Battery Power without any problems ?

That burn is likely the smell of the potentiometer, not the arduino. I would check the arduino with a multimeter set to resistance to make sure that the Vin trace resistance is nominal.


Two-wire Conductivity Sensor and Arduino Hook-up? For the conductivity meter shown in the photo below, it is a non-NPN sensor for measuring conductivity / impedance.

I am trying to figure out the best method for measuring the output of the sensor using an Arduino.

I am told from the supplier that there is no polarity.  I was planning to connect one of the leads through a 10k resistor to an analog input (A0) on my Arduino; and the other lead to 5V?

Without much other information on the sensor, is a 10k resistor a good place to start?

It depends on the conductivity of the liquid which it is going to be placed/submerged to. For example if the liquid is highly conductive(ex. saltwater), then a 10k Ohms resistor should be fine. But if the liquid conductivity is low(ex. tap water), then its best to measure the output voltage of one lead with respect to the Arduino's ground to be sure what value of resistor to apply to or if there is no resistor needed at all.

But generally if you are going to supply it with 5 Volts, it should be fine to connect it with the Arduino's Analog inputs directly as the operating voltage of the Arduino itself is also 5 Volts.

Cheers!


How to measure whether air is flowing through a pipe? I'm looking for a way to check the air-flow from an aquarium air pump. I need something that can test whether air is flowing or not and I'm not bothered about measuring flow speed. The air will be flowing through a pipe but if required I can have the sensor on the end of an additional pipe just used for measuring.

Did you consider a barometric sensor deployed inside the pipe?
The pressure should be higher when the pump is active.


Arduino IDE c++ 11 raw string literal have issues with // in http://, complier thinks // is comment char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js"></script>
  </head>
  <body>
  </body>
</html>
)=====";

I found a problem when using the raw string literal in Arduino IDE.
My code cannot compile if i have http:// link inside the string.

I found that it should be related to how Arduino IDE thought the string after // are comments and during compile time those string are ignored and my codes break.

It looks like the arduino ide's compiler removes all //comment in the code first, before it try to compile the raw string literal and then cause the issue.

As a test I try to debug it by changing my code to https:/-/ the program can be compile as now there is no // in the raw string literal

Is there any workaround?

Escape the two quote marks inside the string using a backslash (literal quotes).

Without the escape characters, the URL is "outside" of a string because the quote marks are string delimiters.

char webpage[] PROGMEM = R"=====(
<html>
  <head>
    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.6/svg.min.js\"></script>
  </head>
  <body>
  </body>
</html>
)=====";


Position Feedback for Stepper Motor I want to rotate a gearwheel with a stepper motor. While Arduino is on everything is well.

My gearwheel transfer its power to a gear worm. The worm will go 10th cm and back repeatedly. When I cut the power, Stepper Motor stops where its last step and position. When the power is on Stepper starts from last position but steps starts from the first step.

Assume that 2038 steps are rotating the Motor one revolution. For example, when 1500 step pass and power cut. Worm is on 6th cm now. And the power is on. Stepper is working from 6th cm and is going 2038 steps. Now it is on 16th cm.

If I use servo, when the power is on, I can write the motor to the 0 position. But I have to use stepper motor. How can I fix this?

Stepper Motor: 28 BYJ 48
Driver: ULN2003A

The cod is here;

int State;
int Wait;

void setup() {

  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);

  digitalWrite(8,LOW);
  digitalWrite(9,LOW);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
  State = 8;
  Wait = 2;
}

void loop() {

  turnRight(2038);
  delay(1000);
  turnLeft(2038);
  delay(1000);

  }

void turnRight(int Step) {
    for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      IncreaseState();
    }
}

void IncreaseState() {
  State++;
  if (State==12){
    State=8;
  }
}

void turnLeft(int Step) {
for (int i = 0; i < Step ; i++){
      digitalWrite(State,HIGH);
      delay(Wait);
      digitalWrite(State,LOW);
      DecreaseState();
    }

}

void DecreaseState() {
  State--;
  if(State==7){
    State=11;
  }
}

There are multiple ways to to this. The easiest and most commonly used way is to use a limit switch as home position sensor. At startup the device will first drive the motor in the direction of the limit switch, until the switch get's activated. Now the the absolute position on this axis is known and you can go on from there. (CNC machines and 3D printers mostly work that way. Often they retract again from the limit switch and approach the switch again with less speed, to increase the accuracy). For this you just need a micro switch on the axis and connect it to one input pin. In setup() you are driving the stepper motor in the direction of the limit switch, until it gets activated. Then you are on position zero and can go on with your sketch.

A more difficult way is to introduce a measurement of position into your device. A servo incorporates a potentiometer connected to the axis. By measuring the voltage on this potentiometer (it is basically a voltage divider), the servos electronics can always know, where it currently is. There are also fader potentiometers, where you don't rotate a knob, but you slide a fader over a linear rail. You might find a fader potentiometer, that fits your scale (10cm is not that much, there might be some).

Or you could save the current position to a non-volatile memory (like EEPROM) and retrieve it, when you start up. But since a power-cut during writing of the position may corrupt the data, you would have to go a more complex way. Something like sensing, that the power was cut, providing the Arduino with power through a big capacitor, so that, when it senses power loss, it still has enough time to write the current position to a non-volatile memory. (This is also better for the EEPROM, than continuously writing to it, since EEPROM has limited write cycles).

All in all I would suggest using the first mentioned method (limit switch). It is used in many devices for a reason. Though it depends on your exact project requirements.


C# Arduino: How to detect if the needed software is present on the computer I have a digispark that uses trinket keyboard library to send media keys back to the computer using a rotary encoder. I currently have it configured to send normal media keys but about 2 weeks ago i started needing to change binds on what the rotary encoder does so i needed a driver of some sort. i asked and i got answers that i can't use serial ports but i can use unused keys like f13+ keys so i use the f keys now to communicate to c# software (it listens on these f keys and as soon as they are pressed depending on the configuration it does what it needs to do).
I don't think that code is needed for this demonstration but if u need it i'll be happy to edit this.

So i made the software and now comes a problem of what happens when u plug in the device that doesn't have the driver. its useless, so i need a way for the digispark to find out if there is a software that can "reprogram" what the rotary encoder does and if there isn't use the default functions(the media keys).

Questions:

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in
Is there any way to add my program made in c# to the digispark, i got a usb headset and when i first plugged it in it installed its driver, so when i plug in my digispark can it load the program

Solutions that i think may work but i have no idea how to do them:

using one of these unused keys as Boolean, when its held down lets say by the c# software can the digispark using the trinket or any other compatible Tiny85 library determine if that key is pressed down or not (this may interfere with other software so i don't think its perfect solution)
If anyone here knows any library or custom firmware that allows the digispark(Tiny85) to communicate on serial ports that'd be pretty useful and would solve the whole question.

For the second problem: do i need any other hardware to do this as i only have a Tiny85 digispark and a rotary encoder with a breakout board

If you have a solution please provide me code or links where i may learn how to do this because as of now i have no idea how to do this, i know my way around c# but i'm a noob in arduino programming. I already asked this on stack overflow a week ago but didn't get any comments or answers. I'm sorry if this counts as a duplicate i'll remove the one on stack overflow if needed. thank you for understanding

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in

I can't think of any way to do that. That's like asking if a keyboard you plug into a USB port can tell if you have Photoshop installed or not.

  Is there any way to add my program made in c# to the digispark ...

No. The Digispark is a tiny computer based on the Attiny85 which has 8k of program memory, some of which is dedicated to a bootloader which lets you upload new code.

Your project is far too ambitious for the level of hardware you are proposing to use. In fact this video which I watched the other day comes to mind:

https://www.youtube.com/watch?v=s7AXskSxxMk

From a comment:

  the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program

OK, so you want the host computer (not the Digispark) to pretend it is holding down F17, and then when the Digispark is plugged in it checks if F17 is down, and if so it knows that the desired program is running on the PC. Is that your idea?

The problem here is that the Digispark is a USB device (not a USB host). I suppose it would be possible to write a special device driver on the PC that, once the Digispark connects, would send some special code to say whether or not the program is running. However with the Digispark only having 8 KB of program memory, this extra code (on the Digispark) might be hard to fit in. Plus you would need to write your USB device driver. Plus the device driver would need to be able to query what programs are running.

I think a far simpler solution would be to have an On/Off button on the Digispark. If you plug it into a PC which has this special program running you press the button, then the Digispark sends the alternative commands to your C# program.


Connect one SD card to two devices I have a system where an Arduino controls a DSLR camera for environmental monitoring. The Arduino can power on/off the camera and control the shutter (through the standard plug for a external shutter). The Arduino record and transmit the status of the system (battery voltaje, time of the last shot, etc.).
I want the Arduino to be able to access the camera's SD card while the camera is powered off. In order to check if the pictures were actually taken and check available memory (I don't need to write to the card).
So my questions are:

If I create a contraption to connect a single card to the camera and the arduino. The fact that the card is connected to one device (although not been used) will interfere in the operation of the other?
Should I consider the use of a multiplexer or something alike to completely disconnect the data lines from one device while the other is using the card?

An SD card has two interfaces: The SPI interface is what is used by the Arduino (it is rather slow). The second one is a parallel interface, which is capable of way bigger transmission speed. It is most likely, that the camera uses that interface, since it has to transmit rather big data packets in a short time. But as I remember some pins are used for both interfaces.
We cannot know, what happens inside the camera. But providing voltage to a digital pin of a microcontroller, while it is not powered, (as it would happen, when you drive the SD card while the camera is off) can be harmful. We must assume, that this would also happen with your camera, or you risk damaging it.
Using multiplexers (or - if you find no fitting one - some simple transistors) to disconnect the camera, when you want to connect with the Arduino, seems a good idea to me. Disconnect all lines, including the supply voltage. The ground line has to stay together, though you should check with a multimeter, if the SD slot ground is the same as the shutter connector ground (if they are not, you don't want to connect these grounds). Is most likely is, but you should check it to be sure.


Creating Sine wave with DAC and feeding it back I want to produce Digital Sine wave send it to DAC0 and then receive it back as input on A0 and plot the graph. I am using Arduino Due. I wrote the following code:

#define maxSamplesNum 120
#define Sample 50000000/maxSamplesNum  // sample for the 50Hz signal expressed in microseconds

static int Table[maxSamplesNum] =                        // lookup table  for sine wave table

  {
    0x7ff, 0x86a, 0x8d5, 0x93f, 0x9a9, 0xa11, 0xa78, 0xadd, 0xb40, 0xba1,
    0xbff, 0xc5a, 0xcb2, 0xd08, 0xd59, 0xda7, 0xdf1, 0xe36, 0xe77, 0xeb4,
    0xeec, 0xf1f, 0xf4d, 0xf77, 0xf9a, 0xfb9, 0xfd2, 0xfe5, 0xff3, 0xffc,
    0xfff, 0xffc, 0xff3, 0xfe5, 0xfd2, 0xfb9, 0xf9a, 0xf77, 0xf4d, 0xf1f,
    0xeec, 0xeb4, 0xe77, 0xe36, 0xdf1, 0xda7, 0xd59, 0xd08, 0xcb2, 0xc5a,
    0xbff, 0xba1, 0xb40, 0xadd, 0xa78, 0xa11, 0x9a9, 0x93f, 0x8d5, 0x86a,
    0x7ff, 0x794, 0x729, 0x6bf, 0x655, 0x5ed, 0x586, 0x521, 0x4be, 0x45d,
    0x3ff, 0x3a4, 0x34c, 0x2f6, 0x2a5, 0x257, 0x20d, 0x1c8, 0x187, 0x14a,
    0x112, 0xdf, 0xb1, 0x87, 0x64, 0x45, 0x2c, 0x19, 0xb, 0x2,
    0x0, 0x2, 0xb, 0x19, 0x2c, 0x45, 0x64, 0x87, 0xb1, 0xdf,
    0x112, 0x14a, 0x187, 0x1c8, 0x20d, 0x257, 0x2a5, 0x2f6, 0x34c, 0x3a4,
    0x3ff, 0x45d, 0x4be, 0x521, 0x586, 0x5ed, 0x655, 0x6bf, 0x729, 0x794
  };

int i = 0;
int sample;
int sensorPin = A0;
int sensorValue = 0;

void setup() {
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit

}

void loop() {

  sample = 50;

  analogWrite(DAC0, Table[i]);  // write the selected waveform on DAC0

  i++;
  if(i == maxSamplesNum)  // Reset the counter to repeat the wave
    i = 0;

  delayMicroseconds(sample);  // Hold the sample value for the sample time
  sensorValue = analogRead(sensorPin);
}

I want to create 3.3V (P-P) sine wave but I don't how to set the amplitude in this wave.

Also I would like to redirect the sine wave output from DAC0 to A0 Pin and plot the graph to check if the sine wave generated was successful.
How do I plot the graph ?

Update : I uploaded the program but there was no result. I tried to read data from A0 but there wasn't any output. What am I doing wrong ?

I ran your code unmodified and plugged in an oscilloscope to look at DAC0 (looks an OK sine wave) and A0 (looks flatline). Hope this helps.


Using Multiple 4 Digit displays with the same pins I currently have a ton of 4 Digit 7 Segmented displays(TOFD-5465GGH-B).

The display is driven by a PT6961 LED Driver. Using a Library that I found here I was able to use the display with no issues. The pin out on the display is as such:

1) 5V
2) CS
3) CLK
4) DIN
5) DOUT
6) Common

Since the display has a DOUT does this mean I can run multiple display is series off of the same pins? If so, can someone point me in the right direction to do so. I am currently using a Particle Photon and I am limited as to the number of PWM pins.

That is an SPI interface.  Using multiples should be easy.  Each one has a CS pin.  When that pin is pulled low it selects that chip as the one you are talking to.  Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS.  To update any given display, you pull its CS pin low and then transmit your data.  If you pull the CS pins on two displays low at the same time you'll send the data to both.  Whichever has the CS pin pulled low on it is the one that listens.

Google SPI and do a little investigation on SPI with Arduino.  That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins.  Driving multiple things with the same pins is the whole point of SPI.

The connection would look like this for an UNO -

Pin 13  ----  CLK pin on all chips

Pin 12  ----  DOUT on all chips

Pin 11  ----  DIN on all chips

Choose a different pin on Arduino for each chip and connect to the CS pin.

To use SPI, pin 10 MUST be configured as an output.  It cannot be an input.  So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.

EDIT:

I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins.  The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.

The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software.  It just limits which pins you have to use to the ones I listed above.

EDIT AGAIN:

I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware.  It compiles but hasn't been tested.  It should work though.  Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.

PT6961_SPI.h

/*
  PT6961.h - Library for communicating with PT6961 LED driver.
  Created by Garrett Blanton January, 16, 2013.
  Released into the public domain.
*/

#ifndef PT6961_SPI_H_
#define PT6961_SPI_H_

#include "Arduino.h"
#include <SPI.h>

class PT6961
{
  public:

    PT6961(uint8_t CS);
    void initDisplay();
    void initRAM();
    void sendCmd(char cmd);
    void sendDigit(char digit, char val);
    void sendNum(int num, char colon);
    void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

    const static char _DISPLAY_6X12 = 0x02;
    const static char _DISPLAY_7X11 = 0x03;
    const static char _AUTO_INCREMENT = 0x40;
    const static char _FIXED_ADDRESS = 0x44;
    const static char _DISPLAY_OFF = 0x80;
    const static char _DISPLAY_1_16 = 0x88;
    const static char _DISPLAY_2_16 = 0x89;
    const static char _DISPLAY_4_16 = 0x8A;
    const static char _DISPLAY_10_16 = 0x8B;
    const static char _DISPLAY_11_16 = 0x8C;
    const static char _DISPLAY_12_16 = 0x8D;
    const static char _DISPLAY_13_16 = 0x8E;
    const static char _DISPLAY_14_16 = 0x8F;

  private:

    uint8_t _CS;

};

#endif

PT6961_SPI.cpp

/*
 PT6961.cpp - Library for communicating with PT6961 LED driver.
 Created by Garrett Blanton January, 16, 2013.
 Released into the public domain.
 */

//0 - A
//1 - B
//2 - C
//3 - D
//4 - E
//5 - F
//6 - G
//7 - Colon
#include "Arduino.h"
#include "PT6961_SPI.h"

PT6961::PT6961(uint8_t CS) {

    pinMode(CS, OUTPUT);
    _CS = CS;

    SPI.begin();
    SPI.setBitOrder(LSBFIRST);

}

void PT6961::initDisplay() {
    sendCmd(_DISPLAY_6X12);
    sendCmd(_AUTO_INCREMENT);
    initRAM();
    sendCmd(_DISPLAY_14_16);
}

// Initializes RAM to all zeros
void PT6961::initRAM() {
    //first clear 8 bytes of the display RAM
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);
    for (int i = 0; i < 8; i++) {
//      shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
        SPI.transfer(0x00);
    }
    digitalWrite(_CS, HIGH);
}

// Use to send command based on enumeration
void PT6961::sendCmd(char cmd) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, cmd);
    SPI.transfer(cmd);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendDigit(char digit, char val) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, digit);
//  shiftOut(_DIN, _CLK, LSBFIRST, val);
    SPI.transfer(digit);
    SPI.transfer(val);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendNum(int num, char colon) {
    int digit1 = num / 1000;
    int digit2 = (num % 1000) / 100;
    int digit3 = (num % 100) / 10;
    int digit4 = (num % 10);

    sendDigits(digit1, digit2, digit3, digit4, colon);
}

void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
        char colon) {

    const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
            0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
        SPI.transfer(DISP[digit1] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
        SPI.transfer(DISP[digit1]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
    SPI.transfer(0xC2);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
        SPI.transfer(DISP[digit2] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
        SPI.transfer(DISP[digit2]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
    SPI.transfer(0xC4);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
    SPI.transfer(DISP[digit3]);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
    SPI.transfer(0xC6);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
    SPI.transfer(DISP[digit4]);
    digitalWrite(_CS, HIGH);
}

Example.ino

#include "Arduino.h"
#include <SPI.h>
#include "PT6961_SPI.h"

PT6961 LED(10);   /// This is the pin number for CS pin on each chip
// PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
void setup()
{
     LED.initDisplay();
     Serial.begin(9600);
}

void loop()
{
     //count through 0-9,a-f
     for(int i=0; i<16; i++)
     {
          LED.sendDigits(0,0,0,i,0);
          Serial.println(i);
          delay(500);
     }
}


Error while connecting Arduino to Macbook: “serial port already in use. try quitting any programs that may be using it” I'm trying to connect to my Arduino board through a macbook pro with mac os x 10.9.3 installed. I'm following the instructions from the arduino guide and in the connection section:

  " Connect the Arduino board to your computer using the USB cable. The green power LED (labelled PWR) should go on.
  If you're using the Arduino Uno or Arduino Mega 2560, a dialog box will appear telling you that a new network interface has been detected. Click "Network Preferences...", and when it opens, simply click "Apply". The Uno or Mega 2560 will show up as "Not Configured", but it's working properly. Quit System Preferences.

I cannot see any ports that hold the USBModem port.

How to setup the connection in the right way?

I read some articles about making a lock folder and I followed them but they didn't work for me, I also tried following this article but the solution there didn't work as well.

Sorry about providing this as an answer, rather than comments; however, I do have some suggestions to troubleshoot the connection.

First, check the usb connections with lsusb

    lsusb |grep -i arduino

Similarly, you can try following the output of dmesg; though, I'm not sure about the version of dmesg your system's installation is running.  Newer version of dmesg have a "follow" option available. On my Fedora system it's:

    dmesg -wH

Check the output as you plug in the arduino for messages related to the device, such as the resulting location of the tty. As a desperate measure, you can also look in the /dev/ folder for the last modified device, and search your logs for those devices:

    ls -alrth /dev/


Pressing button stops listening on nrf24l01 I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:

Arduino 1:

#include <SPI.h>
#include <RF24.h>
#include "printf.h"
#define LED 2
#define RF_CS 8
#define RF_CSN 9
RF24 radio(8,9);
String datargb = "rgb: 000000005";
char chartosend;
char inchar;
String inradio;
int endchar = '~';
void check_radio(void);
void setup() {
  // put your setup code here, to run once:
Serial.begin(115200);
  printf_begin();
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(0x080C600C01LL);
  radio.openReadingPipe(1,0x080C600C71LL);
  radio.setPALevel(RF24_PA_MAX);
  radio.setAutoAck(true);
  radio.printDetails();
  attachInterrupt(0, check_radio, FALLING);
  radio.stopListening();
}

void loop() {
  // put your main code here, to run repeatedly:
int lnth = datargb.length();
  for(int i=0; i<lnth; i++){
      chartosend=datargb.charAt(i);

      while(!radio.write( &chartosend, sizeof(chartosend) )){}

      Serial.println("sent");
  }
  radio.write(&endchar,1);
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
radio.startListening();
    radio.read( &inchar, sizeof(inchar) );
    inradio+=inchar;
    Serial.println(inchar);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      radio.stopListening();
    }
  }
}

Arduino 2:

#include <SPI.h>
//#include <nRF24L01.h>
#include <RF24.h>
#include "printf.h"
//#include <RF24_config.h>
RF24 radio(8,10);
char data;
char chartosend;
char endchar = '~';
String inradio;
void check_radio(void);
String datargb = "To mounti tis manas tou nrf24";
void setup() {
  // put your setup code here, to run once:
  pinMode(9, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, INPUT);
  attachInterrupt(1, check_radio, FALLING);
  Serial.begin(115200);
  printf_begin();
  radio.begin();
   //radio.setRetries(2,15);
    // open pipe for writing
    radio.openReadingPipe(1,0x080C600C01LL);
    radio.openWritingPipe(0x080C600C71LL);
    radio.setPALevel(RF24_PA_MAX);
    radio.startListening();
    radio.printDetails();
    radio.setAutoAck(true);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(7)==HIGH){
  radio.stopListening();
  for(int i=0; i<28; i++){
      chartosend=datargb.charAt(i);
      while(!radio.write( &chartosend, sizeof(chartosend) )){}
      //Serial.println("sent");
  }
  radio.write(&endchar,1);

  while(digitalRead(7)==HIGH){}
  radio.startListening();
}
}
void check_radio(void){

  bool tx,fail,rx;
  radio.whatHappened(tx,fail,rx);

  if(rx){
    Serial.println("interrupt!!");
//radio.startListening();
    radio.read( &data, sizeof(data) );
    inradio+=data;
    Serial.println(data);
    if(inradio.endsWith("~")){
      Serial.println(inradio);

      if(inradio.startsWith("rgb: ")){
        analogWrite(6,inradio.substring(5,8).toInt());
        analogWrite(9,inradio.substring(8,11).toInt());
        analogWrite(5,inradio.substring(11,14).toInt());
      }
      inradio = "";
      //radio.stopListening();
    }
  }
}

Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.

@Gerber remarked:

There is probably a death-lock situation where both arduino's are trying to send data the the other, while both aren't listening. So both are waiting for the other to ack. Like I said at your previous question. Why not send all rgb data in one packet. Also, there is no need to call radio.stopListening.

You send one char, and wait for and ACK. Then you send the next char and wait for an ACK. If the other unit doesn't process the message, the buffer will will up after 3 messages, and it will no longer send an ACK (because the buffer is full), and you while loop will hang


Tone inside interrupt I am trying to play a tone with a buzzer connected on an arduino nano pin. I have also connected a reed switch with INPUT_PULLUP on INT0 and a led. The program loops continuously (it's an environmental monitor and alarm personal project) until the reed switch is set on HIGH where a function is called and the buzzer should play an one-second high pitch tone.

void doorStateChange() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();
  if (interrupt_time - last_interrupt_time > 1000)
  {
    led_B_state   = !led_B_state;
    digitalWrite(buzzPin, HIGH);
    digitalWrite(led_A_Pin, HIGH);

    if (millis() - interrupt_time <= 1000 ){
        digitalWrite(buzzPin, LOW);
        digitalWrite(led_A_Pin, LOW);
    }

  }
  last_interrupt_time = interrupt_time;
}

The interrupt is called, the Led lights up but I can't make the buzzer sound right. I 've tried with tone(buzzPin, 5000, 1000); but seems that the delay does not work - The sound is heard but after the 1000ms it continuous to work in a different tone (strange?).

The only way I could make it work is with buzzPin_state = ! buzzPin_state; where the buzzer beeps as long as the reed switch is HIGH.

I also need to say that attachInterrupt(0, doorStateChange, CHANGE);.

The information I get from googling this issue is gibberish: some say that delays don't run in interrupts, others call external functions etc.

What is the proper way to achieve this ?

Don't do delay() calls inside an ISR. In all probability it will hang indefinitely. If you want to play the tone for a second all you need to do in the ISR is set a flag, which you test in the main loop. Turn the buzzer on when the flag changes state. Remember when you did that. When a second is up turn the buzzer off again.

In fact in your case you probably don't need the interrupt at all. Test for the reed switch change in the main loop as well. Don't overcomplicate it.


Do Water sensors Rust? I'm new to Arduino and still learning the basics.
I tried reading water level by using this sensor I left it in the water for about 5 minutes then I noticed it changing color (some parts darker than other)like the water is still over it .
So my question is do Water sensors really rust ? or is it my own imagination?

Most metals will tarnish, rust, or corrode when left in water, especially in the presence of an electric current. To be safe, a water sensor should either be gold-plated or made of a conductive, insoluble, non-metallic substance.


Make a stepper motor move I am at the moment trying to make a bipolar stepper motor move.
I am interfacing it through a control board, which takes the input Step, Dir, En, and 5V.

I am providing those input signal via an Arduino, but can't get the damn thing to move. all it does it move a step forward and backwards, like it being stuck or and tries to wiggle out of something.. What could the reason be..

Here is the Code:

#include "stepper_motor.h"
int max_step = 200;
stepper_motor::stepper_motor()
{
  pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin,OUTPUT);
  pinMode(dir_pin,OUTPUT);
  pinMode(en_pin,OUTPUT);

  alive_bool = true;
  position_bool = false;
  step_count = 0;
}

void stepper_motor::step_pwm()
{

  if(position_bool==true)
  {
    //Dir pin low
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = false;
  }
  else
  {
    //Dir pin high
    delay(1000);
    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,LOW);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,LOW);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(step_pin, LOW);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    int step = 0;
    while(step < max_step)
    {
      digitalWrite(step_pin,HIGH);
      delay(1);
      digitalWrite(step_pin,LOW);
      delay(1);
    }

    //digitalWrite(en_pin,LOW);
    //position_bool = true;
  }

}

Updated step_pwm():

void stepper_motor::step_pwm()
{
    //Start -  En Low , DIR HIGH, STEP high
    //init configuration!
    digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,LOW); // Previous LOW

    delay(0.005);

    //T1-  En HIGH , DIR HIGH, STEP HIGH
    //Enable high
    //digitalWrite(step_pin, HIGH);
    //digitalWrite(dir_pin,HIGH);
    digitalWrite(en_pin,HIGH);

    delay(0.005);

    //T2-  En HIGH , DIR low, STEP HIGH
    //Direction choosen
    //digitalWrite(step_pin, HIGH);
    digitalWrite(dir_pin,LOW);
    //digitalWrite(en_pin,HIGH);

    delay(0.005);
    //T2-  En HIGH , DIR low, STEP HIGH
    //STEP  step between low and high with 2.5µs between

    while(1)
    {
      digitalWrite(step_pin,LOW);
      delay(2.5);
      digitalWrite(step_pin,HIGH);
      delay(2.5);
    }

}

The control board i am using is a ST330-v3
The motor i am using is this one
here is a little block diagram of how things are connected.

You must set EN BEFORE you set DIR.  The datasheet says EN must be high for at least 5 microseconds before you set DIR.  You should probably just set EN high when your program starts, then not fool with it until your program ends.

The next thing is that I don't see you incrementing the variable "step" anywhere.  So, if you did get the stepper to turn, it wouldn't stop.

The updated code looks like it ought to work.

You should use DelayMicroseconds instead of Delay(0.005) though.  Delay takes an integer instead of a decimal value, so you won't get what you expect.  Curse the Arduino IDE for not throwing a fit when pass a float for an int.

It looks like anything working properly is purely luck.  The board you are using(NOT an Arduino) uses 3.3V logic levels.  The ST330 says a high must be at least 4V, so if it reacts to your control signals at all it is just luck.

The 8266 outputs are rated for 12mA, the ST330 inputs need about 20mA, so you are over doing it.  The 8266 might put up with, and might just die on you.

You might be able to drive the ST330 by switching the mode of the pins.

Low would be "set pin to mode output and set low."

A high would be "set mode input."

Input mode leaves the pin floating, which the ST330 will interpret as a high.

Other than that, you could use NPN transistors to drive the ST330 inputs, then invert your output signals.

The NPN would invert your signal (a high becomes a low) so you would have to set an output to low to get a high going into the ST330.

You can use NPN transistors like this to drive the ST330:

simulate this circuit – Schematic created using CircuitLab

Setting the  GPIO from the ESP8266 to high would cause a low on the ST330 input.

Setting the GPIO pin to low would cause a high on the ST330 input.

This is the solution I would prefer if I needed to use the ESP8266 with the ST330.

If you'd like to try a purely software solution, then do this:

To send a low to the ST330 input, set the GPIO to pin mode output and set the output to low. (pinMode(step_pin,INPUT) then DigitalWrite(step_pin,LOW))
To send a high to the ST330 input, set the pin mode to INPUT (pinMode(step_pin,INPUT)

When the GPIO pin is in input mode, it floats.  It doesn't have a voltage level of its own - it acts like it is disconnected.

If that works, I'd still prefer to use the transistors.

You can avoid all of this using the UNO.  It has 5V logic levels on the outputs.


What happens if device sends data to arduino over serial port (UART) and arduino is unable to read it Suppose delay(10000) function is executed, so Arduino cannot do any other work.

  During this time if the other device sends the data to arduino what
  will happen ?

Depending on the memory available, between 16 and 256 bytes will be stored in a ring buffer. Any bytes that arrive after that will be just thrown away.

The reception code in the core is:

void HardwareSerial::_rx_complete_irq(void)
{
  if (bit_is_clear(*_ucsra, UPE0)) {
    // No Parity error, read byte and store it in the buffer if there is
    // room
    unsigned char c = *_udr;
    rx_buffer_index_t i = (unsigned int)(_rx_buffer_head + 1) % SERIAL_RX_BUFFER_SIZE;

    // if we should be storing the received character into the location
    // just before the tail (meaning that the head would advance to the
    // current location of the tail), we're about to overflow the buffer
    // and so we don't write the character or advance the head.
    if (i != _rx_buffer_tail) {
      _rx_buffer[_rx_buffer_head] = c;
      _rx_buffer_head = i;
    }
  } else {
    // Parity error, read byte but discard it
    *_udr;
  };
}


Serial ports(in 1.0.5 & Port in 1.6.11) is greyed out under tools I am running a linux distro on my pc(Ubuntu 16.04). I have installed Arduino IDE(version 1.0.5 since it's the only one available on the store) from the Ubuntu Software Center and also using the .ZIP file from the official Arduino website(version 1.6.11). When I ran IDE(1.0.5) the "Serial Port" drop-down was greyed out. Next ran the IDE(1.6.11) and again the "Port" drop-down under Tools was greyed out. I have spent hours looking online for a solution but all in vain. A tried and tested working solution will be highly appreciated.

Information on a “Serial Port Setup” page at fedorahosted.org should be adequate to sort the problem manually.  Here are a few snippets from that page, along with notes about application to the current problem.

• Use command ls -l /dev/ttyUSB* to find out the serial port's group.  For example, on my Ubuntu system that shows

crw-rw---- 1 root dialout 188, 0 Aug 20 11:13 /dev/ttyUSB0

Note, substitute for ttyUSB if the port you're concerned about doesn't start with that.

• Use command groups to find out which groups you belong to.

• The fedorahosted page says to use command sudo adduser (username) dialout to add dialout to your groups list.  I haven't tried that approach, and would be more inclined to instead try sudo usermod -a -G dialout (username) [where  “(username)” represents your username].


C++ Undefined reference to 'Class:Function()' I have these files:

Project.ino
Sensor.h
Sensor.cpp
IMU/L3G.h
IMU/L3G.cpp

Sensor.h

#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

pivate:
    L3G gyro;
};
#endif

Sensor.cpp

#include "Sensor.h"

Sensor::Sensor()
{

}
Sensor::~Sensor()
{

}

void Sensor::Init(void)
{
  if (!gyro.init())
  {
    Serial.println("Failed to autodetect gyro type!");
    while (1);
  }
  gyro.enableDefault();
}

Project.ino

#include <i2c_t3.h>
#include <EEPROM.h>
#include <Servo.h>
#include "Sensor.h"

Sensor sensor = Sensor();

void setup() {

  sensor.Init();
}

I got this error

/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:15: undefined reference to `L3G::init(unsigned char, unsigned char)'
/var/folders/8q/rbt7zf3d28b3k9t6d24k5sn00000gn/T/arduino_build_748953/sketch/Sensor.cpp:20: undefined reference to `L3G::enableDefault()'

So, what is wrong?

As Juraj rightly points out, you have a typo, which should give you the following compile time error:

In file included from sketch/Sensor.cpp:1:0:
Sensor.h:17: error: 'pivate' does not name a type
 pivate:
 ^

Here is the correct code for Sensor.h

#ifndef Sensor_h
#define Sensor_h

#include <EEPROM.h>
#include "IMU/L3G.h"

#define CUTOFF_FREQ 30
#define FREQ 400

class Sensor {
public:
    Sensor();
    ~Sensor();
    void Init(void);

private:
    L3G gyro;
};
#endif

Using Arduino IDE 1.8.5 with Teensyduino 1.42 with:

https://github.com/pololu/l3g-arduino
https://github.com/nox771/i2c_t3

However, once the typo has been corrected, as above, then I too can reproduce your problem (sort of), with these link errors:

/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Sensor()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:3: undefined reference to `L3G::L3G()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp.o: In function `Sensor::Init()':
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:14: undefined reference to `L3G::init(L3G::deviceType, L3G::sa0State)'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/sketch/Sensor.cpp:19: undefined reference to `L3G::enableDefault()'
/var/folders/kp/xv3y9k114yq2_64pf8zwh76h0000gp/T/arduino_build_136680/core/core.a(main.cpp.o): In function `main':
/Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/cores/teensy3/main.cpp:53: undefined reference to `loop'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Servo.h"
 Used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/hardware/teensy/avr/libraries/Servo
 Not used: /Volumes/Home/Users/user/Local_Apps/Arduino/Arduino1.8.5-Teensy.app/Contents/Java/libraries/Servo
Error compiling for board Teensy 3.5.

You are probably getting this error, because you have placed the files L3G.cpp and L3G.h in a folder called IMU in the same folder as your .ino file. This causes the undefined error, as, while the IDE sees the declaration in the L3G.h file, the IDE can not find the definition in the L3G.cpp file.

This is easy to resolve.

If you download the l3g-arduino-master.zip file from https://github.com/pololu/l3g-arduino, and from within the Arduino IDE you then add the zipped up L3G library to the Arduino library, using Sketch ► Include Library ► Add. ZIP Library... and then change the line

#include "IMU/L3G.h"

to

#include <L3G.h>

Then it should compile and link without a problem


Arduino Board with Microphone I have this microphone (http://www.digikey.com/product-detail/en/CMA-4544PF-W/102-1721-ND/1869981) and an Arduino Uno board. I'm trying to read audio values off of my microphone (to test the noise of something (in dB)). I'm very new at this kind of stuff so keeping it simple would really help me out! I have a bunch of different capacitors, LM386N op amps, a bread board, and many resistors. Could someone provide a code and schematic that could help me get data off of my mic? I've tried using this schematic: http://wiring.org.co/learning/basics/microphone.html
but couldn't get the code to download onto a Wiring S board due to a "timeout" error and it not being able to "connect with the programmer".

Any and all help would be much appreciated!!

Very interesting stuff. As you are new to this kind of stuff i can suggest you, instead of explaining ( because videos are cool), to watch this video that explains very clearly how to use the lm386 with some filters. That video is a project about controlling the arduino through whistling. Hope that helped.


ESP8266 occasionally stops receiving data So I have an ESP8266 board that I am using to control some LED lights. I wasn't a fan of the needing to reflash my board everytime I wanted to try a new light pattern, so I decided to send the light data over wifi (UDP), and that works for certain light patterns, but any pattern that has leds that turn on/off starts to stutter and stop after a while. If every light is on, there's no problem with the speed I'm sending data, but if there are some that are on and some off, without fail it will always stop receiving data at a certain point. I've got a couple points of failure and this is my first time messing with an arduino so I'm not sure whether the problem could be on my local program, on the program for the board, the data, my wifi, or something else.

dandavis helped me find the answer! Turns out it was a memory leak, due to some poor math on my end. All I had to do was fix that up and it worked fine.


NodeMCU ESP8266 Ver 0.1 not powering on with VIN I'm trying to power on my NodeMCU ESP8266 Ver 0.1 (thats what is written in board), via VIN and Ground with my phone charger.
I'm 100% sure that the USB charger is working, providing 5V, and that the ground and VIN are connected to the right positions.
If I use the same phone charger via the NodeMCU USB, the program blinks the builtin led alright.
If I power via VIN, it flashes when I connect the charger to DC, but the program does not work.
It seems as the NodeMCU is not powering on complety.
Bizarrely, if I short 3V and G pins, the board starts working normally as powered directly via USB port.
This is the code
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

Interesting problem. The input range for Vin is 5.5 to 10 volts. This link will give you more information: https://www.make-it.ca/nodemcu-arduino/nodemcu-details-specifications/
I would not venture to guess that your board is OK, since you short pins all kinds of nasties can happen. Also you do not state your reference point for your voltage measurements so I assume it is ground but the readings do not appear correct. How are you 100% sure that the USB charger is working, providing 5V, and that the ground and VIN are connected to the right positions. Did you measure it with the load connected? Can the charger output the voltage at the current you require?


Using an Arduino Nano, how many LEDs can I safely power? I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: http://www.instructables.com/id/Sleek-word-clock/ and this one: http://www.instructables.com/id/Personalised-Word-Clock/ A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: http://www.amazon.com/gp/product/B00SGMEH7G.

I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.

The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?

Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.

If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.

If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply.  My immediate guess is "not enough".

64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs.  That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.

So you can reduce your current requirements by not having the LEDs as bright.  Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all.  At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.

So you can come up with a compromise between the brightness you desire and the current consumed by each LED.

Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED.  When all LEDs are on that would be (5 × 64) 320mA.  That's reasonable for a linear regulator, but still will generate more heat than is really advisable.

So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator.  You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.

Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip.  There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.


Arduino serial port eats data for 3 seconds before it sends? With the source code below, I'm getting what I think to be strange behaviour with the serial port output.

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

int c = 0;
void loop() {
  Serial.println(c++);
}

Presumably what this will do is starting printing incrementing numbers, one on each line, starting from 0. However, my serial monitor only starts printing these numbers after the 3000 mark. I found this behaviour only after discovered in another sketch that I was losing data at the beginning.

Is this normal Arduino behaviour? Or a serial monitor problem? Or something else?

Is this a Leonardo or Yun?  If it is, you have to wait until the Serial object says the USB connection is really ready:

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB
}

Read this.

Because you did't wait, your loop is able to execute 3000 times before Serial actually sends something back to the PC.


delay() problem for 74HC595 and 7-segment I'm trying to run a 3-digit 7-segment using single 74HC595 based on Arduino. But I have a serious problem with delay() function. When I want to count from 000 to 999 with delay(1000), this delay function causes all digits to be off! My code is as below and I uploaded a video Click Here to understand my purpose. This problem can affect some applications like reading the temperature of DS12b20 which requires a delay itself.
//                 2        1         0
//               ----      ----      ----
//              |    |    |    |    |    |
//               ----      ----      ----
//              |    |    |    |    |    |
//               ----      ----      ----

int latch = 8; //74HC595  pin STCP
int clock = 9; //74HC595  pin SHCP
int data = 10; //74HC595  pin DS

// Each annode pin (for those that don't know think of it as an on switch when it's assigned HIGH)
int dig1 = 2; // digit0
int dig2 = 3; // digit1
int dig3 = 4; // digit2
int digit[4]={dig1, dig2, dig3};

int timer=3;
// these are bits to make the 8 bit byte accepted by the segment display the 9th is the demical point
// 0-9 then invald numbers
byte table[] = {
  B00111111, B00000110, B01011011, B01001111, B01100110,
  B01101101, B01111101, B00000111, B01111111, B01101111, B01111111
};

void setup(){
  pinMode(latch, OUTPUT);
  pinMode(clock, OUTPUT);
  pinMode(data, OUTPUT);
  pinMode(dig1, OUTPUT);
  pinMode(dig2, OUTPUT);
  pinMode(dig3, OUTPUT);
}

//this sends the data to the digit
void RunNum(int num, int SelectDigit){
  digitalWrite(latch, LOW);
  shiftOut(data, clock, MSBFIRST, table[num]);
  digitalWrite(latch, HIGH);
  digitalWrite(digit[SelectDigit], LOW);
  delay(timer);
  digitalWrite(digit[SelectDigit], HIGH);

}

//main program
void loop() {
  for (int i=0; i<10; i++){
    for (int j=0; j<10; j++){
      for (int k=0; k<10; k++){
        RunNum(k, 0);
        RunNum(j, 1);
        RunNum(i, 2);
        delay(1000);  //  <====    This line affects the project
      }
    }
  }
}

I updated my code (only void loop()) as below using millis(). You can watch the results (Click Here). But, the delay problem has not been solved so far!
const long interval = 1000;   //  1000 ms = 1 s
long previousMillis = 0;
unsigned long currentMillis=0;

//main program
void loop() {
  for (int i=0; i<10; i++){
    for (int j=0; j<10; j++){
      for (int k=0; k<10; k++){
        while (currentMillis - previousMillis < interval){
          currentMillis=millis();
          RunNum(k, 0);
          RunNum(j, 1);
          RunNum(i, 2);
        }
        previousMillis = currentMillis;
      }
    }
  }
}

With the displays which use shift register to light multiple seven segment digit blocks, the register lights up only one digit at a time. The illusion of multiple digits lit is created by fast switching the digits in round. Small delays in this cause the number to look dim, larger delays create flickering and long delays show only one digit lit. So a sketch handling this type of display must run without delays.
In this type of sketch, everything must be handled without delays, so if some sensor requires a delay, start the reading and a millis timer and after the elapsed time read the result.
There are displays using specialized chips, for example TM1637D, which handle the seven segments even if your sketch stops in delay.

adoption of the BlinkWithoutDelay basic example for your algorithm:
unsigned long previousMillis = 0;
const long interval = 1000;
int i, j, k;

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

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    k++;
    if ( k == 10) {
      k = 0;
      j++;
      if (j == 10) {
        j = 0;
        i++;
        if (i == 10) {
          i = 0;
        }
      }
    }
    Serial.print(i);
    Serial.print(j);
    Serial.println(k);
  }
}


HLK-RM04 wifi shield factory reset? I have this HLK-RM04:

It came with  no catalogue or manual
all threads about it are in Chinese
after when I found the configuration webpage and changing it to client
it wont connect and it stopped board casting hlink wifi
how could i reset to factory settings?

After very long search I found an English manual.

What does Trst means ?
I don’t understand what I must do to reset it!

Since no one has posted an answer, and I finally found one myself. Ground pin 10 for 6 seconds.


How to send unmodulated IR-Signal via cable? I need to generate en (extended) NEC signal. I have connected an Arduino with a display-device via an IR cable.

Arduino --> IR-cable --> IR-input of display device

IR-cable:

One plug is cutted and the 3 wires are connected with the arduino.

The arduino should generate NEC Signals, and the display shall react to it. Basically the arduino acts like a wired remote control.

The problem is: There are many tutorials around, that show how to do this with a sensor (e.g by using this library). But none of the tutorials says how to do it with a cable.

I found out, my previous attempts all failed, because I tried to generate a modulated NEC-signal to the display. The display however does not understand it, because there is no device that demodulates the signal. The IR sensor normally does this, which is missing in this case.

e.g.
This is, what an modulated NEC signal looks like:

00 4e ff 61

The library generates the moduled signal (pulse bursts) and this is how it works for IR sensors.

But how do I have to send my IR-command, that the display understands it? How do I send a not-modulated IR signal?

The following graphic demonstrates the issue:

I do not have IR-LED Transmitter, Amplifier, Limiter, Band Pass Filter, Demodulator, Integrator, Comparator....
I just want to create the green Output-signal directly from my Arduino

There are two major components to an infra-red signal.  One is the high frequency carrier wave signal that pulses the LED on and off.  This frequency has to match that of the receiver and is used with either a high-pass or band-pass filter to filter out ambient IR light and allow it to only react to a real signal.

The second component, and it sounds like this is the one you are interested in, is the on-off pulsing of that carrier wave in different combinations and with different timings to denote binary 0 and 1.

Without knowing what your cable actually is, and we'd need to see a datasheet to get all the proper information, all this is just surmising.

I would imagine that you provide power and ground to the emitter cable, and the third pin is a logical "on/off" signal that enables and disables the carrier frequency to the LED.  That would allow you to send any codes you like as long as you know the timing of the signal.

In the library you link to is all the timing you need in the ir_NEC.cpp file.  The times are defined as:

#define NEC_BITS          32
#define NEC_HDR_MARK    9000
#define NEC_HDR_SPACE   4500
#define NEC_BIT_MARK     560
#define NEC_ONE_SPACE   1690
#define NEC_ZERO_SPACE   560
#define NEC_RPT_SPACE   2250

The actual data format is defined in the sendNEC function:

void  IRsend::sendNEC (unsigned long data,  int nbits)
{
    // Set IR carrier frequency
    enableIROut(38);

    // Header
    mark(NEC_HDR_MARK);
    space(NEC_HDR_SPACE);

    // Data
    for (unsigned long  mask = 1UL << (nbits - 1);  mask;  mask >>= 1) {
        if (data & mask) {
            mark(NEC_BIT_MARK);
            space(NEC_ONE_SPACE);
        } else {
            mark(NEC_BIT_MARK);
            space(NEC_ZERO_SPACE);
        }
    }

    // Footer
    mark(NEC_BIT_MARK);
    space(0);  // Always end with the LED off
}

The mark and space functions take a number of microseconds to perform either an ON or OFF of the PWM signal.  That is somewhat simpler for you, since it is just an ON or OFF of a digital IO pin to control the output of the emitter cable.  So where you have a MARK you turn on the output, then delay for the specified time. For a space you turn off the output and again delay for the specified time.

So you can just replicate the operation of that sendNEC function but with your own output control and timing in it instead of using the functions in that library.

Edit: It seems the cable doesn't need power - just provide the ground connection and the signal connection.  Of course, this is assuming that it isn't just an LED on a wire.  If it is just an LED on a wire then you would need to just use the library you link to as it is.


Can I control a Z84 counter timer circuit with Arduino? Link to pin description and to the Datasheet.

I'm thinking about connecting channel outputs to LEDs and control the clock with IO-Arduino or a 555: I would program it with a 595 register.

Can someone explain me why this is a bad idea?

I wouldn't say it was a "bad" idea - pointless maybe, but not "bad". A good learning experience if nothing else.


ESP8266 Websocket issue I realize it might be dumb question, but I've been at it for a few hours and I'm going nowhere. I am trying to figure out the standard Websocket library, however I have an issue casting the uint8_t to a String, so I can work with it easily, how do I do that and is it even possible? What I want to do is, get the payload from the main function as shown in the standard library and give it as a parameter to a function I have. This is the part I need, this is part of the switch statements in the standard library.

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

   switch(type) {
     case WStype_DISCONNECTED:
     Serial.printf("[%u] Disconnected!\n", num);
   break;
   case WStype_CONNECTED:
    {
      IPAddress ip = webSocket.remoteIP(num);
      Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

      // send message to client
      webSocket.sendTXT(num, "Connected");
    }
   break;
   case WStype_TEXT:
      Serial.printf("[%u] get Text: %s\n", num, payload);
      move(payload);

you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload[length] and by cast to char* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.


LED Music Visualiser I am trying to create my own LED music visualiser for a university project but I can't seem to find anything I am looking for in terms of circuitry that I need for the project. I am using a teensy microcontroller with WS2812B LED strips. I am trying to replicate an example I came across on youtube but can't figure out what I need to do in the circuit with the tools I have available to me. I have found a frequency to voltage converter diagram which seems useful but have no idea how to set it up to send through the LED strip. I have attached below the LED visualiser I am taking inspiration from along with the link to the frequency to voltage converter diagram I want to build. Can anyone help me figure out how to create this with a Teensy microcontroller? Thanks
https://mathscinotes.files.wordpress.com/2014/03/v2f.jpg
https://www.youtube.com/watch?v=lU1GVVU9gLU

In addition to seconding the FFT approach, I'd like to point out why the F-V approach is problematic.  The circuit you linked to (and F-V circuits in general) depend on having a single-frequency input.  That is most definitely not a description of most music.  About the only thing it would work for would be solos of certain instruments that have repeating waveforms.  That rules out pianos, guitars, and all other plucked or struck string instruments (for example) since their "harmonics" are not true integer multiples of the fundamental during most of the note.  This means you can't extract the fundamental from the waveform to drive the F-V using any simple method.  (Or even any not-so-simple.)  And of course solo instruments have only minor parts in most music.  Yes, the guy in the YouTube got his LEDs to light up, but that doesn't mean he was visualizing the music in any but the crudest sense.


How to count positive electrical pulses? I have a device that has one blinking LED.
I want to count the number of blinks. I planned to do it using Arduino. I will connect two terminals of LED input to Arduino digital input pins, and I will count the number of positive voltage pulses
I just want to know if it is possible? and if yes then can you please hint the code for the same?

You should not count the number of pulses, but the number of transition from 0 to VCC volts or VCC to 0 volts (called rising resp. falling edge).

If you don't want to solder, you can also use a light dependent resistor (LDR) very close by the LED to measure the difference in brightness. See also chrisl's remark below.

The counting you can do manually (in a loop, check as often as possible or needed), or by setting up a timer to check for either rising or falling edges.

I will give the pseudo code so you can figure out the actual code:

bool _ldrPin;
unsigned long int _counter;

setup()
{
   // Set Serial
   Serial.begin(9600);

   // Set LDR
   setAnalogPin(X, INPUT);
   _ldrPin = readAnalog(X);
}

loop()
{
    if (!_ldrPin && readAnalog(X) == HIGH)
    {
        // Rising edge, increase counter
        _counter++;
        Serial.Write(_counter);
        _ldrPin = true;
    }
    else if (ldrPin && readAnalog(X) == LOW)
    {
       // Falling edge, reset status
        _ldrPin = false;
    }
}


Can I use Arduino Nano V3 to program another arduino (Pro Mini)? I was planning to buy serial to USB converter (FT232RL) to be able to program Arduino Pro Mini.
But the shop nearby offers Arduino Nano V3 at almost the same price.
Could I use this Arduino instead (and gain new microcontroller platform for free ;-)?

Yes!

Yes, you can substitute the Arduino Nano V3 for the Arduino Uno and follow the instructions here, providing that the Arduino Pro Mini is a 5V version. (Otherwise, you will have to do some voltage conversion.)

Both boards have the same SPI pins as the Arduino Uno. The connections would be as follows:

Arduino Nano --> Arduino Pro Mini
5V  ------------------->  Vcc
GND  ---------------->  GND
D10  ----------------->  RESET (10uF between RESET & GND)
D11  ----------------->  D11
D12  ----------------->  D12
D13  ----------------->  D13

The process detailed in the link can be summarized as follows:

Load the ArduinoISP sketch into the Arduino that you will use as programmer. You find it under Examples > 11. ArduinoISP > ArduinoISP.
Select the serial port of the Arduino Nano (target): Tools > Port > corresponding port number.
Wire up the two Arduinos as described.
In the Tools menu, set the programmer to the Arduino as ISP.
Select the target board: Tools > Board > Arduino Pro Mini.
Open the program to be loaded to the Arduino Pro Mini and program it by selecting Sketch > Upload using programmer


Problem with structs and pointers(?) - Mega with QueueArray I'm writing a sketch to run on a Mega that builds up an array of timestamps (using the QueueArray library and DS3231 library). I'm having a problem where a struct I'm defining and then queueing is always referring to the first in the list. The relevant bits of the code looks like this:

#include <QueueArray.h>
#include <DS3231.h>
struct payload_t
{
   unsigned long timestamp;
}

QueueArray <payload_t> dataQueue;
DS3231 clock;
RTCDateTime dt;

void setup() {
   clock.begin();
   clock.setDateTime(__DATE__, __TIME__);
}

void loop() {
    payload_t dataPayload;
    dataPayload.timestamp = getTimestamp();
    dataQueue.enqueue(dataPayload);

    payload_t tempItem = dataQueue.dequeue();

    /**
     * At this stage, the dataPayload.timestamp is correct,
     * but tempItem.timestamp will always show the value from
     * the first item in the queue
     */

    sleep(1000);
}

unsigned long getTimestamp()
{
    RTCDateTime dt = clock.getDateTime();
    return dt.unixtime;
}

As per the comment in the main() loop, the first time a packet is added to the queue, the timestamp matches. For subsequent items, the value retrieved from the queue always gives the timestamp from the first item in the queue.

I feel this is my C knowledge letting me down with something basic, but can anyone point me in the right direction?

It's not your C knowlede letting you down, it's just that you haven't gotten used yet to the weirdness of the arduino ide/compiler.

You do not need to create a main() function.

You need to create a loop() function.

main() is already defined and calls loop() in a loop.

Check any other sketch and you'll notice that it usually defines setup() and loop(), almost never main().

You must put in the setup function all the code that needs to be executed once (settings and initializations) and in the loop() function whatever needs to be executed iteratively.

Also, leave declarations out of loop() unless you want such variables to have scope (and life) limited to only one round of loop()


Error: invalid application of 'sizeof' to incomplete type 'int []' when trying to compute the size of an array in a library I have created a library that contains an array. This is the .h file:

class Lib {
  public:
    static int arr[];
};

And this is the .cpp file:

#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};

When trying to compute the size of this array from within the library, it works just fine. When trying to do this from a sketch, I get the error mentioned in the title. This is the sketch I'm using:

#include <Lib.h>

void setup() {
  sizeof(Lib::arr);
}

void loop() {}

What is the problem here?

The reason is that in your sketch you import only the header file (which is good). However, there it is an array (int[]), not the initialized array.

For that you would need to include the cpp but that is bad practice (if even possible).

So instead, create a new (constant) variable, and assign it.

(more or less pseudo code, due to lack of a compiler):

Lib.h:

class Lib {
  public:
    static int arr[];
    static int arr_length;
};

Lib.cpp:

#include "Lib.h"

int Lib::arr[] = {0, 1, 2, 3};
int Lib::arr_length = sizeof(Lib::arr);

Sketch:

#include <Lib.h>

void setup() {
  Lib::arr_length;
}

void loop() {}

See also the comment of LukasFun below. It is also possible to set the size of the array in the header file.

My advice though is keeping all assignments in the implementation (cpp) file. The header file is for defining items, the implementation file for initializing/assigning. But it works too, to initialize items in the header file.


What happens if an interrupt is triggered while sending data via serial? I would like to use an inertial sensor to measure acceleration and send the results to an Android app using a serial communication with a bluetooth Mate Gold module. The sensor provides a data ready interrupt which notifies Arduino-Mega that a new value is stored in a register of the module. The output data rate can be modified during the configuration of the sensor.
I want the information to be sent at a 10 Hz rate to the bluetooth module.

Is an interrupt at 400Hz capable of compromising the integrity of a 50 bytes long message sent at 10 Hz with a baudrate of 9600?
If yes, which approach would you recommend to correctly send the data?

Edit:
I'm using the following formula to compute the amount of time required to send N chars.

bytes x bits_per_character / bits_per_second
N x (8+2) / 9600 = N/960 secs

For N = 52:

52/960 = 0.054 secs = 54 ms

So theoretically, I can send a 54 char-long message at 18Hz with a baudrate of 9600.

Edit2
I can use the hardware serial or the Software Serial interface.

If you are on the ardruino platform, and are using the hardware serial port, you basically don't have to do anything.

The Serial library interface already uses a outgoing data-buffer (it's varies between versions, 1.5.5 has it set to 64 bytes. The arduino people keep changing it's size for no reason), where the call to Serial.print() or Serial.write() only places the bytes in question into the outgoing buffer, and the buffer is then emptied asynchronously in the background by the TX-ready (UDRE) interrupt (which is then disabled when the buffer is emptied).

Basically, all you have to do is ensure that you're not placing data into the transmit buffer from both an interrupt and the main loop(), because it's then possible for the message from the interrupt to be inserted into the middle of the message from the main loop thread.

This can be easily enough done by either guarding the call to Serial.print() with cli() sei() interrupt guards in the main loop() section (or the useless arduino analog: noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason), or simply not printing from an interrupt (which is a good idea anyways, string formatting can be slow).


Stable amplitude of amplified signal Is there any circuit with opamp where can be (by arduino) set constant output amplitude which doesn't depend on input signals amplitude?

Just a word of advice about AGC in general.  There is almost always an issue of attack (how fast the AGC reacts to a sudden increase in signal) and release (how fast it reacts to a decrease).  In most AGC cases you will need to make compromises on these two settings to avoid poor behavior from the AGC... it's not a drop-in solution with pre-determined optimum settings for every purpose.  Depending on the program material, you can get obnoxious artifacts like breathing and pumping for speech and music.  ACG is much better at slow drifting things like signal fade.  I just want you know what you might be getting into...


STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial? I just received a Nucleo F401RE and can't get my sketch to work on it because the compiler says Serial1 is not defined.
My sketch uses multiple serials because I need to use the usb serial monitor while also communicating to another device on a different serial port.

Here is a screenshot of the flags I selected.

According to the F401 specs it has at least 6 different serials, so the real question is: is there an easy way to use Serial1 and so on straight out of the box in the Arduino IDE?

I'm quite new and unexperienced to this field, so please excuse me if this question is too trivial.

Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:

HardwareSerial Serial1(PA10, PA9);

instead of just giving Serial1 for granted as you would do on a regular Arduino mega


Problem with analog pins' name when trying to connect Arduino board and Processing I am trying to use Processing with Arduino Uno board to read the change of voltage done by a potentiometer. The code is simple:

import processing.serial.*;
import cc.arduino.*;

Serial myport;
Arduino arduino;

color off = color(4, 79, 111);
color on = color(84, 145, 158);
int val=0;
float value=0;
void setup() {
  size(600, 600);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(0, Arduino.INPUT);
}

void draw() {
  stroke(on);
  value = arduino.analogRead(0);
  println(value);
  ellipse(300,300,value,value);
  delay(100);
}

My question is: For analog pins in Arduino IDE one should type A0, A1, ... but here in Processing IDE it is an error to type so. Is it possible that Processing reads the wrong pin? Because in Serial output I always get zero, however, for the same circuit in Arduino IDE the values change as I turn the potentiometer knob.
Thanks

(as suggested in comments to bump it down)

your code works ok with me. I've shorted the 3.3v to analog A0 and your code fluctuates between 679~680 in processing

If it helps, this is the software versions I'm using: Processing - 3.0.1 Arduino IDE - 1.6.6 Firmata - 2.5.0


Faster TimerOne with Teensy 4.0 (600MHz) I have a teensy 4.0 which runs at 600MHz, and is double superscaler (i.e. can execute two instructions per clock cycle, sometimes). I need an interrupt to happen faster than every microsecond. I've calculated that it's possible for the processor to run the my code at that speed with some reasonable overhead. Can TimerOne (or similar) be set to produce an interrupt more than once per microsecond?

Thanks in advance.

You can use the TeensyTimerTool for this. It provides a generic interface to the hardware timers (TMR, GPT, PIT) and 20 software timers. Since the coupling of the timer peripherals to the ARM core is rather inefficient, the software timers might be a better fit for sub micro second interrupts.
If you prefer the hardware timers I suggest to use a GPT timer (also supported by the lib). You can configure it to use a 150MHz clock instead of the standard 24MHz clock. So something like 2MHz interrupt rate should be feasible.

Documentation can be found here: https://github.com/luni64/TeensyTimerTool/wiki


Reading SMS using Arduino Uno and SIM800L and print on LCD (16x2 alphanumeric) using serial connection NEED HELP Well, I am making a device, which has to receive SMS and print the text using am LCD display. Now I have code that can receive SMS and store it into a string variable using serial connection.
Here is my code:

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;  //LCD pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
String Arsp, Grsp;
SoftwareSerial gsm(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("Testing GSM SIM800L");
  gsm.begin(9600);
  gsm.println("AT"); //checking
  delay(1000);
  gsm.println("AT+CMGF=1");  //Set to Text mode
  delay(1000);
  gsm.println("AT+CNMI=1, 2, 0, 0, 0"); //Set to notification for new message, New message indication
  lcd.begin(16, 2);
}

void loop() {
  if(gsm.available()) {
    //Check if GSM Send any data
    Grsp = gsm.readString(); //Read data received from SIM800L GSM Module
    lcd.clear(); //Clear LCD Screen
    lcd.setCursor(0,0); //Set LCD cursor to First line, first row
    for(int i = 0; i<=100; i++) {
      //Print received string character by character
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(Grsp); //Print string which received from GSM (sms, sender, sms index, receive time, etc)
        lcd.print("        ");
        lcd.print(i); //Print the string index
        delay(500);
    }
  }
}

When my Arduino Uno is connected to PC and the Arduino serial monitor is already open,
it prints correctly this text received from GSM

"  +CMT: "+995599093230","","18/01/05,16:29:57+16"  0.

In this case I sent a message with text "0". When I disconnect the USB and connect my Arduino Uno to 9V power supply and send the same message text it prints:

"  +CMTI:  "ME", "+995598403536", 40)

In this case 40 is the index of the message received. I want to get the whole string as in the first case when the USB was connected.

I using Arduino GND and 5V to power the SIM800L. What I am doing wrong? Is this due to incorrect serial connection or incorrect code error?

The PP3 battery you are trying to use is far from powerful enough to run a SIM800L. It's barely powerful enough to run an Arduino by itself for more than a couple of hours if you're lucky.

The SIM800L, as the datasheet tells us, must be powered by a supply which can provide at least 2A.

  The power supply range of SIM800L is from 3.4V to 4.4V. Recommended voltage is 4.0V. The transmitting burst will cause voltage drop and the power supply myst be able to provide sufficient current up to 2A.

The Arduino's on-board 5V regulator can't provide more than 800mA if you're lucky (far less if the incoming voltage is more than around 7V due to heat dissipation). Running from USB may allow peaks of up to 2A on a DCP USB socket without the Arduino's PTC fuse blowing.

A typical PP3 battery has an impedance of 1.7 ohms. That means a dead short circuit across the terminals would theoretically allow 9/1.7 = 5.2A maximum ever to flow. That kind of current would dissipate about 46W in heat inside the battery causing it to explode. Also at that current, given the typical low capacity of about 154mAh, the battery would be flat within about 100 seconds.

The maximum rated current for one of these batteries (at least, the maximum current shown on any of the graphs in the datasheet) is 250mA.

You need to power your SIM800L in a completely different manner, including two important things:

You need a power source that can provide 2A at the rated input voltage of your module (5V?)
That source needs to either be separate from the Arduino (except the ground, which must connect to the Arduino as well as the module) or if it is 5V may be used to directly power the Arduino through the 5V pin.


What is the Maximum Current an Arduino can Supply? I was wondering how much my Arduino I/O pin can output when it is set at Output and is at High.

I am using an Arduino Uno R3.

Thanks in Advanced.

40.0mA.

The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.

From page 299 of the data sheet for that processor...

Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up.