Resetting an Arduino with a timer I want to run an Arduino autonomously - but although I apply a watchdog sometimes the systems hangs and can only be restarted by physically interrupting the power-supply (or hitting reset). So I need an external source to do that either after x hrs or based on a condition.

Instead of using another Arduino with a MOSFET or relay I am asking myself if this couldn't be done smarter with a pure electronic component like a timer or a capacitor. I could set a pin of the Arduino on high while it is active and let this charge a capacitor or something similar - if the time/energy exceeds a certain amount (because it hangs) this would connect the reset-pin of the Arduino to ground.

Any idea how this could be achieved and what component should be used?

The following 555 circuit will produce a 170 ms low-going pulse every 24.2 hours.  You can adjust the values of the components using this calculator if you want different timing parameters.

Since the reset line of a microcontroller is configured for open-drain (meaning you can connect several inputs to it, which is a good thing since we are taking advantage of that), we need to drive it with a open-drain output.  That is what the buffer on the bottom of the circuit is for, to convert the push-pull output of the 555 to open-drain.  A typical buffer is one section of a 7407.


How to delete first voltage reading? I'm trying out a new ADC, ADS1262, below is the code. I want to discard the first voltage reading.

*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1                     // Programmable Gain = 1
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data   ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|      ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
// Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     Serial.print(volt_V,8);

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

Simplest way is to have a flag to specify whether you've read the first reading or not.  Default to zero:

int read_first = 0;

Then you can say:

if (read_first ) {
    volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
    Serial.print(volt_V,8);
}
else {
   // discarded first result, now we've read the first one
   read_first = 1;
}


Running Arduino mega on 5V power supply I'm wondering if I can run Arduino mega on 5V power supply, even though it's recommended for 6-12V. USB has only 5V right, will it be a problem? I expect to draw quite a lot of power from the 5V pin too so could it be a problem?

The 6-12V range applies only to the onboard voltage regulator(if you provide power via Vin or the barrel jack). The Arduino itself runs on 5V and the regulator needs a bit headroom above that to do the regulation.
You can run the Arduino via USB, since it has 5V, just as needed by the Arduino
And you can provide power directly to the 5V pin (with a voltage of 5V or course).
If some of your components draw a lot of power, you should never draw that current through the Arduino. You need to connect the power supply in parallel to your components and the Arduino, so that the high currents can flow past the Arduino, not through it.


How to send an email with Arduino and a WiFi shield? I want to make my Arduino connect via WiFi and then send an email. The idea is very simple, but the problem is that I've never worked with those protocols and other things before. I just wanted something that's already premade, so I would just change the information.

Is there a library or a function that sends the email?

If someone could help me to understand, so I can make it myself, that would be the best.

What you're looking for is a SMTP (Simple Mail Transport Protocol) library. A Google search finds 2 for the Arduino:

SMTPClient
This seems to be a minimal-capability SMTP-only library that piggybacks on top of a connection library.

FullIP
This seems to be a full IP package for the Arduino that works with select network devices which includes SMTP capability.


int VS uint8_t VS uint16_t This question is quite clear. What are the differences between an int, an uint8_t, and an uint16_t. I know it has to do with bytes and memory but can someone clarify me a bit?

Things I want to know:

1- How much memory does each take.

2- When to use what.

3- In the end of the day, are they that different?

You can decipher most of them yourself.

A u prefix means unsigned.
The number is the number of bits used. There's 8 bits to the byte.
The _t means it's a typedef.

So a uint8_t is an unsigned 8 bit value, so it takes 1 byte. A uint16_t is an unsigned 16 bit value, so it takes 2 bytes (16/8 = 2)

The only fuzzy one is int. That is "a signed integer value at the native size for the compiler". On an 8-bit system like the ATMega chips that is 16 bits, so 2 bytes. On 32-bit systems, like the ARM based Due, it's 32 bits, so 4 bytes.  Of the three it is the only one that changes.

Personally I rarely use int and always use uint8_t etc., since the variable type is the same no matter what architecture you compile for.  When you use int you can run into problems if you had a program that worked fine on a 32-bit ARM but then doesn't work right on an 8-bit ATMega, since the int can only store a fraction of the range of numbers on the 8-bit system compared to the 32-bit system.


SPI.H library to control APA102 I am trying to run a strip of APA102 addressable LED's using a Mini pro.

The same strip I can run using a raspberry pi using SPI so I know the Strip works and what data I need to send to get it running.

My current code is as follows and I have striped it back to the bare minimum as I see it.

It all compiles and runs but nothing on the LED strip. The stip only has data and clock that should be connected to the CLK and Data in to connect to the MOSI.

All i want is to be able to send a 32bit value,

I had also tried

uint32_t value = 0xE0ffffff

but again no luck

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

  Serial.begin(9600);

  SPI.begin();

  byte start = 0x00;
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);
  SPI.transfer(start);

  SPI.transfer(0xEF);
  SPI.transfer(255);
  SPI.transfer(0);
  SPI.transfer(10);
}

take a look at the datasheet, compare it vs. your code for any incompliance.

based on my quick reading, your code isn't consistent with the datasheet.

put the communications in a routine would help maintain uniformity.


Arduino + ultrasonic rangefinder behaving unexpectedly I'm using an HC-SR04 ultrasonic rangefinder to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given here):

#define trigPin 10
#define echoPin 12

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(9, OUTPUT);

}

void loop() {

  float duration, distance;
  digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin
  delayMicroseconds(30);

  digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
  delayMicroseconds(30);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); //Defines the duration variable

  digitalWrite(9, HIGH); //square wave oscillator
  delay(0.1+duration*0.01);
  digitalWrite(9, LOW);
  delay(0.1+duration*0.01);
}

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

I do not really understand the behaviour of your program, but I would
like to point out a couple of points that may be problematic:

Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as
the program you based yours on, yet you have a 30 µs delay. If
this extra delay makes you miss the rising edge on the echo pin, then
pulseIn() will believe it is seen the previous pulse, and it will
wait for the next raising edge before starting its measurement. Since
that next rising edge will never happen, pulseIn() will eventually
time out after one second. This is probably the silence you are
hearing.
Your sound frequency may not be what you expect, because the time
needed to run through the loop is not only the two calls to
delay(), but also the time taken by pulseIn() and the various
delayMicroseconds(). You should have more consistent timings if you
use the tone() function instead of trying to bit-bang the sound.


When using Arduino Uno as ISP does "Yikes! Invalid device signature" mean a bad connection, bad config, or bad version of avrdude? I'm using an Arduino UNO to program a pre-compiled hex image to an ATTINY45, using the avrdude in the Arduino IDE directory, on Windows 7. The Uno has the ISP sketch loaded from the examples directory and that works- the heartbeat LED pulses nicely.

On the hardware side I have this setup, except the ATTINY is surface-mount, soldered to a surfboard with all its pins verified-soldered with a voltmeter. I use a header-pin strip, held by hand to get the pins touching the surfboard, to get the signals from the Uno to the ATTINY.

Here are the command lines, which I took from looking at the IDE's debugging output:

REM set the fuse for 8MHz, so the ISP programmer can work
C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m
REM load the program
C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -Uflash:w:firefly.hex:i
REM set fuse for 1MHz, as the project requires
C:\Progra~1\Arduino\hardware/tools/avr/bin/avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0x62:m

-I try running those separately, but always get this error:

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

but sometimes the number is ff0000 or ffff00 or ffffff

I read that "Arduino uses a slightly modified version of avrdude to upload sketches to the Arduino board. The standard version queries for the board's device signature in a way not understood by the bootloader, resulting in this error." Does this mean that using the Arduino avrdude with a new ATTINY chip, no bootloader on it, would also cause that same error? In other words, is the modified avrdude incapable of querying a non-Arduino-bootloaded AVR chip?

Or does that error simply mean I don't have a good contact between all my programmer pins and the ATTINY?

And, are the fuse settings truly needed, can the Uno program the flash into an attiny running at 1MHz and thus save me some steps?

(I would just buy a "real" programmer, but need to get this code in the next two days, and am in a rural part of Nova Scotia)

I soldered wires to pads to be sure the connection was good, and used those wires for programming from the Uno. Then the programmer worked, without any edits to the command lines as posted in the question. I ran a few variations and was able to answer all my questions, and a few more besides:

The "Yikes! Invalid device signature" error was being caused by poor contact between the programmer (Uno) and the ATTINY pins.
It had nothing to do with the bootloader not being on the new microcontroller. The new ATTINY45 chip doesn't need a bootloader for the in-circuit programmer to work.
The Uno can program the ATTINY45 configured to either of its speeds, 1MHz or 8MHz. The factory settings are fine, and don't require changing the fuses.
Both avrdude versions worked for programming- the 6.1 from the author's site, and the modified one from the Arduino IDE.
avrdude can program via the Uno using any of -c avrisp, -c arduino, or -c stk500v1, it doesn't matter which.

One little question I wasn't able to answer, was what speed the Uno programs at (communication speed between the Arduino I/O pins & microcontroller being flashed). Is it related to the serial port speed? But it turned out to be not pertinent to answering this problem. Someone else can ask it if curious enough.


Adafruit TLC5947 breakout board is not working with my Arduino Uno I am trying to use this board (setup tutorial on left hand nav) with my Arduino Uno.  I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.

The simplified code I "wrote" is as follows:

#include "Adafruit_TLC5947.h"

#define NUM_TLC5974 1

#define data   3
#define clock   5
#define latch   6

Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch);

void setup() {
  tlc.begin();
}

