Can I use the microchip of Arduino Uno as a standalone microcontroller

Yes it's possible. To use the ATmega328P to "emulate" an Arduino Uno board (without the USB part) you just need 3 ou 4 additional components: the oscillator, two capacitors and a resistor. Please take a look at: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoToBreadboard for a schematic/breadboard.
The Atmega328P features itself the memory, cpu and flash so those components are already inside the chip. You can find the relation of the pins in this image:


Why doesn't my code work in a function, yet works inline?

The problem is that you are passing the value of the ports to the function, not the address of the ports.

You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the actual port variable not the copy of the value that you pass.

The simplest way is to modify your function to be:

void shiftOutFast(volatile uint8_t &dataPort, uint8_t dataBit,
                  volatile uint8_t &clkPort, uint8_t clkBit,
                  uint8_t bitOrder, uint8_t val) {
....
}

That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.

Note that only the "port" variables need to be passed by reference, all the others remain as pass by value.  Also they should be, as Edgar says, flagged as volatile.


@EdgarBonet has it - hv_startup() is part of the the interrupt handler. Interrupt handlers should be as short (timewise) as possible, doing only what has to be done with the interrupts off, and leaving longer tasks for the mainline (loop() and its sub-functions) to do.

But a bigger problem is that loop() is called from hv_startup(), also getting used as part of the interrupt handler, and loop() has a while{} loop that depends on hv_bool, which can never get changed, 1) because there is no statement to set it false (besides the initialization); and 2) because loop is now running at interrupt level and no more interrupts (at the same level) can be taken.

So I'd suggest several fixes:

Don't call loop from your interrupt handler. When your handler exits, loop() will resume from wherever it was when it got interrupted.
Don't delay in your interrupt handlers. If the interrupting hardware needs to be reset, do that and any other processing you have to do while the interrupts are off. But if some longer processing needs doing, set a flag in the interrupt handler (remember to declare it to be 'volatile'!), and exit.

In loop(), test the flag. If it is set, clear it and call another function to handle the less urgent processing required by the interrupt.


Instead of printing "10" or "9" etc, print "10 " or "9 ".  Add an extra space at the end of what you print which overwrites the character that was there before.

mydisp.print(val);
mydisp.print("  ");

I used 2 spaces there, in case you go from 3 digits straight to 1.

Another method is to "format" the number using sprintf:

char temp[4];
sprintf(temp, "%3d", val);
mydisp.print(temp);


Can ZigBee API and ZigBee AT work together in the same network?

My question has been answered on Stack Overflow, if you ask

https://stackoverflow.com/questions/28765288/can-zigbee-api-and-zigbee-at-modules-work-together-in-the-same-network


Why would the resistor be after the LED in this project?

It does not matter if a resistor is before or after a component, see the circuits below.

The resistor reduces the current, and this is true for the path where the resistor is in (until the interconnections before/after the resistor). In the examples there is only one path.

simulate this circuit – Schematic created using CircuitLab


The library, as it stands, doesn't support direct sending from PROGMEM.  However it's not too hard to get around that - if your C++ is up to it.

The IRsendRaw class is a child class that extends the IRsendBase with a single function.  You just need to do the same thing to create a new class that implements the functions in a way that can read from PROGMEM.

This is the original:

class IRsendRaw: public virtual IRsendBase {
  public:
    void send(uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(buf[i]);
        }
        else {
          mark(buf[i]);
        }
      }
      space(0); // Just to be sure
    }
};

You just need to make your own one of those in your sketch, called something different, and which uses the progmem functions instead of accessing buf[i]:

class IRsendRawPGM: public virtual IRsendBase {
  public:
    void send(const uint16_t *buf, uint8_t len, uint8_t khz) {
      enableIROut(khz);
      for (uint8_t i = 0; i < len; i++) {
        if (i & 1) {
          space(pgm_read_word_near(buf + i));
        }
        else {
          mark(pgm_read_word_near(buf + i));
        }
      }
      space(0); // Just to be sure
    }
};

Now you can define your sender object as:

IRsendRawPGM mySender;

And send the data directly:

mySender.send(sources[0], RAW_DATA_LEN, 36);

(Note: this code is untested).


How does changing arduino power supply from USB to Adapter change the circuit?

I have run into problems like this before, often it can actually be that the voltage is not steady due to the LEDs sourcing current from it.

You may be able to solve the problem by adding a capacitor inline with the power input (from the +12v to GND). I would probably start with a value of around 10 μF and increase it if the interference continues.

Capacitive sensors and very sensitive to voltage fluctuations, you may even want to put a second capacitor across the VCC and Gnd of the sensor.


you replace Serial.write(rb); to Serial.write(pack[ndx]); and get?:

char rb = Serial.read();
pack[ndx] = rb;
ndx++;
Serial.write(pack[ndx]);

then you read an uninitialized array item on the next index


This

 int led = Serial.read();

is execute before setup() and loop(), just one time. All initializations outside any function are execute before the start of the program. You have not execute Serial.begin yet.

You probably want to read inside the loop ...

Edit:

Second problem: you are calling loop recursively