void loop() {
  tlc.setPWM(0, 4095);
  tlc.write();
}

  Scroll to the bottom for reference. (TLC5947)

This compiles and uploads successfully.  I have DIN connected to 3, CLK to 5, and LAT to 6.  V+ is connected to the Arduino 5V pin, and GND to Arduino ground.

Using this setup, the LED does not turn on when connected to channel 0 on the board.  Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V.  Checking voltage on the board between GND and V+, I see 4.8V, which looks good.  Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.

I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.

Why is this not working?

... the LED does not turn on when connected to channel 0 on the board. [...] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.

From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current sinks, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.


smaller program bigger sketch I'm working on a program composed by several classes.
I reduced the size of a single class of (more or less) one hundred lines (4kb of stuff)
I expected a smaller sketch but surprisingly it is increased in size (few bytes).

How is it possible?It's something about the compiler?

A compiler translates c/cpp to target assembly language.

To keep it short, some c/cpp language statements or keywords can be used to shorten the code (in c/cpp)... but the mechanics behind all that to translate to assembly can generate more instructions than you thought.

It would maybe be easier to explain if you put some example...


How do I set up an Arduino to be a wireless HID? The question below describes how to set up an Arduino as an HID (Human Input Device -- like a keyboard, mouse, etc.).  How can I set up an Arduino as a wireless HID?
I'm flexible as to the wireless format.  Bluetooth, USB receiver, or any other format is acceptable.
Arduino as USB HID

I'm not sure for Arduino, but it has been done with ESP32. If you have not yet spent the money into a Bluetooth module for Arduino, you'll find that the ESP32 is not expensive either.
You can find the code on Github. The author uses a TinyPico because it's pin compatible with one of his earlier projects. IMHO, any ESP32 should do as well.
The key thing is to
#include <BleKeyboard.h>

the ESP32 BLE Keyboard library that you need to download and install. That library comes with example code that should be easy to adapt to your needs.
You can program the ESP32 in Arduino IDE, but you need to add support for the boards by adding a URL to the board manager.
Have fun with the project. It sounds very interesting. Maybe I try that myself.


Is there some hardware that can be used to upload sketch source code via USB flash disk (Automatically By plugging it in) Well am asking this basically to know if it is possible to create a bootable flash drive that automatically uploads any source code onto the arduino just like creating a bootable flash drive when installing windows operating system on a computer. I will be happy to get some cool responses that would be helpful thanks.

There is a solution with SD card and SD bootloader. You put a bin file on SD card, insert it into the SD adapter and power up the Arduino. The bootloader loads the bin file to flash memory.

I use 'avr_boot' SD bootloader by Zevero. It reads a file named firmware.bin from SD card if present and loads it into flash.

To generate a bin file for Arduino AVR boards add to platform.txt

recipe.objcopy.bin.pattern="{compiler.path}{compiler.elf2hex.cmd}" -O binary {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.bin"

I use this with the ArduinoOTA library which uploads the bin file from IDE to the SD card over network and then resets the MCU for the bootloader to apply the bin.

btw: the ArduinoOTA library can use the upper half of the flash memory too to store the uploaded bin and then activate a modified Optiboot to copy the bin to run location and reset the MCU.


Bluetooth: sync time from an NTP server via Internet connection shared with Android phone I saw that it is possible to sync time from an NTP server over WiFi. I have the HC-06 Bluetooth module and an Android phone that can share its Internet connection with Arduino via Bluetooth. Would it be possible to sync time/date using this infrastructure? And if yes - how (which libraries, etc..)? Has anybody done it already and there is a tutorial on that?

No, not really. It is possible, but not easily like you want it to be. The HC-06 is a Bluetooth-Serial bridge. In the Bluetooth protocol there are many types of interfaces, that a client device might expose to the master. A Bluetooth mouse exposes a HID interface, a headset exposes a corresponding audio interface and the HC-06 exposes a pure Serial interface. Thus the HC-06 does not support what ever interface is used for tethering.

Ways, that may make it possible:

Change the firmware of the HC-06 for exposing the correct interface and interact with it. For this you need to know how to reprogram the HC-06 and how exactly bluetooth works. I guess this is over your current level.
Write an app for your Andriod smartphone, which plays the Serial-Internet bridge on the phone. The app would translate between Serial and Internet, involving your own protocol on the Serial interface. Easiest, when you just make a specialized app for syncing time, so that it does not have to do any other communication.

And at that point it is just too much work to go either way. It is unlikely, that you find libraries or any code for this, since it just doesn't make much sense. Instead you could move from an Arduino to an ESP, which can directly connect to the WiFi network in question and thus get directly the time from the internet, without tethering. That is way easier and you can use the many libraries, that already exist for that problem.


Const data optimisation for Arduino I'm taking a course on Arduino Uno programming and on today's talk I heard that the const data is optimized by Arduino, so that it occupies less space than the actual data type (namely, a const int occupies less than an int).

If instead of int I use const uint8_t, const uint16_t etc. is the optimization still applied, or does using the 8 and 16 bit ints represent bad practice?

This question is not really about the Arduino. It is about GNU C/C++ compiler optimizations.

By adding the keyword const the compiler can do a lot of optimization. One is that the value does not need to be stored in SRAM. The value can end up as part of an instruction, become part of an expression that is evaluated at compile-time, etc.

In the Arduino-GPIO library static const member data is used to allow the compiler to optimize to a single instruction digitalRead() with almost X100 performance improvement (on Arduino Mega).

Check GCC and AVR optimizations for further details.

http://www.nongnu.org/avr-libc/user-manual/using_tools.html
https://gcc.gnu.org/wiki/avr-gcc
http://www.linuxjournal.com/article/7269

Cheers!


Mac Power via Keyboard Shortcut? many mac keyboards have a power button. Is there a way to mimic this power button shortcut from an arduino?

There are multiple ways to do that.

You could use an Arduino Leonardo as a keyboard, then send a shortcut command to shut down or sleep the computer. You can edit these from System Preferences>Keyboard>Shorcuts>Services.
The keycode 0x66 does not work for mac, but may for other operating systems source
You could write a small program (I'd do it in Python) which communicates with the Arduino over the serial port and shuts down the Mac if the Arduino wants it to.
You could sacrifice an USB keyboard and use a relay to "press" the power key.


Erratic readings on Analogread with low voltages I am using Arduino Uno for measuring sensor voltages. I am using multiplexer to switch between different sensors. The readings measured in the range of 800-900 mv are accurate, but at low millivolts (at about 20 mv) they are erratic. I read repeatedly to get average of 20 values. I get values such as 1.3, 1,4, 2,0, 3.8 etc.
Can any one help on why it is happening and how to avoid it.

Additional information: I am using reference voltage of 1.25 volt for better resolution.
I tried having delay between two readings, though there is some improvement, still the problem persists.

I appreciate the help by experts.
Thanks

You are almost certainly running into the noise floor for your setup. When your target signal is a very low voltage your signal to noise ratio (SNR) is small. Because it is the noise floor setting the ADC for better resolution didn't help much. There are many ways to deal with noise. If your signal is "slow" and your noise is random you can try oversampling. If the noise is from the power supply you can add filtering on the input to your sensor. If you have done those and still want to reduce noise more you can try adding shielding to your device/wires.


how to set the pin 13 only HIGH for 1 minute if sensor at pin 8 give HIGH? int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13,OUTPUT);
  pinMode(8,INPUT);
}

void loop() {
  val = digitalRead(8);
  if(val == HIGH)
  {
    digitalWrite(13,HIGH);
  }
  else
  {
    digitalWrite(13,LOW);
  }

  delay(0);
}

Just add delay after you turn on pin 13. So it would be:

int PUMP = 13;
int sensor = 8;
int val;

void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, INPUT);
}

void loop() {

  val = digitalRead(8);

  if (val == HIGH)
  {
    digitalWrite(13, HIGH);
    delay(60000); //60000ms is 1 minute
  }
  else
  {
    digitalWrite(13, LOW);
  }
}


driver is not showing up in Port assignments mac arduino nano, the driver is not showing up in Port assignments. It has worked with this operating system before. I’ve messed something up.  “OS X EI Capitan ver. 10.11.3 I have check the posts but the serial port is a no show

If the port showed in earlier versions of OS X, but never showed after upgrading to El Capitan, then you probably used an unsigned driver, which is no longer allowed by Apple's new System Integrity Protection (a.k.a. "Rootless"; more details in a WWDC session).

Any unsigned drivers will have been disabled during the upgrade process. Even more, SIP does not allow any non-Apple files in /System, /bin, /sbin and /usr (except for /usr/local), so anything you had put in there will have been moved away as well. To see what has been disabled:

ls -l "/Incompatible Software"
ls -lR /Library/SystemMigration/History/Migration-*/QuarantineRoot/*

To get it working again: find a signed driver, or Switch off SIP.


My stepper motor connected to a driver and an Arduino is not working I'm using a 28BYJ-48 stepper motor with a ULN2003 driver board. I'm trying to control the motor using an Arduino MEGA. I initially connected the pins on the driver: IN1,2,3,4 to pins of the Arduino: 8,9,10,11 respectively; as was given in a youtube video I referred to(https://www.youtube.com/watch?v=HdqCtAJxhrs). The power for the motor was given from the 5V and GND ports in the Arduino. What happens is that it rotates 180 degrees,and then stops and then goes at random angles and stops. This was the code:

#include <Stepper.h>

Stepper stepper1(64,8,9,10,11);
int a=1;

void setup() {
  stepper1.setSpeed(50);
}

void loop() {
  while(a<10){
    stepper1.step(2048);
    delay(1000);
    a++;
  }
}

For those who missed the comments, what I made a mistake in, as @JRobert pointed is that I was suppose to have connected the stepper motor to a separate power supply as the Arduino was not capable of so much resources. I also altered the code as I think I had gotten the steps-per-revolution wrong which is needed in the Stepper function in the Arduino Code. One needs to check this with the datasheet or somewhere online for the respective stepper motor model. The final code that got it working is here. All thanks to @JRobert for helping me figure out the solution :)


Controlling Arduino through MATLAB? I had a Roboteq motor controller, but it wasn't fast enough. I'm hoping Arduino will be faster.

Supposing that the transfer is fast enough for my purposes, how can I read angular velocity, given that I have an encoder? Honestly, I'm not totally sure how to hook it up to an Arduino board.
I can't find a name for my encoder... This is the datasheet though.

Can anyone help me with how to hook it up, and what commands to use in MATLAB?

Thanks.

Do all the processing on the Arduino, and supply the results to Matlab over serial.

I'm not 100% sure about your particular encoder, but generally encoders talk in "Grey Code".  This is a series of bits which allow you to know the direction the encoder has turned.

There are a number of libraries and tutorials for Arduino dealing with encoders.

http://playground.arduino.cc/Main/RotaryEncoders
http://www.hobbytronics.co.uk/arduino-tutorial6-rotary-encoder

The one I use comes from here:

http://www.pjrc.com/teensy/td_libs_Encoder.html

It would be best to use a library with interrupt routines on pins 2 & 3 (these support external hardware interrupts), so whenever the pin gets a signal from the encoder, the Arduino can act on it immediately.  If you do not use these pins, and have time-consuming processing in the loop(), it's easy to miss 'ticks' from the encoder.

#include <Serial.h>

// Rotary Encoder (Interrupt Driven)
#define ENCODER_PIN_A       2 /* must be pin2 for interrupt */
#define ENCODER_PIN_B       3 /* must be pin3 for interrupt */
#define ENCODER_OPTIMIZE_INTERRUPTS
#include <Encoder.h>
Encoder encoder(ENCODER_PIN_A,ENCODER_PIN_B);

void setup()
{
    Serial.begin(115200);
    // Gentlemen, start your encoders
    pinMode(ENCODER_PIN_A,INPUT_PULLUP);
    pinMode(ENCODER_PIN_B,INPUT_PULLUP);
}

void loop()
{
    unsigned long start_time = millis();
    Serial.println("Dear Matlab...");

    while (1)
    {
        unsigned long now = millis();
        unsigned int encoder_value = encoder.read();

        // Do whatever angular velocity processing is needed here
        unsigned long ticks_per_ms = encoder_value / (now - start_time);

        // Send the result back to Matlab
        Serial.println(ticks_per_ms,DEC);
    }
}

I think for your encoder the "A" and "B" outputs are where the grey code will be coming from.  These would be connected to Arduino pins 2 & 3.

Obviously the code above is not a complete solution, and needs to take care of edge-conditions like overflow of millis() after some time, etc. etc.


Holding buttons (keyboard) I made a wireless keyboard, but I just need 4 button for my project: left control, left shift, F1, F2.
The problem: When I hold button - it acts like many key presses and releases, but I need, that when I press & hold button - it also acts like I press & hold it.
Could you please help me?
Here is source code:
Transfer_e5.ino:  https://www.paste.org/108039
Receiver_e5.ino:  https://www.paste.org/108040
Or 1 rar package:
https://easyupload.io/o3c5sp
Thank you
Or I can put them just here, if you wish.
Receiver:
#include <Keyboard.h>
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7); // (ce,cs)
RF24Network network(radio);

const uint16_t this_node = 00;
const uint16_t other_node = 03;

unsigned int laser_state=0;
const unsigned long my_interval = 500;
unsigned long last_sent;
unsigned int income=0;

void setup(void)
{
  Serial.begin(115200);
  pinMode(9,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
}

void loop(void){
  digitalWrite(4,LOW);
  network.update();

  if ( network.available() ) {
    RF24NetworkHeader header;
    network.read(header,&income,sizeof(income));

    if(income==10){
      Serial.println("f1");
      Keyboard.press(KEY_F1);
      income=0;
    }

    if(income==11){
      Serial.println("f2");
      Keyboard.press(KEY_F2);
      income=0;
    }

    if(income==12){
      Serial.println("ctrl");
      Keyboard.press(KEY_LEFT_CTRL);
      income=0;
    }

    if(income==13){
      Serial.println("shift");
      Keyboard.press(KEY_LEFT_SHIFT);
      income=0;
    }

    Keyboard.releaseAll();
  }

  unsigned long now = millis();

  if ( now - last_sent >= my_interval  )
  {
//    Serial.print("pin ");
//    Serial.println(digitalRead(9));
    last_sent = now;
    laser_state = digitalRead(9);

    RF24NetworkHeader header(other_node);
    bool ok = network.write(header,&laser_state,sizeof(laser_state));
  }
}

Transfer
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7);
RF24Network network(radio);

const uint16_t this_node = 03;
const uint16_t other_node = 00;

unsigned int laser_state=0;
const unsigned long interval = 5;
unsigned long last_sent;

unsigned int b1=1;
unsigned int b2=1;
unsigned int b3=1;
unsigned int b4=1;

unsigned int d1=10;
unsigned int d2=11;
unsigned int d3=12;
unsigned int d4=13;

//TR1
int btn1 = 3;
int btn2 = 4;
int btn3 = 5;
int btn4 = 6;

void setup(void)
{
//  Serial.begin(9600);
  pinMode(btn1,INPUT_PULLUP);
  pinMode(btn2,INPUT_PULLUP);
  pinMode(btn3,INPUT_PULLUP);
  pinMode(btn4,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);
}

void loop(void){
  network.update();

  unsigned long now = millis();

  if ( now - last_sent >= interval  )
  {
    last_sent = now;

    b1 = digitalRead(btn1);
    b2 = digitalRead(btn2);
    b3 = digitalRead(btn3);
    b4 = digitalRead(btn4);

    if(b1==0){
//      Serial.println("F1");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d1,sizeof(d1));
    }

    if(b2==0){
//      Serial.println("F2");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d2,sizeof(d2));
    }

     if(b3==0){
//      Serial.println("Ctrl");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d3,sizeof(d3));
    }

    if(b4==0){
//      Serial.println("Shift");
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,&d4,sizeof(d4));
    }
  }
}

The root problem is that you send each several ms new key event and on receiver each time you get this event, you call Keyboard.press and right away Keyboard.release. So, it behaves as several key press-releases.
At sender side you should send 2 types of events:

Key pressed (and which button)
Key released (and which button)

At receiver side you should

When you receive "press" event, call Keyboard.press, and don't call Keyboard.release
When you receive "release" event, call Keyboard.release

Edit: I've made changes to your source code, please, try it
Transfer
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7);
RF24Network network(radio);

const uint16_t this_node = 03;
const uint16_t other_node = 00;

unsigned int laser_state=0;
const unsigned long interval = 5;
unsigned long last_sent;

unsigned int b1=1;
unsigned int b2=1;
unsigned int b3=1;
unsigned int b4=1;

unsigned int d1=10;
unsigned int d2=11;
unsigned int d3=12;
unsigned int d4=13;

//TR1
int btn1 = 3;
int btn2 = 4;
int btn3 = 5;
int btn4 = 6;

void setup(void)
{
//  Serial.begin(9600);
  pinMode(btn1,INPUT_PULLUP);
  pinMode(btn2,INPUT_PULLUP);
  pinMode(btn3,INPUT_PULLUP);
  pinMode(btn4,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);
}

void loop(void){
  network.update();

  unsigned long now = millis();

  if (now - last_sent >= interval)
  {
    last_sent = now;

    auto newB1 = digitalRead(btn1);
    auto newB2 = digitalRead(btn2);
    auto newB3 = digitalRead(btn3);
    auto newB4 = digitalRead(btn4);

    unsigned int packet[2];

    if(newB1 != b1){
//      Serial.println("F1");
      packet[0] = d1;
      packet[1] = newB1;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB2 != b2){
//      Serial.println("F2");
      packet[0] = d2;
      packet[1] = newB2;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

     if(newB3 != b3){
//      Serial.println("Ctrl");
      packet[0] = d3;
      packet[1] = newB3;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    if(newB4 != b4){
//      Serial.println("Shift");
      packet[0] = d4;
      packet[1] = newB4;
      RF24NetworkHeader header(other_node);
      bool ok = network.write(header,packet,sizeof(packet));
    }

    b1 = newB1;
    b2 = newB2;
    b3 = newB3;
    b4 = newB4;
  }
}

Receiver
#include <Keyboard.h>
#include <RF24Network.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(8,7); // (ce,cs)
RF24Network network(radio);

const uint16_t this_node = 00;
const uint16_t other_node = 03;

unsigned int laser_state=0;
const unsigned long my_interval = 500;
unsigned long last_sent;

void setup(void)
{
  Serial.begin(115200);
  pinMode(9,INPUT_PULLUP);

  SPI.begin();
  radio.begin();
  network.begin(90,this_node);

  pinMode(4,OUTPUT);
  digitalWrite(4,LOW);
}

void loop(void){
  digitalWrite(4,LOW);
  network.update();

  unsigned int income[2] = {0, 0};

  if ( network.available() ) {
    RF24NetworkHeader header;
    network.read(header,&income,sizeof(income));

    auto keyCode = income[0];
    auto keyPress = !income[1];

    if(keyCode == 10){
      Serial.println("f1");

      if (keyPress) {
        Keyboard.press(KEY_F1);
      } else {
        Keyboard.release(KEY_F1);
      }
    }

    if(keyCode == 11){
      Serial.println("f2");

      if (keyPress) {
        Keyboard.press(KEY_F2);
      } else {
        Keyboard.release(KEY_F2);
      }
    }

    if(keyCode == 12){
      Serial.println("ctrl");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_CTRL);
      } else {
        Keyboard.release(KEY_LEFT_CTRL);
      }
    }

    if(keyCode == 13){
      Serial.println("shift");

      if (keyPress) {
        Keyboard.press(KEY_LEFT_SHIFT);
      } else {
        Keyboard.release(KEY_LEFT_SHIFT);
      }
    }

    keyCode = 0;
  }

  unsigned long now = millis();

  if ( now - last_sent >= my_interval  )
  {
//    Serial.print("pin ");
//    Serial.println(digitalRead(9));
    last_sent = now;
    laser_state = digitalRead(9);

    RF24NetworkHeader header(other_node);
    bool ok = network.write(header,&laser_state,sizeof(laser_state));
  }
}