void loop()
{
    if(Serial.available()) {
        Serial.println(led);
        loop();

When a byte in available in the serial port, you will call loop. As you never read the serial port, Serial.available will still return > 0, and you will enter in a never ending recursion.


Rules of sequential file is : It's saved when its closed, which mean if the file not closed properly, anything written before will not saved, and you'll get blank file.

so, if you get a blank file while you are sure that the data is received, the only possibility is your program doesn't reach

myFile.close();

one of the possibility is the received data not fit into your memory, so the '\n' is undetected.


Having problems with HC-05 and three relays

I don't see a problem with the code indicated for bluetooth; if that code is indeed ok, then probably you should look for hardware issues;  first, look for low +5V when multiple relays are turned on.  (Attach a voltmeter or a scope to +5, see if it changes when a second relay comes on, etc.)  Second, look (with a storage scope) for glitches when the relays switch.  If you don't have a storage scope, try testing with a separate power supply for the relays.  (Tie the grounds of things together, but give the Arduino and the HC-05 +V that's isolated from relay +V.)

More seriously, your code is overweight.  For example, replace

   if (relay1estatus == 0){
    digitalWrite(relay1, HIGH);
    relay1estatus = 1;
   } else {
    digitalWrite(relay1, LOW);
    relay1estatus = 0;
   }

with

    relay1estatus = 1 - relay1estatus;
    digitalWrite(relay1, relay1estatus);


How do I know which is ground and power in Piezo?

On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o


Control two stepper motors simulatenously?

You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.

At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is identical and the motors are essentially attached mirrored on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)

digitalWrite(X1dir,HIGH);
digitalWrite(X2dir,LOW);

Or

digitalWrite(X1dir,LOW);
digitalWrite(X2dir,HIGH);

Then step it like

digitalWrite(X1step,HIGH);
digitalWrite(X2step,HIGH);

delayMicroseconds(2000);

digitalWrite(X1step,LOW);
digitalWrite(X2step,LOW);

delayMicroseconds(2000);
...


For this you need a acceleration/gyro sensor, like the MPU6050.

By tracking x/y/z movements, you can define what is forward/backards etc. Also you can track angles/tilts (in 3 directions).

See an example how to use it here: MPU-6050


Serial communication stops when I connect the tx cable

To have two serial ports on Arduino board like Uno use SoftwareSerial.h.

Example

#include <SoftwareSerial.h>

SoftwareSerial mySerial(2,3); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("Hello!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Now after opening Serial monitor you should see Hello! and then you can test SoftwareSerial.

DO NOT FORGET!!!

When you connect to pins 2,3 or etc, this is TTL voltage level. You can't connect direct to RS232.


Why is there a limitation in using Serial.println on ESP8266?

It's happening because you're not giving the ESP8266 a chance to do its housekeeping activities and the watchdog (which is enabled by default) is timing out - as evidenced by the very first line of your output:

  Soft WDT reset

You need to allow the MCU to do other things at the same time as you are printing to serial:

void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
        yield();
    }
}


driver is not showing up in Port assignments mac

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.


How do you remove dependencies from a library?

The Adafruit Neopixel library is licensed under GPL v3. You can fork a copy of this library into your own code and modify it to suit your own requirements, but if you distribute your code, your compiled project, or a product containing the library or any portion of it, you must ensure you follow the rules of the license by which the library is governed. Those terms of license may include release of the source code if you use any portion of the licensed library in a product. Opinions differ on the exact meaning of GPL v3 with libraries.

You should be able to copy the library into your own codebase and strip out the color-specific routines, put in your own application-specific data-setting routines, but use the same underlying protocol implementation.


Since PWM pins are digital outputs, the maximum output voltage is VCC.


RGB Led - mixing colors using analogWrite

Analog pins aren't PWM pins. Instead you have to use the pins marked with a ~

Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.


Read and write on the same node (central) using an RF24 network on Arduino

The library says you must include network.update() in loop() for the nodes to be in sync. Place that call at the top of loop() in both nodes.


Liquid Crystal LCD Display Prints f in all rows and columns

I don't know the source of the problem, but here are a few things that might help diagnose where the problem begins or what it is due to.

(a) To track execution progress, and detect which statement, if any, ruins LCD operation:  Create a routine to display current line number in code to LCD and Serial; make a macro ss to use for invoking that routine; invoke the macro before and after each line containing a tmrpcm action by calls like ss;.  See following example.

void shoLine(int line) {
  Serial.println(line);
  lcd.home ();     // Set cursor to 0,0
  lcd.print(line);
  lcd.print(' ');
  delay(200);  // /Delay long enough to see stuff appear
}
#define ss shoLine(__LINE__)

Note:  Move lcd.begin(16, 2); to be the first statement in setup() when using this method of debugging.

(b) If you find that the first few LCD calls are ok and then LCD output stops working, try turning off interrupts during LCD output.  That is, put a cli() or noInterrupts() call before an lcd.print(), and an sei() or interrupts() after it, and see if it then works.  If so, that might serve as a last-ditch workaround.  (I don't know whether LCD output routines use any interrupts; I doubt they do; but if they do, this method won't work.)

(c) If the LCD doesn't display correctly at all, even before the first tmrpcm action, it may be that the combination of tmrpcm with other code is using too much memory.  Carefully check the memory-usage reports when you compile your sketch.


Why do I get avrdude: stk500v2_ReceiveMessage(): timeout error when uploading to Arduino Mega?

The error message basically means that the programmer is unable to contact the boot-loader on the device. The code you're trying to upload has no bearing on the problem.

There could be one of the four possible reason behind it. They are:

Wrong Port Selected:

If TX/RX led is not blinking, then you may have selected wrong port. If one of both of them are blinking then, you aren't using the wrong port. It might be worth checking again though, sometimes USB COM devices install on strange port numbers.
Board is not in Bootloader Mode:

The Arduino Mega is not executing the bootloader for some reason. If the programmer is not resetting the micro before attempting to connect, this might be the reason. Try to reset the board (press and release the button) while the programmer is attempting to connect. Sometimes software that runs in a tight loop will prevent the bootloader from connecting.
Barring that, the fuses might have gotten messed up or the code erased. You would need to reflash the bootloader and proper fuses, again, see the appropriate info page for your device.
Arduino Mega 2560 only: ATmega8U/16U software

Might not be working and would need reprogramming. See the Programming section on the info page, you will need the firmware and Atmel-compatible DFU (device firmware update) software on your computer toreflash the target.
Hardware damage:

There could be hardware damage to the board, AVR(s), or FTDI chip. Time to buy another board.

You can check this answer.


How to use ROHM LB202VL display (on BP-006LH-GC board) with Arduino?

I have a similar display, and I found the wiring by inspection and trial and error:

The display consist of 8 pairs of digits (LB-202VL, common cathode).

If contact points are numbered from 1 to 24 from left to right then
the common cathodes for the digits D1-D16 and the segments D.P. and 'a' - 'g' are noted below.
If you i.e. connect 1 to GND and 7 to + then segment 'c' of the first digit will be on. You have to multiplex the digits in order to use it.

D1
D2
D3
D4
D.P.
D5
c
D6
e
D7
a
D8
g
D9
d
D10
f
D11
b
D12
D13
D14
D15
D16


Homebrew Arduino using ATMEGA328P, ISP or ICSP?

ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.


Arduino pro mini (clone) @1Mhz target does not answer

I am closing this thread.

The board is probably not destroyed, more likely are fused corrupted.
There are ways of reviving ATMega328 chip and program fuses back its called high voltage programming. You need to probably unsolder the chip or modify your board (post from tontrack).

Also if you are wondering what to do or not to your Arduino board here is quite interesting page (you wil find it in comment).

I did not found a way how it could have happen but it did.

Anyway Iam done with UsbAsp programmer and ordered AVR pocket programmer. Until it arrives I stop any more attempts.

Hope this helps somebody.


Writing Data through Pin at certain frequency

If I understand correctly, you want to output a synchronous serial bit
stream at 1 MHz. Something like this:

        ___     ___     ___
clk  __/   \___/   \___/   \___⋅⋅⋅
     ______ _______ _______ ___
dat  __D0__X___D1__X___D2__X___⋅⋅⋅

where the data bits come from the PC.

If you want this to be a continuous bit stream, it will not be easy to
generate on an Arduino Uno.

Receiving the data

Since the data comes from the PC, it comes presumably through the serial
link. You have to account for the fact that this link adds a start bit
and a stop bit to every byte. Thus, you have 10 bits on the wire
for every 8 bits of actual data. Since you have to sustain
1 Mb/s average of actual data, this means that you must configure
the serial port for at least 1.25 Mb/s. However, the only baud rate
higher that 1 Mb/s supported by the Arduino Uno is 2 Mb/s.

Does your PC support this baud rate? Is the communication reliable at
this speed?

If the speed is too high, I would suggest you try to have the PC send
the data as PCM at a lower speed, and have the Arduino handle the
PCM → PDM conversion.

Transmitting the data

This data format is very similar to an SPI transmission. Then, the SPI
hardware port seems like the easiest way to generate it. However, the
SPI transmitter on the Uno is not double-buffered. This means that you
have to wait for the current byte transmission to be finished before
providing the next byte to the SPI hardware. This in turn means that you
will inevitably have small delays between consecutive bytes, and one out
of every 8 clock cycles will be stretched beyond the expected
1 µs. If this unsteadiness is acceptable for your application, then
do use the SPI transmitter. If not, you will have to find another
solution.

The serial port on the Uno has a special mode of operation where it
behaves like a master SPI port. Unlike the actual SPI port, this port is
double-buffered, which makes it possible to send a continuous bit stream
with a steady clock. The problem is, you cannot use this mode for
transmission and at the same time use the serial port receiver in its
regular asynchronous mode. Thus you will not be able to receive the data
from the PC when using this mode. If you can manage to route the
PC → Arduino communication through SPI, this mode of operation
of the serial port may be a good choice.

If none of the options above works for you I suggest, as last resort, to
generate the bitstream entirely by software. The timings are tight, as
each level of the clock has to be held for only 8 CPU cycles. But
it is likely doable in hand-written assembly, provided that interrupts
are disabled. Here is roughly how I may try to do that:

    in output, _SFR_IO_ADDR(PORT_OUT)   ; save a copy of the port reg.

loop:
    lds data, _SFR_MEM_ADDR(UDR0)       ; load data from USART

    ; output bit 0
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 0                         ; save data[0]
    bld output, 0                       ; load it into output[0]
    ; no delay needed here
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6                             ; assumed to be a macro
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; output bit 1
    andi output, ~_BV(1)                ; clear clock bit
    bst data, 1                         ; save data[1]
    bld output, 0                       ; load it into output[0]
    delay 4
    out _SFR_IO_ADDR(PORT_OUT), output  ; output
    ori output, _BV(1)                  ; set the clock bit
    delay 6
    out _SFR_IO_ADDR(PORT_OUT), output  ; output

    ; etc...

    rjmp loop

The code above assumes the UART is synchronized with the output stream,
which will likely not be the case in reality. Your real application may
then be more complex, and you will have to make that extra complexity
fit within the delay slots above.

Note that if you handle the PCM → PDM conversion on the
Arduino the resulting code may end up being simpler, as you will be able
to read the UART at every loop iteration without worrying about
synchronization. I have written a program that does something very
similar a while ago, and I just pushed it to GitHub for you to take a
look: avr-dac: Turn an AVR into a 1-bit D/A converter. Note
that this program is meant to be usable on AVRs without a hardware UART.
It expects the PCM data to be fed in the fashion of a shift register.
Using the UART would make the program simpler.


Connect everyone to the MOSI / MISO / SCK and ground, then define every SDA all the way around. and set respectively high low depending on where you want to write.

How ever im not sure if you need to set high or low if you want to read. But since you got multiple you can play around with that your self. Feel free to add to this question with the result for future googlers.

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN           7          // Configurable, see typical pin layout above
#define RST_PIN2           8          // Configurable, see typical pin layout above
#define SS_PIN           9          // Configurable, see typical pin layout above
#define SS_PIN2          10          // Configurable, see typical pin layout above

....

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
MFRC522 mfrc522_2(SS_PIN2, RST_PIN2);   // Create MFRC522 instance.

....

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin();        // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  mfrc522_2.PCD_Init(); // Init MFRC522 card


A/C doesn't detect IR codes sent from Arduino

Hi i have done the same thing. I was using this to get the AC codes for the GREE AC. I find it with two weeks struggle and a forum called AnalysIR. If you find any issue in this code below or method let me know.

AC codes are usually long and those doesn't come right with the code which you used above so i am giving you the sample code to run in the Arduino sketch so that you can test.

   #define LEDPIN 13
  //you may increase this value on Arduinos with greater than 2k SRAM
  #define maxLen 800

       volatile  unsigned int irBuffer[maxLen];
       //stores timings - volatile because changed by ISR
       volatile unsigned int x = 0;
       //Pointer thru irBuffer - volatile because changed by ISR

     void setup() {
     Serial.begin(115200); //change BAUD rate as required
     attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);
    //set up ISR for receiving IR signal
     }

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

   Serial.println(F("Press the button on the remote now - once only"));
    delay(5000); // pause 5 secs
  if (x) { //if a signal is captured
digitalWrite(LEDPIN, HIGH);//visual indicator that signal received
Serial.println();
Serial.print(F("Raw: (")); //dump raw header format - for library
Serial.print((x - 1));
Serial.print(F(") "));
detachInterrupt(0);//stop interrupts & capture until finshed here

for (int i = 1; i < x; i++) { //now dump the times
  if (!(i & 0x1)) Serial.print(F("-"));
  Serial.print(irBuffer[i] - irBuffer[i - 1]);
  Serial.print(F(", "));
                     }

   x = 0;
   Serial.println();
   Serial.println();
   digitalWrite(LEDPIN, LOW);//end of visual indicator, for this time
   attachInterrupt(0, rxIR_Interrupt_Handler, CHANGE);//re-enable ISR for            receiving IR signal
        }

      }

  void rxIR_Interrupt_Handler() {
    if (x > maxLen) return; //ignore if irBuffer is already full
     irBuffer[x++] = micros(); //just continually record the time-stamp of signal transitions

    }

Once this is done you will get the right code to send it to the AC.

A little Tricky part

once you will receive the codes of raw values you will have to little modify it for example i got the raw values and i converted it into the array.

What i received for example
Raw (16): -27750, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628

To Convert the above raw values into array remove first value which is -27750 and put 3800 instead of that. Below is the array sample.**

unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
};

Now sending these values to the IR transmitter use this code below.

      #include<IRremote.h>
       IRsend irsend;
       int KHz = 38;                    // default frequency

      unsigned int data[] = {3800, 4464, 696, 1612, 692, 516, 688, 516, 688, 1620, 692, 512, 692, 1612, 696, 1612, 692, 512, 692, 516, 688, 1616, 696, 1612, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 512, 692, 512, 692, 512, 696, 1612, 692, 1612, 692, 516, 688, 516, 692, 516, 688, 516, 688, 516, 692, 1612, 692, 516, 688, 1620, 688, 516, 688, 520, 684, 1620, 660, 544, 664, 19960, 628, 1680, 628, 1676, 628, 580, 628, 1676, 628, 580, 624, 580, 628, 576, 628, 580, 628, 584, 620, 576, 628, 580, 628, 576, 628, 576, 628, 580, 624, 1680, 628, 580, 624, 580, 628, 580, 624, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 580, 628, 576, 628, 580, 624, 580, 628, 576, 628, 1680, 624, 580, 628, 1676, 628, 1680, 628,
        };

    void setup()
   {
     Serial.begin(9600);
     irsend.enableIROut(38);
   }

    void loop()
   {

    for (int i=0; i<1 ; i++){
    irsend.sendRaw(data, sizeof(data) / sizeof(int),38 );
    delay(40);
          }

 }


Use Arduino to transmit signal to a vibrating pager

To do SMS through a GSM shield like https://www.arduino.cc/en/Main/ArduinoGSMShield with a dataplan, and the device should be accessible anywhere you can get reception.  With a wifi shield like https://www.arduino.cc/en/Main/ArduinoWiFiShield101 you could make it work within your wifi network.

Sparkfun's sales guide at https://www.sparkfun.com/pages/wireless_guide indicates there are a few bluetooth modules that reach 100m, so if your range is less than 100m, bluetooth is a possibility.


Reading contents of ESP8266 Flash from inside sketch

I think you're reading of flash is slightly wrong

while ESP.flashRead takes a unit32_t pointer for output data, the read "count" argument is in bytes - looking at Updater.cpp code it does this

uint8_t buff[128];
for(int i = 0; i < binSize; i += sizeof(buff)) {
  ESP.flashRead(_startAddress + i, (uint32_t *)buff, sizeof(buff));
  .....
}

so, the the address and count are in bytes - given that SPI_FLASH_SEC_SIZE is 0x1000 or 4096, your code is doing the following

reading 4096 bytes into a 16384 buffer
writing 16384 bytes (so the last 12288 bytes are zero, or random, not sure)
adding 4096 to the address
subtracting 16384 from size
repeat until all read

So, the written size will be correct, but the data will be three quarters wrong :p

Therefore, your code should be

unsigned long addr = 0;
unsigned long rem = ESP.getSketchSize();
uint8_t *data = new uint8_t[SPI_FLASH_SEC_SIZE];
int sz = SPI_FLASH_SEC_SIZE;
File f = SPIFFS.open("/fw.bin", "w");

while (rem > 0) {
    ESP.flashRead(addr, (uint32_t *)data, SPI_FLASH_SEC_SIZE);
    if (rem < sz)
        sz = rem;
    f.write(data, sz);
    addr += SPI_FLASH_SEC_SIZE;
    rem -= sz;
    yield();
    Serial.println(rem);
}

f.flush();
f.close();


Check out this link. I guess it will work I had the same MAX30100 module what i did was removed those 4.7k resistors mounted through hole resistors on breadboard and pull-uped them using 5V and it was working fine for me


Weird stepper motor behaviour on RAMPS in arduino

The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.

Recalculate your steps/mm values and slow down the feed rate to get something reliable.

For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.

Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:

#define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


It seems it can't register on the network, GSM modems are power hungry, are you sure you're powering it up with the external power source (through Vin)? Pretty sure the Arduino isn't enough, but I could be wrong, that's a shield that has those issues in mind.

Also try to see the signal strength using AT+CSQ.


Cannot upload to Robotdyn Mega 2560 PRO MINI?

Try placing a 100nf capacitor on RST. That is usually required on an FTDI programmer.

See Edgar's post - https://arduino.stackexchange.com/users/47431/edgar


Pin 10 is the SS pin for SPI. Since you are using SPI for the SD card pin 10 must be an output (for SPI to operate in master mode). Ideally you will use that pin as the SS (or CS, whatever you want to call it) for the SD card.

You can't use it as the echo input of an ultrasound range finder and use SPI.


Help understanding how avrdude works with ArduinoISP and why its not working for me

The target board was not reset.

The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.

  Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

  What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

  Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc


Weird output from chained 74HC595 shift registers

You should change your capacitors.

You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:


Uno - measure the voltage, NOT connecting GND

If I understand the description correctly, neither side of the resistor is at ground potential.  There's a wide gamut of methods of dealing with this, for example using a differential ADC unit, or using an instrumentation amplifier ahead of a single-ended ADC.  But perhaps the simplest method is to use two ADC channels, one attached to each end of the resistor, with ADC ground connected to some common reference point.  Measure both voltages and take their difference .


I am getting blocks on my lcd screen 16*2

There are two possible problems, and you haven't stated which it is.

A single row of blocks (just the top row)

This is caused by either bad communication (wrong wiring) or incorrect code. Basically, the display isn't being initialized properly by your code for whatever reason.

Two rows of blocks (the entire display full of blocks)

The display is being initialized properly, so both your code and wiring are correct.  However, the contrast setting of the display is wrong. You need to check the wiring for your contrast potentiometer and adjust as necessary.


Can I measure multiple photoresistors from one pin?

If response time is critical (on the order of about a quarter of a second) consider using photo diodes instead of Cadmium sulfide cells.

Also, consider using an Arduino with more ADC ports.  The number of ADC ports is usually a constraint of the processor used.  Different Arduinos use different processors.  Some may have more ADC ports.

Finally, to utilize a single ADC port for multiple unknown resistances, consider using a resistor network where all the unknown resistances and a known pull down resistance are connected to the ADC port. Then, in turn, using as many Arduino digital pins as there are unknown resistance, apply a digital high to only 1 unknown resistance. Keeping the digital pins to all the other unknown resistance in a high impedance state. That is, change them from OUTPUT to INPUT digital ports. Then take an ADC sample. Apply this same procedure for all the other unknown resistances. Consider adding a delay after changing the state of the digital pins to allow for the ADC input to acclimate to the new voltage.

simulate this circuit – Schematic created using CircuitLab


Knowing if ESP32 wakes up itself or manually

I think you're getting confused between the ESP32 and the ESP8266. There is no need to connect GPIO16 to reset on the ESP32.
Instead the ESP32 has the "ULP" - Ultra Low-power Processor in it (essentially the RTC processor) which is what sends wakeup signals to the ESP32 cores. It is this which wakes the system up after an hour.
The ULP can also trigger a wakeup from other sources - most often used to wake up from an external signal, such as your button. But this only works if that signal is connected to one of the RTC input pins (GPIOs 34 to 39), or certain interrupt enabled pins (you can read more about what can wake the system up here).
Once a wakeup has happened you can then query the ULP to find out why it woke the ESP32 up using the esp_sleep_get_wakeup_cause() function.


I have multiple components that are lagging

As already stated in Look Alterno's comment and dannyf's answer, the
Arduinos are single-core, and they cannot perform several processes in
parallel. However, unless you have sub-millisecond timing requirements,
this should not be an issue. Your Arduino can just perform one task at a
time and, if it goes fast enough, it should meet your requirements.

So the good question to ask is: given the tasks you want it to
perform, can the Arduino do them while keeping the latency below some
threshold of your choosing? Latency is the time lag between the Arduino
receiving some stimulus (say, a change in light level) and it performing
the required action (e.g. moving a servo). For the kind of actuations
you mention in the question (servos, LEDs, buzzer), it makes little
sense to require sub-millisecond latency, and the Arduino (any Arduino)
should be able to meet your timing requirements hands down.

If your Arduino is really slow, this is generally because you have
something in your program that blocks the CPU for too long. It may be
some process that is very CPU-intensive, but this is unlikely because
you can do a significant amount of computation in one millisecond. More
likely, you are calling some blocking library function: a function
that blocks the CPU inside a do-nothing loop while it waits for some
external event to happen. You will have to go through your code and
hunt down any such blocking calls.

  I have multiple components such as LED's

LEDs are no issue. You can switch them on or off with a digital pin.
Once switched on, you don't need to do anything to keep them on. They
only consume a tiny bit of CPU time when you switch their state, but
none when you leave them in a fixed state.

If you want to dim an LED, then you will have to toggle it on and off
very fast. You can do this using analogWrite() on a PWM-capable pin.
Then, the toggling is done by a hardware timer, and it does not cost you
any CPU time. If you are short of PWM pins, you can also do the toggling
by software, but this will obviously cost you some CPU time.

  servos