AnalogRead value constant for a varying voltage (for LED brightness variation) Having the 11~ pin on OUTPUT mode that delivers a varying voltage (from 0 to 5 : 0 to 255).

and the A0 pin on INPUT mode to read the voltage, I find that the value read by A0 being either 0 or 1016 instead of it gradually taking multiple values between the two. what is the catch?

The circuit and the code i am using:

int volt = 0;
int sign = 1; //values: (1, -1), increments or decrements "volt" by 5.
float potential;

void setup() {

  pinMode(11, OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);

}

void loop() {

if (volt == 0){sign = 1;}
if (volt == 255){sign = -1}

volt = volt + sign * 5; //raises brightness to 255 from 0, then to 0 from 255.
analogWrite(11, volt);

potential = analogRead(A0);

Serial.println(potential);

delay(30);
/*
*/

}

As CrossRoads says, there really isn't any such thing as analog output on an Arduino. (Any Arduino unless it has a built-in DAC.) It uses pulse-width modulation to vary the "duty cycle" of the output from 100% on to 0% on, which simulates an analog voltage.

If you drive an LED with PWM (and the required current limiting resistor) your eyes will not see the flashes, and will average out the brightness based on the duty cycle of the PWM signal.

If you want an actual analog voltage from PWM you will need to add a filter capacitor to average out the voltage over time. With a simple single capacitor filter you'll still have flutter in the output but it will be closer. If you want a clean constant voltage you'll need a more complex filter.


Due: Write to digital pin when ADC is running I have a problem writing to a digital pin on Arduino Due while my ADC is running.

I have the following code:

 #undef HID_ENABLED

// Arduino Due ADC->DMA->USB 1MSPS
// by stimmer
// from http://forum.arduino.cc/index.php?topic=137635.msg1136315#msg1136315
// Input: Analog in A0
// Output: Raw stream of uint16_t in range 0-4095 on Native USB Serial/ACM

// on linux, to stop the OS cooking your data:
// stty -F /dev/ttyACM0 raw -iexten -echo -echoe -echok -echoctl -echoke -onlcr

// source: https://gist.github.com/pklaus/5921022
// applied patch 1 from: http://forum.arduino.cc/index.php?topic=137635.msg2526475#msg2526475
// applied patch 2 from:  https://gist.github.com/pklaus/5921022 comment on Apr 2, 2017 from borisbarbour

volatile int bufn,obufn;
uint16_t buf[4][256];    // 4 buffers of 256 readings

void ADC_Handler(){     // move DMA pointers to next buffer
  int f=ADC->ADC_ISR;
  if (f&(1<<27)){
   bufn=(bufn+1)&3;
   // patch 2 start
   //ADC->ADC_RNPR=(uint32_t)buf[bufn];
   ADC->ADC_RNPR=(uint32_t)buf[(bufn+1)&3];
   // patch 2 end
   ADC->ADC_RNCR=256;
  }
}

void setup() {
  SerialUSB.begin(0);
  while(!SerialUSB);

  pmc_enable_periph_clk(ID_ADC);
  adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
  ADC->ADC_MR |=0x80; // free running

  ADC->ADC_CHER=0x80;

  NVIC_EnableIRQ(ADC_IRQn);
  ADC->ADC_IDR=~(1<<27);
  ADC->ADC_IER=1<<27;
  ADC->ADC_RPR=(uint32_t)buf[0];   // DMA buffer
  ADC->ADC_RCR=256;
  ADC->ADC_RNPR=(uint32_t)buf[1]; // next DMA buffer
  ADC->ADC_RNCR=256;
  // patch 1.2 start
  //bufn=obufn=1;
  bufn=1;
  obufn=0;
  // patch 1.2 end
  ADC->ADC_PTCR=1;
  ADC->ADC_CR=2;

  // this doesn't work:
  pinMode(52, OUTPUT); //
  digitalWrite(52, HIGH); //
}

void loop(){
  // patch 1.1 start
  while((obufn + 1)%4==bufn);// wait for buffer to be full
  // patch 1.1 end
  SerialUSB.write((uint8_t *)buf[obufn],512); // send it - 512 bytes = 256 uint16_t
  obufn=(obufn+1)&3;
}

Pin 52 says 0 V.

With this function, I can pull the digital output voltage to 1.58 V:

void digitalWriteDirect(int pin, boolean val){
  if(val) g_APinDescription[pin].pPort -> PIO_SODR = g_APinDescription[pin].ulPin;
  else    g_APinDescription[pin].pPort -> PIO_CODR = g_APinDescription[pin].ulPin;
}

Any ideas?

I found the problem: The Arduino had been waiting for the SerialUSB Connection.

The Serial connection has not been established because I was running the Arduino without running the corresponding Python script. That script would have opened the Serial connection.

When running the Python script, the Arduino Due then works as expected.


How can I share one power supply between an arduino and servos? I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.
I get jittery/unresponsive servos when hooked up in the following configuration:

power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
all grounds go to top - rail
black/grey/white wires going off right side are power/ground for the servos
red, green, yellow wires going off left/top side are signals to the servos/laser
purple wire going off left/top is ground for the laser

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.
Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?
Components:

Arduino pro micro (5v)
RF Link Receiver (WRL-10532, 434 MHz)
Servo (ROB-09065, sub-micro)
Laser diode (5V, 20mA)
Micro USB breakout (1A)
USB Micro power supply (5.1V, 2.5A)

You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.
Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)


How many connections can Arduino I2C method create? I was just learning about I2C between 2 Arduinos, one as sender and another as a receiver
So I have got curiosity to know how many Arduinos can be connected to I2C connection in serial?
I mean,
Arduino1 --> Arduino2
Then can I connect Arduino3 to
Arduino 2 then again Arduino 4 to Arduino 3? Till how many Arduinos can I continue this connection?

The limiting factor is the bus capacitance. This is the limit of the total capacitance of the bus from all devices connected to it plus the capacitance of the wires used.
It is also affected by the value of the pullup resistors.
The limit, according to the specifications, is 400pF.  An Arduino has an input capacitance of 10pF.  So ignoring the wires that's an absolute limit of 40 Arduinos all connected together.
Reduce that a bit for the wires, so say 30 is a reasonable estimate. Then reduce that again if you're using the internal pullups which are about 10x bigger than they should be. That gives you a guestimate of 5-10 devices.
Use proper pullups instead of the internal ones (why oh why oh why did Arduino ever encourage and even make default such a stupid option?!?!?!) of say 1kΩ and keep wires very short and you'll probably be OK up to 20-25 devices.


How to move Servo in between three positions I want my tower pro 9g servo to start from pos=0, wait there for 1 second, then reach pos=90 wait for 1 second, then reach pos=180 and wait for 1 second. Now it goes back to pos=0 and repeats this cycle. I have written the following code for this purpose:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(12);  // attaches the servo on pin 9 to the servo object
}

void loop() {

  for (pos = 0; pos <= 180; pos += 90) { // goes from 0 degrees to 180 degrees
    // in steps of 90 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

  for (pos = 180; pos >= 0; pos -= 90) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(1000);                       // waits 1s for the servo to reach the position
  }

}

But the behavior of the servo is not correct. It moves few degree from  initial position and then comes back.

What is wrong with the logic in my code ?

The logic looks OK to me. But be aware that these servos don't perform well at or close to their limits - mine tend to jitter there but there may be other issues as well. I have 10 of these hobby servos; each has a different jitter-band at the ends of its travel. You may have better success driving them to 10, 90, and 170 degrees.


FastLED library: How can I adjust the brightness of a single pixel on an absolute scale? I'm using the FastLED library to control a digital RGB LED strip.

While this library seems very comprehensive in capability and ease of use, I do not yet see a way to simply set the brightness value of a individual pixel on an absolute scale. In other words, I want to simply set the brightness of a pixel, without passing a hue or saturation, and without it effecting other pixels.

FastLED.setBrightness() scales down the brightness of all pixels.
leds[i].fadeLightBy() scales down an individual pixel, but if it's called again for the same pixel before updating the LEDs, then the pixel will be faded again from it's already-faded value.

Is there truly no built-in method for setting the brightness of individual pixels to a particular value?

There is no dedicated function to do this, because you can just do exactly this by using the HSV color model. Hue (H) controls the color it self, S stands for saturation of the color and V is called lightness or value. That is what you try to control. Just set the LEDs color to a HSV value and change it's V value:

leds[i] = HSV(color, saturation, brightness);

While color and saturation are staying the same (to keep the same color), you can change the brightness directly with the thirds value. Note, that leds[i] is still defined as CRGB, not as HSV. This assigment uses an implicit conversion, that is defined in the library.

You can see the usage of HSV in the Cylon example of the FastLED library. There it is the Hue value, that get's changed, but it is the same principle with the brightness.

Now there is a problem to solve: The FastLED library can convert HSV colors to RGB colors, but not the other way round. So you cannot simply get the hue and saturation of an RGB color with this library. You can go 2 ways here:

You can just define an extra LEDs array with HSV colors and synchronize both arrays to contain the same data (everytime you want to change a color, you would set a HSV color in the second array, convert that array to RGB by using CRGB(hsv_leds[i]) and save that in the first array, which get's used by the FastLED library). This is relatively easy, but you effectively need double the memory for storing the color values. This is not an issue, if you have enough memory or few enough LEDs to control.
You can write your own function to convert RGB values to HSV, then use it to access the hue and saturation values of the targeted RGB color, create a new HSV color with it and the new brightness and use it to set the RGB values for the FastLED library. In this forum thread there is a brief discussion about that, though it leaves you with the implementation yourself. I think there are suitable implementations, that can be found on the web. A quick search gave me this code from github gist. I have not tested it, so I cannot say, if it really works correctly, but you should give it a try. I'm sure there are also other implementations.


Formula to calculate energy required to power an Arduino board Given an Arduino board with the following specs:

ATmega328 Arduino Nano AVR® ATmega MCU 8-Bit AVR Embedded Evaluation Board (link)

What is the mathematical formula to calculate how much energy/power would be required to keep the Arduino board on (meaning in "standby" mode, therefore not consuming any energy but the one required to keep it "alive")?

Please note I am new to all things electronics, Arduino but most importantly physics and maths. Thank you.

In the datasheet you can read how much every mode uses (normal mode, sleep mode etc). However, it also depends on which peripherals inside the CPU are active and all electronics around it. So make sure you read the datasheet of the entire development board, and not from the CPU itself.

The mathematical formula is reasonably simple: the total power is the sum of each component's Amperage * component's Voltage. But practicially this is hard to calculate.

The easiest way (but not mathematically) is probably just to measure the amperage in the development board, and the voltage and multipley them together.


Using ESP8266 core for Arduino I am working on a wireless sensor network project, in which data is collected at a central node using nRF24 modules and the RFNetwork.h library.

I want to post that to the internet using the famous ESP8266 module, which works fine when used as standalone and programmed with Arduino IDE. But the problem is how to transfer my data from Arduino to the ESP8266 as it only has one serial that is already used to program it?

I have tried to use a nRF24 module that uses SPI with an ESP-12 as it has an SPI header, but it didn't work out and I can't figure out the problem. Is there a way to use ESP core libraries like esp8266wifi.h, wifiClient.h, webserver.h etc., just like we can use the esp8266.h library that uses AT commands to communicate to ESP from an Arduino like in a master-slave manner?

Several solutions:

Are your SPI components 5V or 3.3V parts? The ESP8266 is 3.3V only, and is NOT 5V-tolerant; you may have already fried it.
In most cases that I've had problems with SPI with the ESP8266 (in particular, the Adafruit 8266-12E HUZZAH board), they went away when I drastically lowered the SPI speed to 8000000.
Once you've programmed the 8266, and assuming you don't use Serial for debugging output, it's free to use to communicate with the world. Again, be careful about signal levels -- the 8266 is NOT 5V-tolerant, and most arduinos have 5V signals. So either use a 3.3V arduino-like part (my favorite is the Teensy 3.2 for larger projects, and the Adafruit Trinket for smaller ones), or use a level converter. If you need debugging output, you can still use Serial1 for output only (and don't forget to change its bit rate -- by default it's something crazy like 74380bps).
Run the 8266 as another SPI slave and have the Arduino write to it. Or come up with your own serial protocol! Again, careful about signal levels.
You can use a different version of the 8266 (or another wifi chip), one that's already meant to be used with the Arduino. Sparkfun and Adafruit have several, as do a lot of other vendors.

I'd still suggest that you try to work out the SPI problems and stick to the 8266.

Also, don't forget that neither serial nor SPI guarantees data integrity. Always use a CRC to make sure your data were transferred correctly, and have some provision for retransmissions if you can't afford to just ignore corrupted data.

/ji


Is there any way to create some AI with Arduino? Is there any way to create some AI with Arduino?. The question is just that. I would like to give some intelligent (explore the house, trigger alarms, etc) to a rover but I dont have so much expierience. Thank you

If for IA you mean just decisions based on some inputs (sensors), yes.
The main problem on that kind of applications is the memory. The Arduino has a limited quantity of flash and Ram. Really limited.
A way to improve it, is to have a Web server and use the Arduino to send the data to your server over a WiFi module.
As said, the only limit on Arduino is the memory.


ESP8266 blink not building to esp-01 I am trying the esp8266 esp-01, and did all it asked on the arduino IDE side, but i am having problems compiling and building the blink example into the board

Using: FT232RL usb-ttl in the 3.3v configuration, two 1.6v (new) batteries to power the esp, and all the conections as indicated here (not using the led though).

when I hit (go) it compiles, but as it transfers both boards blink sincronously and I recive the following errors:

O sketch usa 219.479 bytes (50%) de espaço de armazenamento para programas. O máximo são 434.160 bytes. Variáveis globais usam 31.172 bytes (38%) de memória dinâmica, deixando 50.748 bytes para variáveis locais. O máximo são 81.920 bytes.

error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data error: failed reading byte warning: espcomm_send_command: cant receive slip payload data warning: espcomm_sync failed error: espcomm_open failed error: espcomm_upload_mem failed

I looks to me as a newbie that its trying to establish a link and failing... what could it be?

the configurations are default, programmer is "AVRISP MKII"

You did not put ESP8266 into programing mode.

the easiest way to do so is to make your own programing board, something like shown here. Go down to middle of the document to title "Writing a program to the ESP8266" where you will see a schematic of simple programing board. You will need two switches and a 10k resistor.

The voltage regulator can be omitted if you are powering it by 3.3v power. Also its a good idea to put a small capacitor (100uf) between vcc and ground to stabilize any drops in voltage which is primary cause of esp8266 rebooting it self.


Using two MIDI inputs with Arduino UNO (with one serial) Would it be possible to use TWO MIDI inputs (and a MIDI output) on an Arduino having only one RX/TX serial port? Timing will be somewhat critical so a software serial port is not usable probably. I need to listen continuously to both MIDI (in) ports not to miss messages.

Or is it better to use an Arduino Mega having 4 serial ports?

Use a Mega. SoftwareSerial is shaky at best and cripples everything else while it runs, and there really is no substitute for real hardware UARTs.

Alternatively look around and see if you can find a board based around the ATMega328-PB (note the "B") which has a second UART built in.


Decimals missing when using radio.write(); with Arduino I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.

I'm sure there's something wrong on the transmitter part of the code, but I can't see what.

Here's my code:

#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>

OneWire oneWire(4);

DallasTemperature sensors(&oneWire);

// ce,csn pins
RF24 radio(8,7);

// init data buffer to hold a sensor type byte and one uint16_t sensor data
unsigned char data[3] = {
  0};
unsigned long count=0;
void setup(void)
{
  sensors.begin();
  Serial.begin(57600);
  Serial.println("**************V1 Send Sensor Data***********");
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.setChannel(0x4c);

  // open pipe for writing
  radio.openWritingPipe(0xF0F0F0F0E1LL);

  radio.enableDynamicPayloads();
  radio.setAutoAck(true);
  radio.powerUp();
  Serial.println("...Sending");
}

void loop(void)
{

  sensors.requestTemperatures();
  float currentTemp;
  currentTemp = sensors.getTempCByIndex(0);

  //assign 'T' to represent a Temperature reading
  data[0] = 'T';

  data[1] = currentTemp;

  count++;

  sprintf(data, "T %5.2f\n", currentTemp);  // build command in data[]
  radio.txMode(strlen(data));               // set # bytes to xmit
  radio.write(data);                        // send bytes

  // print and increment the counter
  Serial.print("Temperature sent:  ");
  Serial.println(currentTemp);
  // pause a second
  delay(500);
}

In this example, when I print currentTemp, it will display the decimals, but if I print data[1], it won't.

What am I missing?

EDIT:

I've modified the code to include the answer from JRobert (updated code above), but it comes back the following error:

nrf24SendSensorDataV1_ino.cpp: In function 'void loop()':
nrf24SendSensorDataV1_ino:56: error: invalid conversion from 'unsigned char*' to 'char*'
nrf24SendSensorDataV1_ino:56: error: initializing argument 1 of 'int sprintf(char*, const char*, ...)'
nrf24SendSensorDataV1_ino:57: error: 'class RF24' has no member named 'txMode'
nrf24SendSensorDataV1_ino:57: error: invalid conversion from 'unsigned char*' to 'const char*'
nrf24SendSensorDataV1_ino:57: error: initializing argument 1 of 'size_t strlen(const char*)'
nrf24SendSensorDataV1_ino:58: error: no matching function for call to 'RF24::write(unsigned char [3])'
C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t)

Any thoughts?

EDIT 2

I've made a dirty fix that will solve the issue.

In the transmitter code I've added:

uint16_t sensorValue = currentTemp*100;
//do the bit shift to put uint16 into uint8 array
data[1] = sensorValue >> 8;
data[2] = sensorValue;
// print and increment the counter
radio.write(data, sizeof(uint16_t)+1);