Servos are typically driven using the Servo library. This uses a
combination of hardware (a timer for generating interrupts) and software
(an interrupt service routine that sends the control signals to the
servos). The CPU load should be small, unless you have a lot of servos.
Expect the interrupt to add some latency to the rest of your program.
Something like a few tens of microseconds or so (I haven't measured it).

Also, the servo library will use one of your timers, so you loose the
PWM feature on a couple of pins.

  photoresistor

You typically read a photoresistor with analogRead(). This
is a blocking function: it blocks the CPU while it waits for the ADC to
do its conversion. It will eat about 110 µs every time you call it,
so it is probably not such a big deal.

  buzzer

You switch a self-drive buzzer on and off just like an LED, with any
digital pin. If it's an external drive buzzer, you will have to
continuously toggle it. This is typically done with the tone()
function, which uses Timer 2 and costs you no CPU time.

  ultrasound

Ultrasound sonars are typically read using pulseIn(). This is a
blocking function, and often a very serious offender: it block the CPU
while waiting for the echo to come back. If the target is 16 cm
from the sonar, you will have to wait for about 1 ms, and
proportionately longer for a target further away. If the sonar cannot
see a target, pulseIn() will wait until it times out, and the default
timeout is a whopping full second!

If you are using pulseIn(), the first thing to do is to make sure you
provide an explicit timeout in the call. Make that timeout slightly
longer than the echo time for the longest distance you want to sense. If
that is still too long, you will have to look for a non-blocking
alternative to pulseIn(). You may find some on the Web.

  delay()

You did not mention delay() in you question. You are not using
delay(), right? If you are, then you only get what you are asking for.


You work with accelleration and absolute positions. Are you aware of that?
This Library is not made for running permanently in the same direction. It let you define a position where the movement should end, an acceleration or speed and the controller moves the motor to that position.
The run method must be called permanently, It triggers the steps. So, I put it directly into the loop() method.
The following prog should hopefully move the motor towards position 1000 if you press the 8-button, towards position -1000 if you press the 9-button and stops if both buttons are off. I have not the hardware available at the moment, you it's just blind programming. Use it as an idea.
#include <AccelStepper.h>
AccelStepper stepperX(1, 3, 2);

void setup()
{
  pinMode(8, INPUT)
  pinMode(9, INPUT);

  stepperX.setMaxSpeed(100.0);
  stepperX.setAcceleration(3.0);
}

int positivePosition = 1000;
int negativePosition = -1000;

void loop()
{
  if ( digitalRead(8) == HIGH )
  {
    stepperX.moveTo(positivePosition);
  }
  else if (digitalRead(9) == HIGH)
  {
    stepperX.moveTo(negativePosition);
  }
  else
  {
    stepperX.stop();
  }
  stepperX.run();
}


How to send two different sets of int numbers over serial?

I looked at your code, but the main problem seems to be that you have not defined the problem, and it is thus not possible to definitively answer.

The conventional solution to this would be to send 2 numbers with separator (usually space) followed by a newline. I know Arduino does not have an inbuilt function to do this, but you could write one. http://arduino.cc/en/Tutorial/SerialEvent shows one way this could be done.

Another approach is to send bytes (how long is each number? I would guess 16 bits) so you would send 4 bytes and on reception assemble them into 2 16 bit integers. Whether you need to ensure the data is synchronised depends on your problem. If you are sending continuous data this is essential, and you could use the kind of compelled sequence signalling you seem to be implying.

From the code it looks like you are sending from a Raspberry Pi. If I were doing this I would probably use I²C (at least over a short distance).


NodeMCU second HARDWARE serial TX as a debug port

ESP8266 Arduino core has Serial1 as write only hardware Serial on io 2 as TX. IO 2 is D4 on NodeMcu and Wemos D1 mini.

To use the USB chip of the NodeMcu/Wemos with Serial1 you could wire io 2 (D4) to TX. This would not disturb the flashing mode, because bootloader would still listen on standard Serial pins. I tested it.

And for RS485 adapter swap the Serial to io 13 (D7) as RX and io 15 (D8) as TX with the Serial.swap() command.


Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1?

One of the problems of the Uno is that the hardware SPI pins conflict with some of the PWM pins. If you want lots of motor control then you have it at the expense of no SPI. If you want SPI then you have it at the cost of reduced motor control.
The V1 shield uses a shift register for some of the motor signals, and that has to fit its signals in around the available PWM pins, so that as well has spilled over into the SPI pins (since you can't use SPI because of the PWM pins that really doesn't matter).
So no SPI means no nRF24L01.  Or does it?
You could (though I don't know of any libraries that handle this) use "bit-banged" software SPI on other pins (such as the analog pins) to communicate with the nRF24L01. Your mileage may vary with that, but it is technically possible - as long as you can find (or write) the right software support for it.
Would it be better to throw more hardware at it and have the wireless connection on a dedicated MCU? I would say, yes. Not only does it mean you can use existing libraries to communicate with the nRF24L01 without any worries of conflicting pins, but you get to compartmentalise your software into discrete units that don't interfere with each other. Parallel processing :)
How to communicate between the two? Well, you have I2C available on the analog pins A4/A5, which is well documented and plenty of examples. Or you could use serial, although the 328P's lack of serial ports means that you'd probably be working with SoftwareSerial which is ropy at best.  I'd pick I2C out of those two TBH.


Using millis() function to start at potentiometer reading

The statement TDCRLevel = analogRead(TDCRPot); will almost always set TDCRLevel to a non-zero value; hence the && TDCRLevel term of your last if statement almost always is satisfied.  The only time it won't be satisfied is when TDCRLevel is exactly zero.

When TDCRLevel >= 1000 is first satisfied, it's likely to be true for some while; during that time, each pass through loop() will toggle Bluestate and set previousMillisBlue = currentMillis.  This happens many times per millisecond while TDCRLevel has a high value.  Whether Bluestate is on or off when  TDCRLevel goes below 1000 is a fairly random outcome.

To handle the process properly, set up a state machine, using either one state-number variable or several variables to maintain state.  Change states when conditions tied to state, TDCRLevel, and time are met.

More simply, something like the following might work.

loop:
  if !P1 and L > Plim1:
    Set P1; record T1
  if P1 and T-T1 > Tlim and L > Plim2:
    Set P2
  if (P1 or P2) and L < Llim:
    Turn off pumps, clear P1 and P2

where P1, P2 represent pump states; T represents current time and T1 represents time that P1 most recently turned on; L = analogRead(TDCRPot); Plim1 and 2 are pot levels for pump turnons; Llim = low level for pump turnoffs; Tlim = desired time delay before pump 2 comes on.

Edit 1:  The above is pseudocode, rather than any simulacrum of valid C or C++.  As such, you may need to add sets of parentheses and brackets, substitute meaningful variable names, etc.

Note that the constants Plim1, Plim2, Tlim, Llim should be declared via either const int declarations, or via enum {} constructs (enum declares only integer constants), if they are integers rather than floats.  For example, do like either of

const int Plim1 = 1000; // level for pump1 turnon
const int Plim2 = 1000; // level for pump2 turnon
//etc

or

enum { Plim1=1000, Plim2=1000, Tlim=3000, Llim=100};

The phrase “Set P1; record T1” corresponds to code like

P1 = true;
digitalWrite(Pump1, HIGH);
T1 = millis();

in braces.  If you don't set P1 and record T1 as current time, the process won't work.  P1 and P2 represent state variables, not constants.

The phrase “if P1 and T-T1 > Tlim and L > Plim2: Set P2” corresponds to code like

if (P1 && (T - T1 > Tlim) && (L > Plim2)) {
  P2 = true;
  digitalWrite(Pump2, HIGH);
}

The phrase “if (P1 or P2) and L < Llim: Turn off pumps, clear P1 and P2” corresponds to code like

if((P1 || P2) && (L < Llim)) {
  P1 = P2 = false;
  digitalWrite(Pump1, LOW);
  digitalWrite(Pump2, LOW);
}


The LM339 is a comparator, not a motor driver. The L239D is a dual H-bridge motor driver.

They are completely different things. One is used for comparing two voltages (up to 4 times, it's a "quad"), the other is used for driving motors.

The LM339 can output an absolute maximum of 20mA. That's half what the Arduino itself can output on an IO pin!

You could use the LM339 as part of the control circuitry to control a H-bridge, but it cannot itself drive a motor in any way, shape, or form.


Not output on serial monitor, sending string on serial.print

There is a fundamental problem with your communication strategy, and that is you have nothing to tell the receiver "This is the end of a message".
You are sending a constant stream of
 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510 515; 510.....

and the receiver really doesn't know what to make of that.
This is because you are using the function .readString() at the receiver. This will blindly receive characters and store them in the target string up until the point those characters stop arriving. And that happens only after a break of at least 1 second in transmission. That never comes. So never ends. That is, until you reset the sender and it sees that break in transmission.
It's a very crude function and I'd never recommend anyone ever using it for anything.
Instead you need to break your transmission up into separate lines with .println() or appending \n to the string.  Then you can use .readStringUntil('\n') to get each line in turn and display it.
Also, on a side note, you really shouldn't be appending all your data to a string then sending the string, that's completely redundant. Just send each individual part of the data as separate prints. All you're achieving with all that String manipulation is to fragment your heap and cause your code to be unstable.


Help making LEDs blink like blinkers in a car

It looks like you need to do something like:

if ((buttonStateRight == HIGH) && (buttonStateLeft == HIGH)) {
    digitalWrite(ledPinRight, HIGH);
    digitalWrite(ledPinLeft, HIGH);
}
else if (buttonStateRight == HIGH) {
    digitalWrite(ledPinRight, HIGH);
}
else if (buttonStateLeft == HIGH) {
    digitalWrite(ledPinleft, HIGH);
}
//One delay for all
delay(500);
//Shut anything off that might be on after the delay
digitalWrite(ledPinRight, LOW);
digitalWrite(ledPinLeft, LOW);

Your code is really hard to read but it may mostly be because you need to insert four spaces at the beginning of each line of code to make it look right on this forum.


Getting 0 cm from ultrasonic sensor when nothing is in front

The documentation for the NewPing library states:

  Constructor

NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

  max_cm_distance is optional [default = 500cm].

Then:

  sonar.ping_cm(); - Send a ping, returns the distance in centimeters or
  0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.

Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.


How to use ESP8266 Pin D3 / GPIO 0 and D8 / GPIO 15 properly

A 74HC244 can be used to buffer up to 8 outputs and isolate them at will from the ESP8266. It can also be used for inputs as well if you connect gates the other way around. One additional IO line is required to control it.


Infrared distance sensor picks up distances that are not there

I see one problem with your code and how it relates to this device.

The output from the sensor is not the monotomic function you describe; not over its entire range.  Your conversion function describes only a section of the response.  The device is only intended to be used when an object is in range 10-80 cm.

You should check that the voltage at the analog input is valid before performing the math:

int v;

v = analogRead(sensorPin);
// sensor is valid in range 0.4 to 2.5 V
if((82 < v) && (v < 512)) {
  // voltage is in usable range, can convert
  distance = 12343.85 * pow(v,-1.15);
  if(distance < 50) {
    digitalWrite(ledPin, HIGH);
    delay(1000);
    digitalWrite(ledPin, LOW);
  }
}
else {
  // no valid reading - probably just skip and try again on next loop
}

With that the false triggers may be eliminated.


Do the I/O pins on Arduino read current or voltage?

They read voltage.  When you close the pushbutton switch the input should have a 0V or digital "0" on it.  When you open the pushbutton the resistor should pull the input to 5V or digital "1".
Yes, it is still connected to +5V via the resistor but the nearly 0 Ohm switch pulls the line all the way (or very close) to 0V.


I recently worked extensively on a Home Automation Project and here's what I would recommend based off of that:

Use Arduino for hardware interfacing.
Use Raspberry Pi for hosting your server.
Write your server using Node.js (or Python if you wish).
Use Express, Socket.io (or Python simple server). Google these.
Use Serial (USB) for communication between Arduino and Raspberry Pi
Use RF/BLE if you want to go wireless.
Use Redis or MySQL for database.
Use a graph JS API for charting.
To build an android app, send http requests (or a Socket.io link), for communication.

This is a simple to implement, but you'll need to put some time. Good luck.
All of the above steps are abstracted from each other. This means that if you want to incorporate additional features, you can change any stage without affecting the whole.


You're confusing the idea of using all the pins to that of plugging into all the pins.

Yes, your shield may well have all the pins on it which then fill all the available holes.  Only some of them will actually be connected to anything on the circuit board though.

The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.

You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.


LED staying on after first relay trigger

If using a solid state relay, consider such a device may rely on driving a load using AC rather than DC.  That is, the solid state relay my not turn off until a zero crossing occurs.  Solid state relays intended to switch DC driven loads are normally designed using MOSFET switches.  Solid state relays intended to switch AC driven loads are normally designed using SRC or TRIAC switches.  Read more about this here.


Most likely the motor you are trying to drive requires much higher current than what the UNO can provide through its digital outputs.

Check out this summary to find out detailed specs for the I/O ports.

What you could do is to draw power from the 5V line provided by the Arduino. If that can drive your motor, then use the line to power an output stage, driven by the digital I/O. See this example.
In general, the idea is that the digital I/O provides the control logic, while the output stage provides the power required by the specific load.

The typical loads that can be driven directly by GPIOs are low power LEDs.
Anything that involves moving parts is generally out of reach, power-wise.


Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code

Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).

They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.

If I'm allowed to give you a tip, you could eventually pick one of these here, they are pretty good in my opinion.

Of course there are a ton of others around, so you can just pick one which fit your needs.

On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).


How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?

To drive such high currents, you may have to cascade several transistors (you can also use a Darlington transistor). There are arrays of Darlingtons mounted in a chip (e.g. the ULN2803A has 8 darlington transistors, but is limited to 500mA).

You probably will have to deal with higher power transistors; as an example I have found STMicroelectronics TIP110 which can support switching a 2A current (4A peak), but it would probably need a heatsink to dissipate heat.

Note that I wonder if your steppers really need 2A current (are they that big?). For steppers, you can generally find IC that can drive them easily, e.g. the L293D but this one can drive "only" 600mA).