This will send the (temperature value)*100

On the receiver end, I just convert the uint16_t to a float element and divide it by 100.

uint16_t sensorValue = data[2] | data[1] << 8;
float temp = (float) sensorValue/100;
Serial.print("T: ");
Serial.println(temp);

Dirty, but effective!

Many thanks guys for the help, it really pointed me and my lousy programming skills to the right direction.

Since I can't comment yet I will place this as answer.

But have you tried to use radio.print(data[1], DEC); ?

DEC stands for Decimal for if you want to force something to print it in Decimals. When you want something to be printed in Hexadecimals you can use HEX for example. Hope this will help you.


Can I use and external power supply and USB at the same time on my Arduino? Can I use the Arduino with an External wall-wart and the USB at the same time?  I need to power more LEDs, and the USB on my computer can only supply so much.  But, I didn't want to destroy my computer because I had the USB and the external plugged in.
I saw this,
External power supply?
But I am still unsure.  The reason I want to at all is because when I connected this circuit, the Arduino would cease to be recognized on the USB.  I don't know if it is because there wasn't enough power to the LED, if I short-circuited something, or something else.  I do not wish to break my laptop though.
What happens if I power the Arduino with both the USB and external power voltage simultaneously?
These all seem to indicate you don't just "plug in" with both, and you need some other kind of regulator or something.  But in that same answer, one person says,
https://arduino.stackexchange.com/a/896/69706
And that indicates when the power is plugged in the USB is cut off.  Again, my fear is breaking my laptop, and that is the main question.  Especially in light of this,
Is supplying 5V from both external 5V and USB harmful?
The external power is this,
9 VDC 1000mA regulated switching power adapter

Yes, you can simultaneously connect external power supply and USB. As explained in one of the answers, that you linked, the Arduino chooses it's power input through the supplied voltage on Vin/barrel jack. Vin has no direct connection to the VUSB, so the USB port will not get any voltage from the external supply, thus it does not get damaged.
BUT: Your thinking is wrong. Clearly your LEDs need more than 500mA. This current should never flow through the Arduino. You can easily fry the protection diode or the voltage regulator (which is an inefficient linear regulator), if you connect all the LEDs to the 5V pin. One GPIO pin can only provide about 20mA (40mA at absolute max, you should stay below 20mA) and only 100mA through all GPIOs together. They are not made to provide power, but for switching.
Instead you should connect the LEDs outside of the Arduino to the power supply. If you want to use the specified 9V power supply, you need to buy a buck switching voltage regulator, which gets the voltage down to 5V for you. Make sure, that this regulator is rated for a current significantly higher, than what you need.
How to control the LED then? That depends on your LEDs. If you just have some bare LEDs, you could use a transistor to switch the higher voltage from the Arduino. If you have a plain LED strip you can also use a transistor. Best use a MOSFET for this. If you have an addressable LED strip, just connect the power lines to the 5V output of your new switching regulator and the data line to the Arduino.


How can I send data to many IC's without using tons of shift registers? I'm building an audio circuit that will play VGM files (Video Game Music).

I have it working with two different "vintage" IC's such as the SN76489 and the AY-3-8912.

Currently, my design is using an Arduino Micro and two shift registers for the data buses and direct pins for the control pins on the audio IC's.

On average, an audio IC has 8 pins for the data bus and 4 pins for the control or address bus.  This varies per IC.  Some might be 3, some 4, some 6, etc.

Bottom line, even with the 20 IO pins on the Arduino, I will quickly run out of pins.  I thought about serializing many shift registers and basically pass 64 or 128 bit numbers to spread out to the multiple IC's but this sounds ugly.

I'd like to be able to support maybe 6 IC's which could be 60-80 pins.

I also have an Arduino DUE which has many more IO pins.  But then I have to deal with the 3.3v limit and I only have 4 level shifters (16 pins).

Any suggestions on how to handle this?

Thanks.

There are other ways,but for a brute force many pin driver solution:

Back at the beginning of time when steam driven IC's were all the vogue there was the awesome MM5450.  40 pin DIP. 34 on/off outputs. 3 pin control. Or the really keen could do it with 1` pin control and some basic RC timing. I was. I did.

Its day has passed. but, fortunately. neither Micrel or Digikey know this.

MM5450 datasheet
In stock Digikey $5.46/1

It's a very benign beat to drive once you get to know it. There is no reset (inless you buy bare dies) so you have to start off getting it synchronised  - it's not hard, just not quite usual. Works well.

For single GPIO pin control the pin acts as data out and clock with some RC timing.
Fot ICs with clock/data/load you can do all 3 with RC timing on one pin.

And there is a 44 pin PLCC pkg version available.

AND!

SN74LS673 16 bit SR, 24 pins
http://www.ti.com/product/sn74ls673

ICM7243
http://www.ebay.com/itm/ICM7243BIPL-HARRIS-40-Pin-DIP-LED-DISPLAY-DRIVER-ICM7243-7243A-/390402848376

And others
http://www.ebay.tv/sch/i.html?_sop=7&_nkw=led+driver+ic&_frs=1


Converting 8 bit binary to a hexadecimal pair as unsigned char I have a function:
void Epd::SendData(unsigned char data) {
  digitalWrite(dc_pin, HIGH);
  SpiTransfer(data);
}

At the moment I am hardcoding data sent to it by calculating on paper and then writing the result as code, but I want to improve that. For example, I am calling:
SendData(0x03);
SendData(0x1f);

To get those two values (0x03 and 0x1f) I am converting the decimal value of 799 to binary: 1100011111 and then adding 0 at the beginning to make sure my binary result is 16 digits long: 0000 0011 0001 1111. After that, I convert every 4 bits to hexadecimal value and sending them as pairs using the SendData function.
I feel like I am almost there, but I don't know how to convert my result to proper type in order to send it to the SendData function:
void Epd::SendDecAsData(int dec) {
  int binary[16];
  for (int i = 0; i < 16; i++) {
    binary[i] = dec % 2;
    dec = dec / 2;
  }

  int dec1 = binary[15] * 8 + binary[14] * 4 + binary[13] * 2 + binary[12];
  int dec2 = binary[11] * 8 + binary[10] * 4 + binary[9] * 2 + binary[8];
  int dec3 = binary[7] * 8 + binary[6] * 4 + binary[5] * 2 + binary[4];
  int dec4 = binary[3] * 8 + binary[2] * 4 + binary[1] * 2 + binary[0];

  String val1 = "0x" + String(dec1, HEX) + String(dec2, HEX);
  String val2 = "0x" + String(dec3, HEX) + String(dec4, HEX);

  SendData(val1); // error because I'm sending `String` instead of `unsigned char`
  SendData(val2);
}

I need help converting those strings (val1, val2) to the right data type, or even better, optimizing this process to get the final result in the right type with less code/computation (probably avoiding conversion to String).

As StarCat suggested, I can just send decimal values using the same function SendData I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.
This is the function I used to send decimal data in 8-bit pairs:
void Epd::SendDecAsData(int dec) {
  if (dec == 0) {
    SendData(0);
    SendData(0);
  } else {
    SendData((dec-1) / 256);
    SendData((dec-1) % 256);
  }
}


Using external power supply to power leds on multiple pins (A0-A5) I'm totally new to Arduino, and microcontrollers for that matter, so I'm having a hard time figuring out how to connect LEDs to multiple pins, but using a common external power supply...

I've created a starting light that's connected to pin A0-A4 + A5 (turn all LEDs on). I hooked each LED to its own pin directly (A0-A4) for the countdown part ("5, 4, 3, 2, 1, ..."), and then 5 additional LEDs to pin A5 ("GO!").

For the countdown part, when only one LED is on at a time, there's enough power. But if I were to light them all up at the same time, there won't be. So I figured that I should put a relay into the mix for that part, and have them draw power from an external 12 V power supply.

I did manage to make the relay work in the circuit - switching all LEDs on/off, and getting power from the external power supply, but only through one pin.

I'm not sure how to have the start lights use an external power supply, and at the same time get signals from multiple pins. How do I do that?

I'm sorry if my description is unclear. So please let me know if you need more information.

The LEDs are 3.4 V 20 mA.
The power supply I'm planning to use is 12 V.

I'm planning to have this start light - which is built in its own casing - use its own power supply, while the Arduino is running of the power from USB. So all I want to do, is to have the signals sent over to this starting light unit, and not power and ground.

UPDATE:

Here's a quick overview of how I'm testing this whole thing at the moment:

The 5 red countdown LEDs (red) is getting powered by the board itself through the pins, while the 5 "GO!" LEDs (green) are getting powered from a 12 V power supply since they're all are going to be turned on simultaneously.

My question is how I can get both the 5 red LEDs, that uses separate pins, to get powered from the external power supply as well?

Since all the LEDs are built in its own casing, apart from the microcontroller because that also handles other stuff...

Did that make any more sense at all?

Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.

Current in your Arduino:

A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.

Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

This question was answered nicely over at the electronics stack exchange.
Here's a PDF tutorial on using transistors as switches.
Found a nice reference on figuring out the transistor / resistor relationship.

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.


How to pulse a signal at 100ms to 500ms? Based on this PDF I need to pulse between 100ms and 500ms to record a video (the description is apparently wrong according to this guy). How would I generate such a pulse? The small module has 3 wires I can use, which are positive, ground, and a yellow wire. I assume I need to pulse the yellow wire.

I don't want to hook anything up wrong, but my guess would be using pulseIn(). However, I am not sure at all. Any help appreciated.

Okay, so pulsing is apparently easy enough. If I just do:

digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);

It will start recording, then turn off about a second later, start again about a second later, and then repeat. I somehow managed to get a 5 second recording as well. I'm not really sure how this is supposed to work. I need to test some more.

EDIT: Turns out the schematics were right. If I do something as simple as:

digitalWrite(13, HIGH);
delay(500);
digitalWrite(13, LOW);
delay(1000);

It will turn on the video recording and turn off whenever it gets HIGH again.


How to connect IRLZ44N to Arduino? simulate this circuit – Schematic created using CircuitLab

In above schematic;

what value should R1 have? is it even needed?
do we need that pull down resistor(R2)? if yes, 10K is enough or we need higher value like 100K resistor there?

IRLZ44N DATASHEET

It's better with resistor so output driver isn't stressed to its maximum limits. Gate has its capacitance so it's better to limit charge/discharge current for such weak source
As the gate is basically capacitor, it has really big input impedance. Without pull down resistor it'll be catching all kinds of EMI (electro-magnetic interferences). So 10k is fine. The 100k might be less unreliable if the mcu output is not active (boot/reset)


Resurrecting a fried Arduino (Bluno) USB port Slightly distractedly, I went and connected 5V to the 3.3V pin on my DFRobot Bluno (the pins are right next to each other!)

The magic smoke leaked out of the AMS1117 3.3V regulator in a neat little puff. The sketch that was loaded on the board still runs fine, but the Bluno is no longer recognised by my Macbook Pro when I plug it into USB (I have tried different ports and different cables; they're all fine—it's the USB on the Bluno that's fried.)

In an attempt to repair it, I've replaced the AMS1117 (check the third paragraph of that tutorial—ha!) with an LF33ABV; this went well and I'm now getting a stable 3.3V on the 3.3V pin. Check out my handiwork:

However, the Bluno still isn't being recognised by the USB ports on my Mac.

Is there another way to upload new sketches to the Bluno? Theoretically you can do so over BTLE, but you need another Bluno to act as the "peripheral" and I don't have one to hand. I have various other Arduinos laying about if that helps.

Upload via ICSP. See those six pins next to the regulator you so expertly tacked on? Those are the ICSP pins. You'll need a second controller or programmer to do it.

http://arduino.cc/en/Tutorial/ArduinoISP


How to use Serial.setTimeout() I am just playing with the UART interface of my board to learn about how it works. Since I have only one board, I send data out just to receive them by my own board, which is working so far.

Now I wanted to find out what Serial.setTimeout() is for. As per description on the Arduino homepage, it sets the maximum time for to wait for data. The description says, upon others Serial.find() will use it.

So I set Serial.setTimeout() to 100ms, and between sending and trying to receive data, I put a delay of 500ms. Therefore my expectation would be, Serial.find() will not detect a message, since there is more than 100ms no traffic on the bus. But I am still recieving data, it seems that the Serial.setTimeout() has no effect.

What is wrong in my understanding/usage of Serial.setTimeout()?

Here is my example sketch:

#include <M5Stack.h> // needed for my board M5Stack

HardwareSerial Serial2(2); // R2: Recieve Serial2, 17: Transmit Serial2  --> connnect pin R2 and 17

unsigned char buf_recive[1];
unsigned char buf_transmit[2] = {0x42, 0x00};

void setup()
{
  M5.begin();
  Serial.begin(9600);    // setting baud rate for COM3
  Serial2.begin(9600);   // setting baud rate for M5Stack2M5Stack communication
  Serial2.setTimeout(100);    //set the Timeout to 100ms
}

void loop()
{
  delay(500);
  // send buf_transmit
  Serial2.write(buf_transmit, 2);
  delay(500);
  // detect first byte of recieve message
  if (Serial2.find(0x42))
  { //start to read when detect 0x42
    Serial2.readBytes(buf_recive, 1);
    Serial.println(buf_recive[0]);
  }
  buf_transmit[1] = buf_transmit[1] + 0x01; // just to see that something's going on
}

And here some prove, that I am still receiving data:

The bytes are received to rx buffer with interrupt in the core. The find() function finds them there after the 500 millis delay. Timeout is to wait for the next byte if the rx buffer is empty.

The timeout is good if you know that the other side sends a collection of characters or bytes. Like for example a line sent from Serial Monitor or a Http request on networking client. The transmition has small gaps between bytes, but you want to receive it at once. So a function waiting a little for the next byte is useful.

Serial, networking Client classes and other Arduino stream classes inherit reading functions from the Stream class. This class has all the read and parse functions. There are 3 non blocking functions available, read and peek. All other read and parse functions use the timeout and wait for the next byte if the rx buffer is empty.

try this sketch with Serial Monitor

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

void loop() {
  if (Serial.available()) {
    String s = Serial.readString();
    s.trim();
    Serial.println(s);
  }
}

send a line from Serial Monitor. a couple of characters. then send fast another line and then wait longer then 10 secs and send one more.


Is it required to delete variables before going to sleep? This tutorial shows how to put the arduino to sleep and use a watchdog to wake up at intervals:
https://youtu.be/urLSDi7SD8M
I been studding c++ and as I am getting better I am instantiating objects with the new keyword. I have learned that if you create something with the new keyword you are responsible for deleting it from memory when you no longer needed. But I do not know if this applies when you put arduino to sleep.
Anyways my question is in the comments of the code:
Foo * someObject;

void setup()
{
    someObject = new Foo(arg1, arg2, ..); // crete an instance of someObject
   // init pins etc..
}

void loop()
{
     if(button1Pressed())
     {

          // **** DO I HAVE TO DELETE OBJECTS BEFORE GOING TO SLEEP? Do I need this line? ****
          delete someObject;

          gotToSleepAndWakeUpIn4Seconds() ;  // places arduino in sleep mode and wakes up again in 4 seconds

          int x = 0; // this line never executes arduino is on sleep mode and will wake up again in 4 seconds
     }

     // more code
     if(something)
        someObject->executeFunction1();

     // etc...
     // ....
}

You have probably learnt that objects created with new are stored in
the heap, while globals are stored in the .data and .bss sections, and
locals on the stack¹. This distinction, however, only exists in the
software. At the hardware level, .data, .bss, heap and stack are just
arbitrary portions of the RAM.
Think of what would happen if the RAM was erased, or somehow corrupted,
when the microcontroller sleeps. Not only would that affect the
heap-based objects, but also every variable in the program. And even the
return address from the call to gotToSleepAndWakeUpIn4Seconds() would
be lost, so the CPU would not know where to resume execution when it
wakes up. The only reasonable thing to do at wakeup would then be to
restart the program from scratch. And this is actually what happens when
you reset the microcontroller².
But a sleep is not a reset. The contents of the RAM is preserved while
sleeping. This means that the whole state of the program is preserved:
locals, globals and heap-based objects. No need to delete and re-create
stuff.
As a side note, if you can allocate memory statically, this is usually
better than dynamic allocation, ans you avoid the risk of heap
fragmentation:
Foo someObject(arg1, arg2, ..);  // static global instance

void loop()
{
    // Some code, then,

    if (something)
        someObject.executeFunction1();
}

Notes:
¹ As an optimization, locals of the current stack frame may be in CPU
registers, but this doesn't change the conclusion.
² On AVR, a warm reset doesn't loose the RAM, but it is then
reinitialized by the C runtime. A cold reset (power-cycle) does loose
the RAM.


Using Arduino Wifi Shield to Receive Signal I am trying to use an Arduino Uno with Arduino Wifi Shield 101 to receive a signal from phone or webpage over wifi so it will "initiate" my circuit. I was able to connect the board to wifi but am unsure on how I should continue. My main goal is to be able to send it two different commands that would run different parts of code in my arduino script. I am very new to this stuff! Thanks :)

Look for the Web Server example in the arduino IDE.  That will give you a starting point to allow you to control the arduino via a web page.  This tutorial is also very in depth : https://startingelectronics.org/articles/arduino/switch-and-web-page-button-LED-control/


Arduino Reaction LED game I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?

    int ledPin;
    int direction;
    int isChanging;
    unsigned long lastChange;