As a conclusion, I am afraid you will not find a "one size fits all" solution, as all your devices are different and should be driven by the appropriate circuit.

Edit:

Since oversizing is not an issue in your prototyping case, then you could go with a MOSFET instead of usual bipolar transistors. A MOSFET will be able to drive higher currents and voltages than standard transistors.

The downside is you can use it as a switch only (like e.g. a relay) and thus can't really drive the exact power for your devices. I guess that does not matter for a Stepper motor, or a Solenoid, but that may be important for driving lights for instance.

However, the good point is that you can still use PWM for that as the MOSFET switching speed is good enough for such purposes.

Regarding price, there are many diferent kinds of MOSFET out there, but I guess you can find one that fits yours needs (12V, 2A) for less than $1.

I advise you to take a look at this great article about this topic.


Will I be able send a HTTP request using the Arduino Yún?

Looking at your other two questions as well I see you have had limited success with a ESP8266.  I have never used a Yun, but I haven't seen much good stuff about them on here.  If you want a Linux based none real time system then you may as well get a PI.

Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link.  You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys.  The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package.  It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in.  If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.

Now I suspect you have an ESP-01 board and are wondering what the [heck] I am talking about, 10 pins.  The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1).  You might want to look at a Wemos D1 or a Node MCU.  Both are fully fledge dev boards, jus plug in the USB and away you go.

So to answer your question:

Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)


You are limited to what your microcontroller supports. You could use a 12MHz oscillator to clock your Arduino and set the SCK divider to fOSC/2 = 6MHz (even if it was possible, I wouldn't go higher. Having some margin just to be on the safe side is generally a good advice).
Drawback of this solution is that you lose CPU performance. Please consider also that just collecting ADC data is not enough. You also have to do something with it. Therefore the question should rather be:
"What minimum ADC acquisition rate do I need for my application?"


Why all blink tutorials use 330 ohm resistor

150 Ohms may be "enough", but it's often still far too bright, so many tutorials keep a lower limit of around 10mA to help the LED live longer without affecting the application.

You'll probably find that red LEDs are still visible at 1mA and a 330 Ohm resistor with a 5V supply will give about 8.5mA (assuming a 2.2V drop), which is plenty.

It's really a "lazy" choice that will work well in "most" situations.


How do I control the buttons on an Arduino LCD keypad shield?

I have found an easy way to do this, i found a tutorial on instructables that has explained in detail what to do, i then applied this to my LCD keypad shield rather than external buttons on a breadboard.

All you have to do to see what the results are for your particular buttons is to load the sketch below onto your board then open the serial mapper on the arduino ide, simply press the buttons and you should see the results.

 /*
  Debounce

  Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
  press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
  a minimum delay between toggles to debounce the circuit (i.e. to ignore
  noise).

  created 28 October 2009
  by Riaan Cornelius

  */

 // constants won't change. They're used here to
 // set pin numbers:
 const int buttonPin = 0;     // the number of the pushbutton pin
 const int ledPin =  53;      // the number of the LED pin for testing

 const int BUTTON1 = 1;
 const int BUTTON2 = 2;
 const int BUTTON3 = 3;
 const int BUTTON4 = 4;
 const int BUTTON5 = 5;

 const int BUTTON1LOW = 970;
 const int BUTTON1HIGH = 1024;
 const int BUTTON2LOW = 850;
 const int BUTTON2HIGH = 950;
 const int BUTTON3LOW = 700;
 const int BUTTON3HIGH = 800;
 const int BUTTON4LOW = 400;
 const int BUTTON4HIGH = 650;
 const int BUTTON5LOW = 250;
 const int BUTTON5HIGH = 350;

 // Variables will change:
 int ledState = HIGH;         // the current state of the output pin
 int buttonState;             // the current reading from the input pin
 int lastButtonState = LOW;   // the previous reading from the input pin

 // the following variables are long's because the time, measured in miliseconds,
 // will quickly become a bigger number than can be stored in an int.
 long lastDebounceTime = 0;  // the last time the output pin was toggled
 long debounceDelay = 50;    // the debounce time; increase if the output flickers

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

 void loop() {
   // read the state of the switch into a local variable:
   int reading = analogRead(buttonPin);
   Serial.println(reading);

   /*
   Not needed while getting the values.

   int tmpButtonState = LOW;             // the current reading from the input pin

   if(reading>BUTTON5LOW && reading<BUTTON5HIGH){
     //Read switch 5
     tmpButtonState = BUTTON5;
   }else if(reading>BUTTON4LOW && reading<BUTTON4HIGH){
     //Read switch 4
     tmpButtonState = BUTTON4;
   }else if(reading>BUTTON3LOW && reading<BUTTON3HIGH){
     //Read switch 3
     tmpButtonState = BUTTON3;
   }else if(reading>BUTTON2LOW && reading<BUTTON2HIGH){
     //Read switch 2
     tmpButtonState = BUTTON2;
   }else if(reading>BUTTON1LOW && reading<BUTTON1HIGH){
     //Read switch 1
     tmpButtonState = BUTTON1;
   }else{
     //No button is pressed;
     tmpButtonState = LOW;
   }

   // check to see if you just pressed the button
   // (i.e. the input went from LOW to a buttonState),  and you've waited
   // long enough since the last press to ignore any noise:

   // If the switch changed, due to noise or pressing:
   if (tmpButtonState != lastButtonState) {
     // reset the debouncing timer
     lastDebounceTime = millis();
   }

   if ((millis() - lastDebounceTime) > debounceDelay) {
     // whatever the reading is at, it's been there for longer
     // than the debounce delay, so take it as the actual current state:
     buttonState = tmpButtonState;
     Serial.println(buttonState);
   }

   // save the reading.  Next time through the loop,
   // it'll be the lastButtonState:
   lastButtonState = tmpButtonState;

   // set the LED using the state of the button for testing:
   switch(buttonState){
     case BUTTON1:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON2:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON3:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON4:
     digitalWrite(ledPin, buttonState>0);
     break;
     case BUTTON5:
     digitalWrite(ledPin, buttonState>0);
     break;
   }
   */
 }

Liam


They're for programming, as well as carrying the non-select signals for SPI. The right one is for programming the main MCU, the left for the USB communication MCU. You should almost never need to use them unless you need to write a bootloader to a new chip or change the fuse or lock settings on them.


SPI: problems communicating with sensor using Arduino

Change your chipSelectPin. Pin 10 is exclusively used by SPI library. See Arduino Uno description.

Similar issue has been discussed here.


Unable to connect Ethernet shield W5100 to localhost

After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.

Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.


The main problem seems to be, that you are not adhering to the MCP's communication protocol. You just try to directly and only send the pure analog measurement to it.

Look at this image from page 18 of the MCP4725's datasheet:

It describes the operation is Fast Mode, which seems to be the correct mode for this. (Similar descriptions for the other modes can be found below that image). The first byte is done by the SoftWire library, but the following is your responsibility. The
next 2 bytes consist (in this order) of 2 bit's setting the Fast Mode, 2 bit's for the devices power down select (both zero for normal DAC operation) and then the 12 bits of the actual voltage value for the DAC.

At this point I will show another problem with your code. You read an analog voltage with the Arduinos ADC, which is a 10 bit number (of type int) and use it in

Wire.write(aPin);

But the parameter for Wire.write() is defined as uint8_t (see line92 in SoftWire.h of the Softwire library), which means, that your int value get's casted and you loose all bits above 255 (the lower byte), because uint8_t just cannot store more.

What you have to do: You should put the I2C data bytes together in your code and then send them. This may look like this:

byte byte1 = (aPin & 0x0F00) >> 8;
byte byte2 = (aPin & 0xFF);

This code uses bitwise operators. The & will do an AND operation, the >> shifts the bits to the right by the amount after the operator. The 0x denotes a value in hex representation (binary representation would be 0b). So for the first byte we are doing an AND with the value 0x0F00, which will give us a value with only the first 4 bits of the second byte of aPin. Then we shift the result 8 bits to the right, so that the remaining data is nicely aligned to the right of your byte. We don't need to include the mode bits and power down select bits here, since they are zero anyway. If you want to set them non-zero you could bitwise OR them (of course with the correct shift, so that the bits have the correct position in the resulting byte):

byte mode_bits = 0b10;
byte power_down_bits = 0b11;
byte byte1 = (mode_bits << 6) | (power_down_bits << 4) | (aPin & 0x0F00) >> 8;

Then you can send these bytes out with I2C:

Wire.beginTransmission(I2C_7BITADDR);
Wire.write(byte1);
Wire.write(byte2);
Wire.endTransmission();

That should work, though note, that I have not tested this. I just read the datasheet, which is always a must read.

What happened with your original code: The datasheet states for the command "Write DAC Register" (which uses 4 bytes including the address byte) the following:

  The device ignores any partially received data  bytes  if  the  I2C
  communication with the Master ends before completing the 4th byte.

So it just drops any I2C messages, that are not complete. Though it is not stated clearly, we can be pretty sure, that the same happens also for the other operation modes. You were sending only 1 byte, so the MCP found the message incomplete and ignored it.

That said, there is a principle to work around the limit of only 2 devices on the same bus, which I also only learned recently about. You might not wanna go this way here, but it's a great idea and a valid solution to the problem with the limit.

Every MCP has 1 address pin A0, which set's 1 bit of the address, resulting in 2 possible addresses. On an I2C bus there must not be more than 1 device with the same address. But if that doubled address is never called, the bus doesn't have a problem.

You would connect the A0 pins of each MCP to one digital output pin of the Arduino each. By setting the state of these output pins you can change the address of the MCPs (requirement is, that the MCP actually checks the A0 pin during operation, but the datasheet seems to suggest this). Now you keep every A0 pin on one level, so that all MCPs have the same address. To communicate with one, you would change the state of it's A0 pin to change it's address. Now this MCP is the only MCP with this address (all other MCPs have the other address). You can now communicate with it. When you want to communicate with another MCP, you reset the first MCPs A0 pin and then change the next MCPs A0 pin.

That way you make sure, that on one of the two addresses, there will always be 1 MCP at maximum, while you never use the other address. You can use as many MCPs, as you have digital output pins to change their addresses.


Unable to upload sketch on Mac OSX El Capitan

Possibly the boot-loader baud rate in the IDE's boards.txt file is wrong. I have older (less than 6 years) '328p chips whose boot-loaders expect 57600 baud, but the boards.txt file in more recent Arduino IDE's try to talk to them at 115200 baud. I've had to duplicate the Arduino Uno entry in boards.txt and make one that specifies 57600 baud, to use these chips.


How do I write an Arduino program to an AVR chip without the Arduino bootloader?

Step 1: Get yourself a programmer.
This can be anything from a USBasp to an Arduino programmed for ISP all the way to an AVR ONE!. Some can be used from the IDE, and some cannot.
Step 2: Set up the chip as expected from the entry in boards.txt and from the datasheet.
Add a crystal, decoupling caps, whatever. Don't connect power yet.
Step 3: Connect the programmer.
If using ISP, connect the ISP pins. If using JTAG, connect the JTAG pins. If using something else, see the programmer and chip documentation for connection details. You may want to connect power at this point for the next step.
Step 4: Program fuses.
Program the oscillator, BOR, CKDIV8, EESAVE fuses as desired/required. Fuse calculator.
Step 5: Compile the program and write it to the chip.
If using the IDE, select the programmer in Tools | Programmer and then hold shift when clicking the Upload button (or press Ctrl-Shift-U). If your programmer is not supported by the IDE then compile the program (Sketch | Verify/Compile or Ctrl-R), locate the temporary directory it has been built in, and use avrdude or your JTAG program to upload it to the programmer.
Step 6: There is no step 6. You're done.
I just wanted to see if you would read this far.


How to add the previous value to current value from sensor

Btw, you can make the volatile variables global, by putting them above void Setup.
To put the total (new) value, use:
total += <sensorValue>;

where <sensorValue> is a call to get the sensorValue (or the value that has the sensor value stored in it), but I cannot see that in your sketch.
total += 0.3;

is the same as writing:
total = total + 0.3;

The value right of the '='sign is copied (assigned) to the left part of the '=' sign.


If the device turning the LEDs on / off runs on 3.3 Volts (has ground to 3.3 Volts outputs), then you might consider directly connecting the 3.3 Volt outputs to the GPIO pins of the ESP8266.  If the device turning the LEDs on / off runs on higher voltages consider either using the appropriate level shifter or the appropriate optical isolator:


Giving the impression of a dying device - making a vibrating motor slow down and stop

You can control the motor using PWM (Pulse Width Modulation) and make it run for full, then slowly decrease the speed till stop and after light up the led.
This tutorial from Adafruit could be a good start if you are not familiar with PWM and have also some good advices: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview

Please be really careful about the supply source. Motors can easy draw more current then the limited available from the pins of arduino. Maybe a H-bridge could be helpfull here.(take a look at this for example of h-bridge: https://learn.adafruit.com/adafruit-raspberry-pi-lesson-9-controlling-a-dc-motor/lm293d )


RH_RF24_MAX_MESSAGE_LEN is probably defined in the header file RH_RF24.h.

It doesn't matter what size it is, you should always use RH_RF24_MAX_MESSAGE_LEN rather than the number because the value might change in the library and this will break your code if you have used the number.

If you want to send a message that is larger than RH_RF24_MAX_MESSAGE_LEN then you will need to 'fragment' the message (unless the library supports that).
I would use the first byte of the message as the type of message and define one of those types as a multi part string.  Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.


Why so different not connected analog inputs?

Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...


3v3 ESP one way communication with 5 V Arduino?

Yes, it will work, but only just. It's borderline.
The ESP32 gives out at most 3.3V as a HIGH signal. The Arduino accepts "above 0.6Vcc" as a HIGH signal. That means that it needs to see a voltage that is at least 60% of the voltage on the Vcc pin (5V pin) of the Arduino.
If the Arduino has exactly 5V then 60% of that is 3V. Since 3.3V is higher than 3V it sees it has a HIGH.
However if the Arduino is being powered by a slightly higher voltage than 5V (some USB ports can give out 5.2V and it's still in spec) and if the ESP32 is being powered slightly below 3.3V, then that 0.3v margin of error gets narrower and narrower. Eventually it disappears and HIGH can no longer be detected.
For example if the Arduino has 5.2V and the ESP32 has 3.1V then the Arduino expects at least 3.12V and the ESP32 gives out no more than 3.1V.
So in  most circumstances it does work, but there are factors that can stop it from working. Those factors can be mitigated by using logic level translation.


Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the NRF24L01 library.

Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).


POV using ATmega328 powered with cr2032 cell

Not exactly an answer, but too big to place into the "comments" area.

Clock
For the 8MHz vs 16MHz, you should be able to run your project at 1MHz. Just use a bare AVR MCU with the Internal 8MHz oscillator divided by 8 - search for AVR Fuses. You can program it using an ISP (or and Arduino as ISP)

Battery
About the CR2032 or coin-cells in general are not designed to constantly supply current. You can use it for very low currents, up to 2-4mA or in pulses. Otherwise you damage the cell, reducing it's total usable capacity. Maybe have a look on sub AAA batteries instead of coin-cells.

Motor
For the motor, have a look on the micro coreless dc motors. They are really tiny and should offer an excellent efficiency. Motor example

Motor Driver
Not sure about the LM317. You don't want any kind of regulation as it would waste energy. To drive the motor a small Mosfet should do the trick. You can control the Mosfet using PWM, which will define the motor speed. Don't forget to implement some kind of rotary encoder to count the motor RPM so you can precise speed control - a tiny magnet and a hall-sensor should be enough.


Is there a way to define an alias for a hardware Serial


ESP8266 (D1 mini) fails to upload sketches

Thank you for your input. Especially the tip on connecting the battery while connected to usb [tttapa] I finally got it to work by changing the baud rate and messing around with the settings(i.e. board in IDE). I believe I got it to work with the "WeMos D1 R2 & Mini" board whereas I was using the generic esp8266 board.


If you want to take it to to the extreme, I always use an algorithm called Diamond Coordinates. It is described in this PDF.  It performs perfectly, and I keep a C# and Java implementation handy. I'll probably be doing a Python one soon :)


Problem with deploying matlab simulink mode to Arduino UNO

Right click on your MATLAB shortcut and click "run as administrator". See if helps. Then do all the necessary steps and see if it happens again.

Also test with x86 version. I have seen lots of these kinds of error with x64 version. Always had compiling related issues with MATLAB x64 and Simulink!


You need to turn your macro itself into a macro. Sounds odd, I know.  But take the following example:

#define foo bar, baz
#define foobar(X, Y, Z) something(X, Y, Z);
#define boofar(...) foobar(__VA_ARGS__)

boofar(foo, 4)

boofar is a macro that takes a variable argument list.  That expands out into a call for your actual macro call, expanding foo in the process.  Then your actual macro gets expanded out with the real arguments already in here. The point here is that foo is expanded before being passed to the macro that needs the multiple arguments that are inside foo.

So the expansion chain is actually:

boofar(foo, 4) ->
foobar(bar, baz, 4) ->
something(bar, baz, 4);

Running it through cpp and you get:

# 1 "t.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "t.c"

something(bar, baz, 4);


I would go with a Yun. Despite having a low end CPU, it runs at 400MHz and the disk space can be expanded using the uSD card (see this blog post).

If you don't plan to make CPU intensive tasks (such as real time video streaming and manipulation), the Yun is a nice tool. Otherwise, the Tre fits better (however, at the time of writing, it still has to be released).


'AttachPinChangeInterrupt' was not declared in this scope

You don't have the library installed. To install:

Go to https://github.com/GreyGnome/PinChangeInt
Click the green Clone or Download button
Select Download ZIP

The .ZIP file will download to your computer. Take note of the location.

Open up the Arduino IDE
Go to Sketch > Include Library > Add .ZIP library...
Browse to the download location
Select the PinChangeInt ZIP file

Its done! Compile your program and all should work!


Error opening serial port '/dev/cu.Bluetooth-Modem'. (Port busy)

You are not selecting the correct port to upload to - hence the strange message about the Bluetooth modem. Start by unplugging your Uno and running Arduino. Select Tools -> Port from the menu bar. You should see a list of options. Now plug in your Uno and do the same again. You should see an extra port listed now - this will be the Uno. Select it. You will need to check this every time you connect a board.

Also, before you click Upload, make sure you have Arduino Uno selected under Tools -> Board in the menu bar.


If you use default values in struct declaration, you have to define also constructors for setting specific elements:
struct Amiibo
{
  const char *aName{};
  const char *ID{};
  const char *AudioFileName{};
  bool alreadyPlayed{false};

  Amiibo() = default;  // default implementation for default constructor

  Amiibo(const char* name, const char* id, const char * audio)  // constructor with three c strings as parameters
  : aName{ name }
  , ID{ id }
  , AudioFileName{ audio }
  { ; }
};

Amiibo amii[] = {
      {"Mario","A5005B00","MARIO",false},                     //0
      {"Meta Knight","A5 00 02 00","MK"},                     //1
      {"Inkling", "A5 00 05 00","INK"},                       //2
      {"Donkey Kong","A5 00 01 00","DK"},                     //3
      {"Lucas","A5 00 0A 00","LUCAS"},                        //4
      {"Duck Hunt", "A5 00 08 00","DUCKH"},                   //5
      {"Ocarina of Time Link","A5 00 01 00","OOTL"},          //6
      {"Breath of The Wild Link","random","BOTWL"},           //7
      {"8-bit Link","random","8BITL"},                        //8
      {"Toon Link","random","TOONL"},                         //9
      {"Mr. Game and Watch","random","GANDW"},                //10
      {"Falco","random","FALCO"},                             //11
      {"King Dedede","random","DEDEDE"},                      //12
      {"Mewtwo","random","MEWTWO"},                           //13
      {"Captain Falcon","random","CAPF"},                     //14
      {"ROB","random","ROB"},                                 //15
      {"PAC-MAN","random","PACMAN"},                          //16
      {"Cloud","random","CLOUD"},                             //17
      {"Ness","random","NESS"},                               //18
      {"Ryu","random","RYU"}                                  //19
};

Btw on the older AVRs all those strings will resides also in memory


To generate a square wave, you only need to update the output at a rate of two points per cycle. (Technically, when the Arduino's PWM output is configured for 50% duty cycle, that's a square wave at some frequency.)

But to generate a clean sine wave (without a lot of distortion), you need to update a lot more frequenclly than two points per cycle. Personally I wouldn't want to go much below 20 points per cycle.

Imagine the sine wave is generated by a wheel that spins at some rate. Viewed from the edge, a point on the edge of the wheel traces out a sine wave. Viewed from the axle, you see the point going around in a circle.

Now instead of spinning the wheel continuously, suppose the wheel moves in steps of 30 degrees, 12 steps for a complete turn. Instead of a continuous sine wave, you get discrete steps of 0, 0.5, 0.866, 1, 0.866, 0.5, 0, -0.5, -0.866, -1, -0.866, -0.5, 0, 0.5, ...   Although this sequence approximates an ideal sine wave, it's pretty coarse because the steps are so large.

Now try 15 degrees per step (24 steps per cycle). Now you get 0, 0.259, 0.5, 0.707, 0.866, 0.965, 1, ... Much smoother, although the steps are still fairly noticeable.

So there will be less phase error, the more steps there are per cycle of the signal. That's not the only source of distortion however. There is also round-off error due to the limited resolution of the Digital-to-Analog Converter (DAC). For example, the value 0.866 I mentioned above should actually be an irrational value, half the square root of 3. Since it's an irrational number, there's no way for a real DAC to get this value exactly right. DAC output step values are ideally based on powers of two (1/2, 1/4, 3/4, 1/8, 3/8, 5/8, 7/8, etc.). And furthermore a real DAC can have offset error, gain error, non-linearity, as well as uncertainty about precisely when the new programmed value is reached.

There's also frequency error when the system's highest-frequency master clock is divided by an integer. If the Arduino UNO's master clock frequency is 16MHz, and the SPI setup function setClockDivider() is used to divide the master clock by 2, that's 8MHz. Divide by 3 and you get 5.333MHz. Divide by 4, that's 4MHz. Divide by 5, that's 3.2MHz. There's no way to get a clock frequency that's between these discrete steps. For small divisors, there's a big jump between steps. So if you needed to be able to smoothly adjust the frequency, you'd need a much higher master clock frequency. And, if you needed to configure the 16MHz Arduino UNO to an SPI clock frequency of exactly 5.7MHz, that's just not possible -- setClockDivider(2) is too fast, setClockDivider(3) is too slow, and setClockDivider(2.807017543859649) isn't supported by the hardware.

If your system could write to a DAC at an update rate of 12MHz, then 12 points per cycle gives a 1MHz output, and 24 points per cycle gives a 500kHz output. Or taking it the other way round, if you need to generate a 5.7MHz output waveform, then the DAC update rate needs to be somewhere around 100MHz to get a clean, low-distortion waveform. This is probably beyond the limit of what you can directly synthesize in software using something like an Arduino or a Raspberry Pi. A 16MHz Arduino UNO could maybe synthesize a few 100kHz using software synthesis, but at 1MHz there's going to be significant distortion.

Software-controlledDirect Digital Synthesis is very sensitive to timing, so the actual DAC update would need to be implemented in an interrupt service routine, run by a periodic timer. ( See https://electronics.stackexchange.com/questions/26363/how-do-i-create-a-timer-interrupt-with-arduino )  If you just used a while loop with a delay statement, then whenever the code needs to do something else, the waveform would just freeze up. This is more of a problem if the Arduino is trying to manage several other tasks at the same time as it is synthesizing the waveform.

Hardware Direct Digital Synthesis (DDS) is possible. Same principles. There needs to be a phase accumulator, which is just a counter that keeps track of the phase angle of the "wheel" that's generating the sine wave. (The phase accumulator needs to be modulus 360 degrees or 2 pi radians, but there's no requirement to count in 1 degree steps. Better to divide the circle into 2^N slices so that 360 degress maps to the natural counter overflow value.) And there also needs to be a lookup table with the sine value for each of those steps. This lookup table only needs to cover 90 degrees of the sinewave, because the waveform is symmetrical -- the other three quadrants can be found by 2's complementing the values and indexing from the other end of the table. Or, the sine can be approximated by a polynomial calculation. More steps x more DAC resolution requires a deeper, wider lookup table. There are integrated circuits available that perform the timing-critical actions, all the software needs to do is send some initial configuration to set it up. Changing the frequency only requires configuring a new frequency divisor value into the DDS chip, so the Arduino can manage other things without causing distortion.

If the original problem only needs one fixed frequency under 200MHz, and doesn't need any adjustment to that frequency, then the hardware gets a whole lot simpler. The crystal oscillator circuits that we use to generate the timing for digital circuits, are in fact analog to begin with. You can contact a crystal vendor and request a custom AT cut crystal; google custom quartz crystal frequency for quartz crystal vendors. Construction requires a careful printed circuit board layout; the white solderless breadboard commonly used in Arduino projects just doesn't work well above 10MHz. Granted, this fixed-frequency solution doesn't involve Arduino in any way, but if it solves the problem, that's what's important.


Can I connect an output pin to an input pin to measure it's voltage on a single board?

PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.

Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.

You could Google "Active low pass filter" for a lot of schematics and formula.

BUT

To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.

If your sample rate is close to Nyquist rates,  you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.

Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.


Reconnect to I2C with a different address (ATTiny85)

You only need to reinit the I2C slave.

The TinyWireS lib I found lets you just call TinyWireS.begin() with the new slave address. Though it doesn't have a way to stop the I2C connection. But the lib is hackable enough that with the ATTiny's specsheet you can add an end() to it.

However I believe that it may be better if the newly connected ATTiny acts as a master first and requests a free address from a known fixed slave acting as a dhcp server.


Problems with Windows 8.1 install of Arduino IDE

Getting started with a new toolchain can be quite a challenge…

I'm not a Windows guy, but it looks like there are drivers that need to  be installed to get things working with the Arduino. I'm guessing that what is going on here is that Windows is looking locally for drivers and not finding them (or any indication that drivers are needed). I think the button was grayed out because it couldn't help – not because help wasn't needed.

Here are a few sources that I found by searching on:

  arduino driver windows 8.1

[SOLVED] Arduino drivers for Windows 8.1 64bit
Windows 8.1 (64bit) USB-serial driver for Arduino?
Installing the Arduino IDE – Windows 8.1 & 10
Install Arduino Drivers on Windows 8

While we're at it, it is worth mentioning that "out of sync" error message from avrdude are very common. A bit of searching here will find you some good resources on solving them as well – deal with the drivers first, then see if errors persist.


How do you call a class method with named parameters?

C++ doesn't support named parameters, and I doubt it ever will.

It has strict calling conventions which mean you couldn't re-order the parameters at call-time without adding an unnecessary layer of data duplication/indirection (which would hurt performance). It would also need a significant change to compiler architecture, as variable/parameter names are usually stripped out long before the linker is invoked.

If you want to achieve a similar effect though, you could use comment blocks instead, e.g.:

Motors motors(/*p1*/ 123, /*p2*/ 456);


How To Get Data From Arduino Uno Onto My Laptop Through The USB

The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.

You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.

So:

Use Serial.print() etc to send data to the PC
Write your own PC software in your language of choice to process that data, or
Use some third party application to read and process the serial data


The main issue with your code is:

sizeof(s)

That doesn't return the string length - it returns the size of the char pointer - which is two bytes (on an 8-bit system, 4 on a 32-bit system).

Instead you need to use strlen(s) and add one to it for the NULL character at the end.

if(verbose){
  char buf[8 + strlen(s) + 1] = "[DEBUG] ";
  strcat(buf, s);
  Serial.println(buf);
}

However, what you are doing is pointless. Just print twice:

if(verbose){
  Serial.print(F("[DEBUG] "));
  Serial.println(s);
}

Note the use of the F() macro to ensure that [DEBUG] doesn't waste RAM.


Removing Element From Array While Keeping Order

You need to compact the vector: First search for the first non-zero element and then move all non-zero elements. It could look something like below:

void setup()
{
  Serial.begin(57600);
  while (!Serial);

  char vec[] = { 2, 5, 3, 0, 0, 1 };
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));

  vec[1] = 0;
  print(vec, sizeof(vec));

  compact(vec, sizeof(vec));
  print(vec, sizeof(vec));
}