void setup() {
   //set pins 2 to 10 to be output
  // and LEDs off
   int pin;
    for (pin = 2; pin <= 10; pin++) {
       pinMode(pin, OUTPUT);
       digitalWrite(pin, LOW);
    }
     //set pin 11 to be input
     pinMode(11, INPUT);

     ledPin = 2;
     direction = 1;
     lastChange = millis();
  }

 void loop() {
    if (isChanging) {
    if (millis() - lastChange > 500) {
        //turn off old LED
        digitalWrite(ledPin, LOW);
        //reset time
        lastChange = millis();
        //change the led
        ledPin = ledPin + direction;
        if (ledPin > 10) {
          direction = -1;
        ledPin = 9;
      } else (ledPin < 2); {
        direction = +1;
        ledPin = 3;
     }

       //turn on new LED
        digitalWrite(ledPin, HIGH);
     }
       //check for button
       if (digitalRead(11)) {
        isChanging = 0;
     }
     }
    else {
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
       //wait for it to be pressed again
       while (!digitalRead(11)) {
     }
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
    }
   }`

Your are not explicitly initializing the variable isChanging, so the compiler sets it to 0. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.

But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:

boolean button_pressed = false;
unsigned long button_timestamp = 0;

void loop(){
  ...
  if(!button_pressed && digitalRead(11)){
    button_pressed = true;
    button_timestamp = millis();
  }
  if(button_pressed && millis() - button_timestamp > 50){
    if(digitalRead(11)){ // real button press
      button_pressed = false;
      // check, if the middle LED is ON and act accordingly
      // or, if the game hasn't started yet, start it
    } else { // just a bounce of the button, not a real button press
      button_pressed = false;
    }
  }

  // LED CODE
  if (millis() - lastChange > 500) {
    ...
  }
}

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.

Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.

For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".


Can I use Arduino to generate a 0 to 15V analog output? Is it possible to use the analog output pin with some circuit to generate a 0 to 15V analog output?

The Arduino cannot directly produce anything more than 5V.

You can use PWM and a Low-Pass Filter to produce an analog waveform between 0 and 5V, which you can then amplify using a suitable non-inverting buffer with 3x gain (op-amp), which will boost the voltage to 15V. Whether that is suitable for your needs, though, since the current will generally be quite low (most op-amps have a high output impedance) is unknown.

If you want a cleaner waveform you can attach or create a DAC which produces discrete output voltages (again between 0 and 5V) which you then amplify similarly.

simulate this circuit – Schematic created using CircuitLab

R3 and C1 form the low-pass filter and should be sized according to the frequency ranges you want to filter and keep. Note that many op-amps that can cope with the higher voltages you need aren't rail-to-rail which means you will have to use a higher power supply voltage than you want to output to leave some headroom. Similarly the 0V will be clipped and will never go below a certain voltage. If you want to get right down to 0V you will need a negative power supply to feed the V- supply of the op-amp (which is currently connected to ground in this schematic). That would allow the output to drop right down to 0V.


Connecting MPU6050 to Arduino Lilypad To preface, I am very new to Arduino and I watched this video on YouTube.

It shows how you can build a motion controlled car with Arduino and I decided to make this for my school project.

One thing I am having difficulty with is connecting the MPU6050 to the Lilypad. In the video he doesn't really show much of it and just sticks it onto the board.

However, do I need to solder the MPU6050? Where do I solder the pins the underside or the top. Do I need to align the pins with that of the Lilypad?

Sorry if it's a stupid question I genuinely don't know.

The current condition of our lilypad:

What it's supposed to look like:

If you see the images, in addition to the yellow light of the MPU 6050 and the red light of the HC 05, the red light of the Lilypad is also supposed to light up like the second picture, however in ours, only the MPU 6050 and the HC 05 lights up and not the Lilypad.

Since you seem to need some orientation, I will explain a few things, to get you started.

The MPU6050 is a device, that communicates through the I2C interface. It uses 2 communication lines (SCL for the clock and SDA for the data). To use is with the Lilypad, you have to connect those two lines, Vcc (5V) and Ground. If you look at a pinout diagram, you can identify, which of the pads are SDA and SCL on the Lilypad.

It is up to you, if you connect the mentioned lines via soldering or by other means. Normally you would solder connecting wires between the MPU6050 and the Lilypad. If you want the MPU to be removable, you can solder a cable with a pin header (for example female) to the Lilypad and the according pins to the MPU (for example a male pin header). That way, you could also stick the MPU to the board and remove it again if necessary. How you are doing it is not important, as long as the electrical contact is good.

There are also a lot of tutorials and ready to use libraries for the MPU6050 on the net. newbie already posted a link to a tutorial. Also Adafruit has a library on github with examples, that explain how to use it. That way you should be able to get started with your project.

Good luck!


How to use Serial Monitor without Arduino board? I want to use Arduino(atmega8) on breadboard using USBASP programmer and want to use Serial Monitor without using any Arduino board as ISP programmer.
My questions: 1. Is such thing possible?
2. How do I do that?

How to use Serial Monitor without Arduino board?

Yes that is possible. Connect to the RX/TX pins on the breadboard chip. Remember these are 5V. You will need an Serial-USB or RS232 adapter to connect your development machine. Please see this blog post for some inspiration.

Cheers!


What could cause AdC Reading only to get stucked? I am doing a Solar water heating contrôler with arduino.
I have had a freeze of the AdC value read (ntc probe that read Solar panels) that remained at -1.75degc. this was confirmed by the serial data sent an recorded (using raspberry and Time series database) but also the direct Reading on the LCD (16x2). After rebooting Arduino everything get back normally.
Additionnel strange thing is that the water tank ds18b20 temperature sensor serial data value showed a huge spike 1e4... That lasts less than 1 second (which Can not happen as the sensor max value is 125 deg c from this numerical sensor.). After that spike, the adc recorded value remained Frozen. The other ds28b20 and LCD menu navigation and display were ok...
Could that be related to EMI?
To SRAM overflow? Even if the rest of the program seems to work?
What could enables me to discriminates between those issues?
It seems it happened arround 2 days after the Arduino was rebooted.
Description of set up:
I am using a standalone atmega 328 with polulu programmer. 8mhz internal crystal. Everything places on veroboard (main). Then a child veroboard holds the various resistors (Pullup, pulldown) for the input signals. Another child veroboard holds the outputs (pwm pump speed driver), optocoupler for pump Relay.
The supply is a meanwell din rail 5v ac-dc concerter.
I places decoupling caps arround atmega 328, diode+ pull up resistor + cap on reset Line as i had resets regularly (they are gone now).
The pump Relay is on a separate 24v supply. Grounds are separrated from Arduino with this 24v circuit (that incluses flyback diode). But grounds are common to main and 2 children veroboards. The ntc Solar panel probe wire is twisted rj45 cat6. It is shielded and shielding is connected to the atmega grounds.
My program is non blocking type with use of millis and state machines. During developpent I checked the Time operation of the program that was running fast (no delay).
The main structure is quite straightsforward. See bellow commented:
//Get Button state and debounce
buttonLeft.launchSM();
buttonRight.launchSM();
buttonDown.launchSM();
buttonUp.launchSM();

//Menu(uses menubackend library)
menuNavigationBehavior(); // ie detect action from button pressed.Should be executed very rapidely... (less than 10 ms).
EditingVarInMenu(); // changing variables in Menu requiring speed loop (set parameters for example)

//Getting Temperature from panel1, 5 for 5 averaged values
//every 20 ms ie 20 * 5 we have a temperatuure every 100 ms.
TemperaturePanel1(5,20,Tpanel1);

//Getting Temperature from one wire. Time between fetch and return of 100 ms.
getOneWireTemp ();

//CONTROLLER---------------------------------------------------------------
//System Control Logic updated at Time loop
// Controller logic state machine execution
switch (ControllerMainState)
    {
        case CONTROL_MANUAL:
          ManualStateActions();
          break;

        case CONTROL_AUTO:
          AutoStateActions();
          break;

        case CONTROL_ERROR:
          ErrorStateActions();
          break;
    }

    //MENU DISPLAY_____________________________

    if( millis() - timer_50_ms > 200) //
         {
              timer_50_ms = timer_50_ms+200;
              displayMenu(); // change the display. Can be done less often ie every 200 ms
          }

You appear to have a difficult problem.  One of the rules I use is never power the arduino with 5V power, always use the barrel connector and go with about 8 volts. The additional filtering etc the on board power supply does is amazing. The external 5V is ok for most of the other devices. Another option would go to the local electrical store and purchase a metal junction box and mount the electronics in that complete with a metal cover. Be sure it is grounded to earth. The reason for this is your prototype assembly has a lot of antennas that will pick up just about all of the electrical noise in the area. Remember all grounds must be connected. Arduinos are not hardened for industrial or commercial controller applications.


What background do I need to have before starting Arduino? Like: basics of electrical circuits, etc..

In order to go far in Arduino and electronics.

I am a Electrical technician and bought the starter kit from the Arduino team for my 13 year old son. My plan was to try the kit to teach my son about electronics.

The end result is that he is the one showing me new stuff.

In my opinion, you do not need any special background before starting with Arduino. You should have a interest in learning something new, and in learning about electronics. To get started, buy a tutorial book and a starter kit. (Many starter-kits comes with a tutorial book) When you have gone through the book, you will have some basic knowledge and a base to continue learning from.

Good luck


Arduino ultrasonic sensor project I'm a newbie at Arduino, and I'm trying to make a project with ultrasonic sensor, I'm using the grove ultrasonic ranger, not the HC-SR04, and I already did test with distance and it worked very well, but now I need help with the code.

I need to create a vector that save the values of the distance to after calculate the speed using distance/time calculus, but the case of my project its to use in open places, so will be times that the distance will be "max" because there's nobody in the range, so I need a condition to exclude those values of the array (the maximum distance printed when the sensor can't feel nothing is 516 cm)
I'm not experienced with Arduino coding, so please help me, in anex is my code for basic scanning.

#include "Ultrasonic.h"

Ultrasonic ultrasonic(7);
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    long RangeInCentimeters;
    Serial.println("The distance to obstacles in front is: ");

    // two measurements should keep an interval
    RangeInCentimeters = ultrasonic.MeasureInCentimeters();
    if(RangeInCentimeters > 400)
    Serial.print ("distancia nula");
    else
    Serial.print(RangeInCentimeters);//0~400cm
    Serial.println(" cm");
    delay(1000);
}

If you don't know how many data points will be recorded, look into vectors or an external storage device. Alternatively you could use a circular array if you don't mind losing recorded data after a while.

If you know how many data points will be recorded, a basic array will suffice.

As for excluding invalid values:

// Keep trying to get a valid data point
While (RangeInCentimeters > 512 && RangeInCentimeters < 400)
{
 delay(200);  // The minimum value of this delay depends on the sample rate of your sensor
 RangeInCentimeters = ultrasonic.MeasureInCentimeters();
}

//... Store data to array/linked list/etc

I changed your max range to 512 because this is likely the max real value (2^9 = 512).