void loop()
{
}

void compact(char* vec, size_t len)
{
  int i = 0;
  for (; i < len && vec[i] != 0; i++);
  if (i == len) return;
  int j = i;
  for (; i < len; i++) {
    char c = vec[i];
    if (c != 0) {
      vec[j++] = c;
      vec[i] = 0;
    }
  }
}

void print(char* vec, size_t len)
{
  for (int i = 0; i < len; i++) {
    unsigned c = vec[i];
    if (c < 16) Serial.print(0);
    Serial.print(c, HEX);
    if (i + 1 < len) Serial.print('-');
  }
  Serial.println();
}

This give the following output:

02-05-03-00-00-01
02-05-03-01-00-00
02-00-03-01-00-00
02-03-01-00-00-00

Cheers!


int A0, A1,A2,A3,A4;
delay(200);
A0= analogRead(A0);
A1= analogRead(A1);
A2= analogRead(A2);
A3= analogRead(A3);
A4= analogRead(A4);

Your local variables (A0 through A4) are shadowing the global variables for the pins (A0 through A4). Give your local variables different names.


the SD card is at /mnt/sd/ . you should consider reading the yun tutorials here before going further, the ability to send and receive data is at the heart of the yun design.


Is there a way to power off external devices during deep sleep

I made a temperature and humidity sensor which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.

The power-control part of the circuit is here:

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

The full schematic is:

I think I've changed the batteries once since making it in 2013.


Connecting breakout board to Arduino with UART

Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.

For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).

These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.

You could either:

Breakout the 3.3V signals onto connectors by modifying the SIM908
breakout board.
Build a level converter to take the 3.3V signals from
the DigiX to RS232 and then connect them as before.

You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.


Why do you need a second resistor when using a photoresistor/LDR?

The simple answer is that voltage is very easy for the Arduino to measure, while resistance is not, and most sensors such as Photoresistor (LDR), flex sensor, thermistors and more - are actually a variable resistors.

The main reason it's hard to measure resistance changes is that the Arduino (and most IC) contain a tiny system called Analog to Digital Converter (ADC). This system translates changes in analog voltage to a series of 1's and 0's that can be in turn converted to an Integer for example.

The ADC is designed to read voltage changes, and if we want to use the Arduino's analogRead (which utilizes the ADC) to get the Photoresistor readings for example, we will need a way to convert the changes in resistance to changes in voltage - and a voltage divider is the easiest way to do it.

It is true that the sensor is already a resistor, and as such it should change the voltage across it. But you would have trouble measuring the voltage changes, since there is no reference point except for Vcc (5V) and Ground:

In contrary, when using a voltage divider, you have a well defined reference point to measure the voltage changes:


How to connect a varying output voltage to the Arduino?

If “what I want is counting the pulses of my meter” means that you want to count the number of pulses the meter produces, you can use a circuit like the following to clip the voltage into the 0-to-5V range (as acceptable for inputs on Uno digital pins).

simulate this circuit – Schematic created using CircuitLab

Then, to count pulses, write a sketch that repeatedly reads the selected input pin.  Each time it changes from low to high, add one to your count of pulses.

If you don't have 5.1V zener diode like the 1N4733A, you could instead attach the anode of an ordinary diode to the junction of R1,R2 and its cathode (the cross-bar end) to 3.3V on the Uno.  This will clamp the voltage on the input pin to at most about 4V.  (Note, with such a diode clamp, there would be high-current problems if you subsequently changed the pin to a high output.  You could of course put a 100Ω resistor in series with the clamp diode if you are concerned about that.)


A little late but in case someone like me ran into this:

HC-05 seems to be the DIY choice. Can work in slave or master mode and works with Android but not iOS.

HC-06 is the same as HC-05 except that you can only use it in slave mode.

HM-10 seems to be the option for iOS users.


How to only detect the opening and closing of door sensor once

As often, the answer to this question is “Implement a ‘Finite State
Machine.’”. In this instance, you need at least three distinct
states:

ARMED: the buzzer is not active, but it is only a matter of time...
ON: bzzzz... bzzzz... bzzzz...
STOPPED: the user has stopped the alarm.

Each of your alarms should have a start time and a stop time (say, two
minutes after the start time). Then, the possible state transitions are:

ARMED → ON: when we hit the start time of an alarm
ON → STOPPED: when the user stops the alarm
ON → ARMED: when we hit the stop time of the alarm
STOPPED → ARMED: when we hit the stop time of the alarm

Notice that, once the user stops the alarm, the only way for the buzzer
to start buzzing again is by going through the transitions STOPPED →
ARMED → ON. The first transition happens at the alarm's stop time,
whereas the second one happens at the next alarm's start time.

You did use a kind of state variable in your code, but the problem is
you failed to realize that ARMED and STOPPED should be distinct
states. If you fuse these states together then, when the user stops
actively “stopping” the alarm, and if it's still start time, the
system transitions immediately back to the ON state.