Good books to learn more about microcontrollers / electrical engineering?

The newly updated 3rd Edition of "The Art of Electronics" by Horowitz and Hill is a great text/reference, worth every penny of its $80 price. It has a very practical approach and requires only high school math. I have been working with electronics for longer than I would care to admit and it teaches the subject the way I would like to have been taught.


Arduino ethernet shield not getting correct IP

The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay.  Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.

The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.

You can't use the old Ethernet library with the new Wiznet W5500 chip.  It doesn't work.

You have to use the "Ethernet 2" library as described here:

http://labs.arduino.org/Ethernet+2+Library

  Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above.  If you had read the product page you would already know this.


Play sound on top of background music using arduino uno tmrpcm library

Assuming you are using an Arduino Uno, You didn't say. As there are many Arduino platforms these days.
As the tmrpcm library is using the PWM  (Pulse Width Modulator) HW (Hard Ware) to recreate the sound waves from the WAV file on the SDCard, the PWM is not available for creating the sounds from your piano application (you didn't say what piano application you were using).  That said, it is not impossible to re-write both applications to SUM the two wave forms together mathematically before resampling the SUM and writing that sample value to the PWM HW to simulate the SUM of the two wave forms.  However, this is likely not trivial and it is also likely the Arduino Uno processor (an Atmel ATmega328P) will not be powerful enough (perform the math fast enough) to keep up with normal sound playback.
It would likely be much simpler to use 2 Arduino Uno boards and sum the sound from the sound file application and the piano application using analog techniques external from the Arduno Uno boards.


How to get keyboard input to arduino from the computer its plugged in to?

You can't. It's impossible.

Or not as you have requested it, anyway.

The Arduino can only talk over Serial, so you will have to have some software running on the PC that transfers data (however that data is generated) over serial to the Arduino to process.

The only other option will be to have one of the Arduino boards that is capable of acting as a USB Keyboard device, such as a Leonardo, plus either a PS/2 keyboard or a USB keyboard plus a USB Host shield. Your Arduino the receives the keystrokes from the keyboard, processes them, and sends the result on to the PC.


Uno's Mega's and so on have a separate MCU (u3) that contains the boot loader and is responsible for the USB connection and for driving the virtual serial port. Micros ( and also Leonardos and Esploras ) have built in USB support in the main MCU (u4). So if your program does something that breaks the USB part of the MCU the communication breaks also. This  happens for instance if you disable the interrupts.

The only thing you use in your program that might cause a problem is the Serial connection. The blink example has no serial output.

If you add a Serial.begin(115200) and a Serial.println("Hello") to the blink example, I guess the problem occurs also.

The IDE establishes the programming connection by connection to the selected com port at 1200 Baud. The boot loader recognizes that, performs an auto reset and opens a second (programming port) from then the IDE has access to this port and uses it to communicate with the boot loader. On a UNO this is handled by the separate MCU and on the Micro the main CPU is responsible for that.

Perhaps it helps if you add a time delay, before the Serial.begin(). Then you will have more time to start the programmer.

There is also a trick to enlarge the time you can start the programming after a reset to 8 seconds. https://forum.arduino.cc/index.php?topic=224416.msg1643210#msg1643210

And one additional hint:

Your code is unnecessarily complicated. If you want, you can try the program below. I think it does the same as yours. I have no compiler and no micro at the moment so it's complete untested.

You used a calibration variable. I guessed that it is for skip the first calibration values. If you need the values you can store them in a separate array.

My prog. has a lower memory footprint because I store the integer values from the analog input into an integer array. You used a double array.

You also did a lot of unnecessary computations after you read an analog value. This can slow down the readings. Perhaps therefore you missed some values you expected to see.

//amount of calibration values we will average
const int valueCount = 400;
const int calibCount =   0;

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

void loop()
{
  // the readings from the analog input
  int vals[ valueCount ];

  for (int idx = 0; idx < valueCount + calibCount; idx++)
  {
    int rawValue = analogRead( A0 );
    if ( idx >= calibCount )
    {
      vals[ idx - calibCount ] = rawValue;
    }
  }

  double total = (double) 0.0;

  for (int idx = 0; idx < valueCount; idx++)
  {
    total += (double) vals[ idx ];
  }

  Serial.println( total / valueCount );
}


Powering an Arduino Mega with external USB Power Bank?

I have a "USB power bank" with two USB ports, which I use to power some projects.

I have discovered that my bank (i.e. your mileage may vary!) shuts off unless my project draws at least 50mA. If your project does draw at least that at ALL times, you should just be able to plug a USB cable directly from the powerbank to the project.

For some other projects, I have bought a USB cable (USB A to USB A) which I cut in half, stripped the wires, then used a multimeter set to "Volts" to work out which wire was +5V and which was GND; I connect these straight to the 5V/GND on my project. To make sure at least 50mA was drawn at all times, I put a 100 Ohm resistor from +5V to GND (at LEAST 1/4 watt!!). This obviously wastes a lot of power (turning it into 1/4 watt of heat), but it keeps the power bank "awake". By using a USB A to USB A, I now have two cables.

My power bank also has a "torch" (led) integrated; if the torch is on, it also stays awake.


While you are doing a delay() you can't be doing anything else - that includes looking to see if the beam has been broken by the ball.

You must not use delay() in your sketch, instead use millis() as in the BlinkWithoutDelay example sketch in the IDE's File -> Examples menu.

Also how you are dealing with your IR system is incorrect.  You are first generating a brief square wave and then afterwards you are looking to see what was received.  Instead you need to be generating the square wave and at the same time see if that square wave is being received.  Normally that is achieved by using one of the PWM outputs of the Arduino set to the right frequency to generate a constant waveform which the receiver then senses all the time.


Unexpected behavior of sprintf with i32/u32

Ints and unsigned ints are 16 bits on AVR ATmegas.
So while the argument passed is a 32-bit value, sprintf() is expecting a 16 bit value.  The stack is packed with twice as much data as needed.

From the "2,0,4964" bit, it looks like it taking part of the previous/next parameter during processing, which makes me think this even more.

You need to use long types, e.g.: %ld or %li and %lu


As noted in Majenko's answer, the Arduino IDE doesn't provide a breakpoint  mechanism but Atmel Studio does support breakpoints.[*]

However, if you have a switch and an LED, you can track the progress of your program in a way that provides some of the benefits of breakpoints.  You would add a subroutine, say BPReport(), that via serial output or an LCD reports values of critical variables, then lights the LED and waits until the switch has been pressed and released, with debounce.  Call your BPReport() routine whereever you want an unconditional breakpoint.  For conditional breakpoints, you can have a routine BPReportIf(cond) which calls  BPReport() if cond is true.  If you don't want to output via serial, you might use several LEDs or an LCD, and you might use several switches if you want external break controls (for example, cond could be a test of one of the extra switches).

[*] Some hardware debuggers modify downloaded code each time breakpoints are added, changed, or removed.  That usage will wear out flash memory more rapidly than just occasionally downloading to it.  If a chip has been heavily used for such debugging, don't use that chip in a production system.


Is it possible to extend the reach of a PN532 NFC/RFID shield?

I suspect not. NFC is designed for short range for privacy reasons. Some RFID systems have longer ranges (a few meters). They work by using an electromagnet to create a switching magnetic field. The RFID/NFC chip takes power from the magnetic field and then modulates a signal onto it, which the sensor detects. In order for it to work the chip needs to be close enough to get as strong enough field to power itself, and to modulate that field.


I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.

If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.

Few ideas for voltage levels:

Voltage on "main" ATMega328 (You can check it through ISP header)
Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.

If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


Beginners code, loop doesn't detect unplugged pin

SInce I can coment I have to write this as answer.
there are two ways of understanding your question:
If you dont want it to ever blink again then simply remove
ledBlinked = false;
If you are trying to prevent the blinking until the button is depressed and pressed again then first think I see is the error in blinkLed function as
for (int i=0; i<=times; i++) would run times+one time. because it runs first with value of i being 0 (Eg times=4 would run for i equal 0,1,2,3,4 -> Five times ) So correction to for (int i=0; i<times; i++) would run correct number of times (Eg times=4 would run for i equal 0,1,2,3 -> four times )
Although as you are not checking status during the running of blinkLed function for the status of the button, if you release it while blink is running the script would not notice unless its still unpressed when script gets back to Loop.

Although since hardware operation take more work then logical operation I would recommend if...else statement rather then multiple hardware operations. Although they make code simpler to read
if(digitalRead(10) == LOW){
         if(ledBlinked != true)...
   } else { ...}


I have good news, and I have bad news.

The good news is that only two changes to the board are required to change it from a 5V board to a 3.3V (or any voltage within spec) board.

The bad news is that there's no way in hell you'll be able to do them.

So, we work around them and get the board up and running.

The first is obvious: a 3.3V board should be running off of 3.3V. Since we can't replace the SOT23-5 regulator on the board (the little 5-pin device towards the end) we need a voltage regulator to supply this, directly to the VCC pin. Find yourself a linear or switching regulator that provides this voltage.

The second is that the microcontroller, an Atmel ATmega168/P, is not specced to run at 16MHz when the supply voltage is only 3.3V; the maximum speed is 12MHz. Since we can't replace the crystal on the board (the little silver package next to the MCU itself) we need to perform some trickery to tell the MCU divide the frequency down to something way below safe, and then boost it up after. Use a programmer (see some of my other answers for more info about this) to set the CKDIV8 fuse and then use the routines in avr/power.h in your code to "reduce" the divisor to 2, bringing the clock speed back up to 8MHz. While you're at it, check the BOD fuses to make sure they're not set to something useless like 0b100.

As always, see the datasheet.


FreeRTOS : Create Tasks but don't start Scheduler

You need to vTaskSuspend the tasks immediately after creating them.

Then when you need a task to run you vTaskResume it.


How to increase the detection distance on Arduino KY-032 obstacle Avoidance sensor?

The wizecode page has some nice info. However the R5 pot (near the EN jumper) does not change the duty cycle but directly the current to the IR LED - still affects the brightness though. Too much current seems to trigger false positives - depends on your additional optical shielding. I put some black heat shrink tubing over the sensor - with a hole punched in for the sensor to see though.
Also the R6 pot does not really "fine tune" the frequency, more like "coarse tune" - even a small nudge can detune by a kHz, greatly reducing the sensitivity.
If you use the EN jumper, a suddenly appearing object gives a short pulse, but then the disturbance signal suppression kicks in turns sensitivity down and 'unsees' the object. Also slowly appearing objects are not recognized for that reason. Only very near objects (a few cm) give a strong enough signal to overcome that sensitivity attenuation.
What I found somewhat irritating: Setting EN to LOW lets the IR LED steady on instead of off, which I would have expected. That might irritate the sensor more than necessary. Also draws more power (maybe even a lot, depending on R5 current setting).
Funny enough, you can get a somewhat analog behaviour from this sensor if you measure how long it takes from activating the EN pin to the sensor output getting low. The nearer the object is, the faster it reacts. Near objects take ~190us, farther objects more than 400us. Not nearly a linear behaviour though. Also depends on distance, size, angle, IR reflectivity and IR LED power.
However it can detect a person in more than 1m distance.


Light up more than one LED connected to 74HC595 Shift Register

You don't mention if you are using and Arduino, but I will assume that is the case.

Using the shift register to light up LEDs is fairly straight forward.

You can use the ShiftOut() function to send out an 8bit binary value to the register. https://www.arduino.cc/en/Reference/ShiftOut

In summary however, if you want to light up the LEDs on the output pins 2 and 7 you would shift out b01000010 to the shift register. If you wanted pins 4, 5 and 7 to light up, you shift out b01011000. These assume the least significant bit is sent first.

Here's an example:

// set shift register output pins 2 and 7 to high
uint8_t data = 1<<2 | 1<<7; // use bit shifting

digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, data); // send the data
digitalWrite(latchPin, HIGH);


Why is my code only reading the change of the encoder's pin A?

You're confusing interrupt events and pin states here.

A pin can be either HIGH or LOW. Never anything else.

An interrupt can trigger on one of four events:

The pin transitions from HIGH to LOW (FALLING)
The pin transitions from LOW to HIGH (RISING)
The pin transitions from one state to another (CHANGE)
The pin remains low (LOW)

Your code should be (as you have done) attaching the interrupt to the pins using CHANGE so you can see any change in the state of the pins.

Your interrupt code should then examine the two pins to see their current state.

But there is one bit missing from your code, and that is what was the state before this interrupt triggered? - i.e., from what did the pins change from to get to this state?

The simplest way of coding this kind of thing is to think of each pin as a bit in a 2-bit binary number. Join the two pins together to form a number between 0 and 3:

uint8_t pinVal = (digitalRead(encBPin) << 1) | digitalRead(encAPin);

The truth table for that would be:

B | A | B<<1 | pinVal
0 | 0 |  00  |   00 (0)
0 | 1 |  00  |   01 (1)
1 | 0 |  10  |   10 (2)
1 | 1 |  10  |   11 (3)

There you have 4 states. And if you remember that state from one interrupt call to the next, you can compare the current value to the previous value. And that is where you get your 8 states from.  Encoders use Gray Code so the sequence of numbers you would get as you rotate the encoder would be:

0, 1, 3, 2, 0, 1, 3, 2 ...

Or the other way:

2, 3, 1, 0, 2, 3, 1, 0 ...

And it's the transition between those values that tells you what the encoder is doing:

0 <-> 1 <-> 3 <-> 2 <-> 0 ...

Each of those transitions can go two ways, and if you count the arrows (< and >) there are 8 of them there, which are the 8 states you were thinking of before.

So if the previous value is stored in oldVal from the last time the interrupt triggered, and the new value is in newVal, your 8 states are:

oldVal == 0 && newVal == 1
oldVal == 1 && newVal == 3
oldVal == 3 && newVal == 2
oldVal == 2 && newVal == 0
oldVal == 0 && newVal == 2
oldVal == 2 && newVal == 3
oldVal == 3 && newVal == 1
oldVal == 1 && newVal == 0

The first four are progressing in one direction, the last four in the other - one set is clockwise, one is anti-clockwise.

So you could have an (untested) interrupt handler that looks something like this:

void encUpdate() {
    static uint8_t oldVal = 0; // Static variable to remember the last state
    uint8_t newVal = (digitalRead(encBPin)) << 1 | digitalRead(encAPin);

    if (
        (oldVal == 0 && newVal == 1) ||
        (oldVal == 1 && newVal == 3) ||
        (oldVal == 3 && newVal == 2) ||
        (oldVal == 2 && newVal == 0)) {
            encCount++;
    } else {
        encCount--;
    }
    oldVal = newVal;
}

You notice I've only implemented the comparison for the first four states and not the last four. Since there are only 8 states, and those states cause one of only two things to happen, if it's not one of the first four states, which would increase your count, it must then be one of the last four states which decrease your count. No point in checking for them since it can't be anything else.  If you turned it clockwise then increase the value. Otherwise you must have turned it anti-clockwise since there is no other direction you can possibly turn it in, so decrease the count.

This is precisely why Gray Code is used - only one pin ever changes at a time, so there is no ambiguity in what has happened - either you turned it one code-point in one direction or you turned it one code-point in the other. Even if there is lots of bounce it will just bounce between two neighbouring code-points and settle on the final new code point (as long as the interrupt can react fast enough to catch all the bounces).


MPU6050: Setting Gyro Output Range Throws of Positional Reading

Had the same problem, it appears that MPU6050 DMP code works like that once you change accelerometer and gyro scales.

Works better once you use +-2000 deg/sec and +-2g scaling settings.

    mpu.setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
    mpu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

The issue lies in the way "DMP" inner logic fuses data, i suppose it has "constants" that are tuned for these settings only.

In case you need both "changed settings" and "yaw\pitch\roll" data, you might want to implement sensor data fusion by yourself or use existing libs.

The easiest i may suggest would be implementing Complementary Filter.
More complex, yet accurate would be using Kalman Filter, all depends on time and patience you have to research those topics :)


How do you connect parts once all GPIO ports are used?

Yes, it is one possible way, another are using some kind of multiplexing as input shift registers, Charlieplexing http://www.instructables.com/id/Charlieplexing-7-segment-displays/?ALLSTEPS, button matrix http://pcbheaven.com/wikipages/How_Key_Matrices_Works/ or i2C bus, which can connects up to 127 different i2c devices


... and works fine with the other shields of the same model from the same batch.

So had you considered that the shield might be faulty? Have you contacted the manufacturer or vendor for support?


If your chosen power supply is of a good quality and provides proper ground isolation then it shouldn't be a problem to connect the grounds of the two systems together.

However, since there are so many bad power supplies available on the internet (and even some "good" power supplies are somewhat iffy when it comes to grounding) it is safest to hedge your bets and add your own galvanic isolation.

The simplest method is to use an opto-isolator.  Use the +5V and GND from your computer's USB port (assuming it's not an always-on charging port - look for a lightning bolt symbol) along with a resistor (470Ω - 1kΩ is good) to drive the LED side of the opto-isolator. The other side then acts as a button to the Arduino:

simulate this circuit – Schematic created using CircuitLab

In this arrangement your input will be LOW when the PC is on. Also R2 could be replaced by the internal pullup of the GPIO pin (pinMode(PIN, INPUT_PULLUP);)

As I say, this most likely won't be strictly necessary, but for the minimal cost of an opto-isolator it's silly not to add that extra layer of protection. After all, an opto-isolator is cheaper than a new Arduino or (heaven forbid) a new laptop.


If you're just outputting to serial you don't need to concatenate - just print each bit separately, such as:

Serial.print(out1);
Serial.print(",");
Serial.print(out2);
Serial.print(",");
Serial.println(out3);

You should avoid using String as it's not good on devices with small amounts of memory like Arduinos. Instead if you really need to concatenate numbers you should use a C string and maybe snprintf to format the numbers into it:

char out[30];
snprintf(out, 30, "%d,%d,%d", out1, out2, out3);


It's not the compiler, it's the libpng package (and other libraries too).  It only contains the runtime shared library (.so) files.  You can't use it for development.

I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.


Read RFID Card Number in Processing over Serial

input has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before Serial.print(input), you write input[12] = 0. Also the argument to string.equals() should be a String as well; you must write the statement like this: input.equals(String("11006F26DC84"));


What happens when code is uploaded using the bootloader?

When you reset a Uno running the Optiboot loader, the bootloader first flashes pin 13 three times.

Top line (gray) is sent to the Arduino, middle line (orange) is sent from the Arduino.

While that is happening, the program avrdude running on your computer is sending a query to the device:

STK_GET_SYNC / CRC_EOP  (0x30/0x20)

The Arduino doesn't notice the first "get sync" because it is busy flashing pin 13. Once it is done it notices the "get sync" (it would be buffered by the serial hardware) and replies:

STK_INSYNC / STK_OK (0x14/0x10)

It looks like avrdude got a bit impatient, and timed out, because it tries again with the "get sync" query. This time Optiboot responds immediately.

The rest of the uploading is described in the next image. Example produced uploading the stock "Blink" program.

(Click on the image above for a larger version)

The steps are:

Query: Get Sync? Reply: In Sync.
Query: Get parameter? (major version) Reply: version 4.
Query: Get parameter? (minor version) Reply: version 4.
Set device parameters. The following device parameters are sent to the chip:

0x42  // STK_SET_DEVICE
0x86  // device code
0x00  // revision
0x00  // progtype: “0” – Both Parallel/High-voltage and Serial mode
0x01  // parmode: “1” – Full parallel interface
0x01  // polling: “1” – Polling may be used
0x01  // selftimed: “1” – Self timed
0x01  // lockbytes: Number of Lock bytes.
0x03  // fusebytes: Number of Fuse bytes
0xFF  // flashpollval1
0xFF  // flashpollval2
0xFF  // eeprompollval1
0xFF  // eeprompollval2
0x00  // pagesizehigh
0x80  // pagesizelow
0x04  // eepromsizehigh
0x00  // eepromsizelow
0x00  // flashsize4
0x00  // flashsize3
0x80  // flashsize2
0x00  // flashsize1
0x20  // Sync_CRC_EOP

Optiboot ignores all those and replies with In Sync/OK. :)
Set extended device parameters:

0x45  // STK_SET_DEVICE_EXT
0x05  // commandsize: how many bytes follow
0x04  // eeprompagesize: EEPROM page size in bytes.
0xD7  // signalpagel:
0xC2  // signalbs2:
0x00  // ResetDisable: Defines whether a part has RSTDSBL Fuse
0x20  // Sync_CRC_EOP

Optiboot ignores all those as well and replies with In Sync/OK.
Enter program mode. Reply: In Sync/OK.
Read signature. Optiboot replies with 0x1E 0x95 0x0F without actually reading the signature.
Write fuses (four times). Optiboot does not write the fuse but just replies In Sync/OK.
Load address (initially 0x0000). The address is in words (ie. a word is two bytes). This sets the address for where the next page of data will be written.
Program page (up to 128 bytes are sent). Optiboot replies "In Sync" immediately. Then there is a pause of about 4 ms while it actually programs the page. Then it replies "OK".
Load address (now 0x0040). This is address 64 in decimal, ie. 128 bytes from the start of program memory.
Another page is written. This sequence continues until all the pages are written.
Load address (back to 0x0000). This is for verifying the write.
Read page (up to 128 bytes are read). This is for verifying. Note that even if the verify fails, the bad data has already been written to the chip.
Leave programming mode.

What does "not in sync" mean?

As you can see from the above, every step through the programming sequence the Arduino is expected to reply with "In Sync" (0x14), possibly followed by some data, followed by "OK" (0x10).

If it is "not in sync" that means that avrdude did not get the "in sync" response. Possible reasons could be:

Wrong baud rate used
Wrong serial port selected in IDE
Wrong board type selected in IDE
No bootloader installed
Wrong bootloader installed
Board not configured to use the bootloader (in the fuses)
Some device plugged into pins D0 and D1 on the Arduino, interfering with serial commications
The USB interface chip (ATmega16U2) not working properly
Wrong clock for the board
Wrong fuse settings on the Atmega328P (eg. "divide clock by 8")
Board/chip damaged
Faulty USB cable (some USB cables provide power only, and are not for data, eg. cheap cables for USB fans)

What is "in sync"?

As mentioned above, the response "In sync" means that the Arduino (bootloader) is synchronised with the uploading program.

What protocol is being used?

The protocol is the STK500 protocol as documented by Atmel. See the references below.

References

Optiboot source code - GitHub
AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2
Have I bricked my Arduino Uno? Problems with uploading to board
AVR Downloader/UploaDEr - avrdude

Note: STK500 Version 2 is not used in Optiboot, but it is included for information in case you are using boards like the Mega2560.

STK500 constants

/* STK500 constants list, from AVRDUDE */
#define STK_OK              0x10
#define STK_FAILED          0x11  // Not used
#define STK_UNKNOWN         0x12  // Not used
#define STK_NODEVICE        0x13  // Not used
#define STK_INSYNC          0x14  // ' '
#define STK_NOSYNC          0x15  // Not used
#define ADC_CHANNEL_ERROR   0x16  // Not used
#define ADC_MEASURE_OK      0x17  // Not used
#define PWM_CHANNEL_ERROR   0x18  // Not used
#define PWM_ADJUST_OK       0x19  // Not used
#define CRC_EOP             0x20  // 'SPACE'
#define STK_GET_SYNC        0x30  // '0'
#define STK_GET_SIGN_ON     0x31  // '1'
#define STK_SET_PARAMETER   0x40  // '@'
#define STK_GET_PARAMETER   0x41  // 'A'
#define STK_SET_DEVICE      0x42  // 'B'
#define STK_SET_DEVICE_EXT  0x45  // 'E'
#define STK_ENTER_PROGMODE  0x50  // 'P'
#define STK_LEAVE_PROGMODE  0x51  // 'Q'
#define STK_CHIP_ERASE      0x52  // 'R'
#define STK_CHECK_AUTOINC   0x53  // 'S'
#define STK_LOAD_ADDRESS    0x55  // 'U'
#define STK_UNIVERSAL       0x56  // 'V'
#define STK_PROG_FLASH      0x60  // '`'
#define STK_PROG_DATA       0x61  // 'a'
#define STK_PROG_FUSE       0x62  // 'b'
#define STK_PROG_LOCK       0x63  // 'c'
#define STK_PROG_PAGE       0x64  // 'd'
#define STK_PROG_FUSE_EXT   0x65  // 'e'
#define STK_READ_FLASH      0x70  // 'p'
#define STK_READ_DATA       0x71  // 'q'
#define STK_READ_FUSE       0x72  // 'r'
#define STK_READ_LOCK       0x73  // 's'
#define STK_READ_PAGE       0x74  // 't'
#define STK_READ_SIGN       0x75  // 'u'
#define STK_READ_OSCCAL     0x76  // 'v'
#define STK_READ_FUSE_EXT   0x77  // 'w'
#define STK_READ_OSCCAL_EXT 0x78  // 'x'


Your IR receiver is decoding the high frequency pulsed On-Off-Keying waveform for you. The Arduino doesn't do that.

An IR signal consists of high frequency (say 36KHz) on-off light pulsed at a lower (data) frequency (different combinations to make 1 and 0)

The receiver you have takes that high frequency signal, amplifies it, filters it, and gives you just the resulting 1 and 0 signals. From that the Arduino can use simple time measurements to work out the code.

Without the filtering that the receiver provides the Arduino will have to do all that work by itself - and while that may be technically possible, it's seldom done. You may be able to find a library that can do it, but it's unlikely.


All of the sudden the Nano will not accept programming

This problem occurs quite often with all the boards. Here is how to troubleshoot it.

1 - Unplug the Arduino.

2 - Upload the program WITHOUT any boards connected to your computer.

3 - Replug your Arduino.

4 - Upload the program WITH your Arduino connected to your PC.

If this doesn't work, read this post by Nick Gammon.


You want to use snprintf for this:

char timeString[9];

snprintf(timeString, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
Serial.println(timeString);

By using a format string like this you are taking into account time portions < 10 (like 7 minutes and 23 seconds past 3 am, which would otherwise be 3:7:23) by padding the time with leading zeroes where needed.


It is possible to use a OTG Y cable just plug it into your phone, power cable into the power source and use the third connector to connect  to your PC. (Assuming the PC only gets GND, D+ and D- and battery bank GND, 5V)

It is also possible to reprogram an Arduino with an Android device that has OTG support.
Would save you a bit of hassle.

My Android phone (LG D605) with ArduinoDroid can easily upload code to my Nano and Uno.


Can I control Arduino functions via PWM?

A filter and ADC should solve communication problem. However, UART would be much better.


Generic solution:

void loop() {
    static bool yes_we_did_the_one_time_job = false;
    if (yes_we_did_the_one_time_job) {
        do_the_other_jobs();
    } else {
        do_the_one_time_job();
        yes_we_did_the_one_time_job = true;
    }
}


what is good practice around initializing variables

Initializing a global is appropriate if you know in advance that it should always have a given value at startup. The compiler will generate a globals image in ROM that will be copied into RAM before any of your code is executed.

Safe to assume compiler will initialze?

The compiler will initialize to 0, a global not specifically initialized by you. Let's take the case of your Boolean. '0' means 'false', right? So 'x' is pre-initialized to 'false'. But I, as the reader (or yourself, six months later) may not know whether you intended this to be initialized to 'false' (the default value) or forgot to initialize it. Specifying it to be 'false' may not have any different effect on the code, but it does inform me or your future self, that you meant it to be set 'false' at startup. Remember that your code communicates to people as well as to the compiler. Write it so you or I will not only be able to understand it, but won't be able to misunderstand it.
If you initialize it in setup(), the compiler generates code in setup() specifically to do that. If the setup() function needs to decide during startup, what the initial value of that variable should be, then this is the place to do it. Otherwise, the extra code just takes up space in Flash. It's not any more harmful than wasting those few extra bytes of code-space, but it doesn't accomplish anything more than letting the globals image do it.
Whatever you did or didn't do with 'x' at load time or in 'setup()', it will persist into 'loop()', so 'x's state isn't unknown when you get there. (If I misunderstood that part of your question, please edit it in your question.)


How can I add phonebook entry to sim card using Arduino GSM shield?


Im trying to get a 3 button password sequence working

Without programming everything out, use something like this:

Initialization:

Create a (global) variable of string ("12331") which is the code
Create a (global) variable of int that shows the number of correct numbers so far (initially 0)

In the while loop:

Check which button is pressed
If it is the correct button
increase the int variable
If that variable is 5 (meaning all numbers ok), light up the LED
Delay
Make the variable 0 again
Clear the LED
If the wrong button is pressed
If it is equal to the first value ('1')

Set the variable to 1 (since the wrong number is the first correct number)

Else

Set the variable to 0


how does a bluetooth on android works and what are the best alternative in saving data receive from bluetooth?

Serial communications only consist of one character. That is what serial is - the sending of one character at a time.

How you then deal with those characters, combining them into strings, interpreting them as numbers, whatever, is completely up to you to program.

There is no such thing as a string in serial communications. There is only the character.

The Arduino API has a few (badly implemented IMHO) helper functions that can get a whole string (kinda), but it is much better (both from a learning perspective and an implementation perspective) to do it yourself.

I have a little tutorial here that may help you get to grips with it.


Scenario 1 fails because yellow and green LEDs have forward voltages of about 2V each, so when putting 3 in series, you need a forward voltage to light them that exceeds the 5V available.

Scenario 2 fails because the wire you have in parallel with the LED provides a path with a very low voltage drop (close to 0V), so the path through the LED with a ~2V voltage drop is not taken (and if you remove the wire, the same reasoning as in scenario 1 applies, so nothing would work).

BTW, you should never run LEDs without a series resistor, as your experiments will surely demonstrate to you soon ;-)


glediator + PL9823 (WS2812B) + teensy = fail?

G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with FastLED.h but is the serialReadBlocking how it deals with the input data? Not that it's wrong, just not what I was expecting.

Two things to look at:

Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.
I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td_uart.html


Change int switcher = LOW/HIGH to just switcher = LOW/HIGH.

Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).


The tutorial sample source code has the line:

Serial.print(bmp.readAltitude(1013.25)); // this should be adjusted to your local forcase

That 1013.25 value should be the local pressure at sea level in hundreds of Pa. If want to show altitude above ground level, you will need to know that for your location and write your code to calculate the altitude offset.

The sensor can't know location -- it only measures pressure. The AdaFruit library provides the altitude conversion, but being generic, it relies on several assumptions.


Arduino Mega, PWM analogWite doesn't work with Timer interrupt

When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the Timer1.initialize(100000); function call).

So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).


How to use get_properties to get RSSI in RF24?

By using the RH_RF24 rf24;(Singleton instance of the radio driver), read a series of properties is really simple.

The properties shall be in the same GROUP,
Up to 16 properties could be read in the same request,

  Hereafter is a example to read from SYNC_CONFIG to SYNC_BITS_7_0 (5
  properties).

Step 1 - Declare your own uint8_t sync_stat[5]; or use the still declared uint8_t status[8];.

 uint8_t sync_stat[5];

Step 2 - The firstProperty is in fact the first property to be read and count is the number successive properties to be read (from SYNC_CONFIG = 0x1100 to SYNC_BITS_7_0 = 0x1104.

// And check the returned code
if (rf24.get_properties(SYNC_CONFIG,sync_stat,5)) {
    // sync_stat[0]= SYNC_CONFIG
    // ...
    // sync_stat[4]= SYNC_BITS_7_0
}

  Then, the equivalent command() is:

uint8_t buf[3];
buf[0] = SYNC_CONFIG >> 8;
buf[1] = 5;
buf[2] = SYNC_CONFIG & 0xff;
if (rf24.command(RH_RF24_CMD_GET_PROPERTY, buf, sizeof(buf),sync_stat,5)) {
    // Same array
}


Powering ESP8266 from Leonardo's 3.3v pin

The Leonardo is specified to provide only 50mA on the 3V3 pin. A ESP8266 can use up to almost 300mA when transmitting. Consider using a LDO regulator connected to the 5V pin instead.


Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino

I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers

I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.

However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).

So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.


Adding comments to your code would help us understand your intentions.

It is assumed you are sending the ASCII values for 'a', 'b', 'c', ... for different buttons and their actions.  And that you want to receive these on an Arduino over the USB using the USB serial port protocol. It is also assumed that your Python script works and the Linux OS is creating a /dev/ttyACM0 or some such serial device when you plug in your Arduino.

Looking at your Arduino code we see you are only checking for the number of bytes in the Arduino's serial port receive buffer by using the Serial.available() method call.  If your intentions were to read a byte of data you would instead call the serial.read() method.

It is suggested that you check if there is any data available and if there is you would read it once and save it to a variable. Then you can check this variable many times and decide what action to take based on its value.  If you read the buffer many times you would be pulling a new byte of data from the buffer with each read.  If you run out of data to read you will be supplied with the value of -1 as an indication there is no more data.


If I understand correctly your goal is to receive data on your computer from an arduino connected with xbee? You could use a USB > Xbee board similar to Sparkfun's Xbee USB explorer board. I am not familiar with the shield that you are using, but some xbee shields allow you to select the pins that the xbee is connected to. It sounds like yours is defaulting to Pin 0 and Pin 1, hardware serial on the Uno. If you can switch it to Pin 2 and Pin 3 (or any two digital pins) you could use software serial with the xbee, leaving hardware serial free for your USB connection.


High Precision Temperature Sensor LMT70 connection to arduino mega

Every electronics component has a document that describes it. It is called a "datasheet".

This is the page for the LMT70: ti.com LMT70
The red text is for the datasheet as pdf document, or else you can use the tab "Online datasheet", and the datasheet can also be found under the tab "Technical documents".

According to the datasheet it works with 5V, you can use it with the Arduino Mega (which is a 5V Arduino board). Connect the analog output of the sensor to an analog input of the Arduino Mega.

If you don't use the T_ON, then the datasheets says: "Tie this pin to VDD if not used". That means you can connect T_ON to 5V.

Do you have the chip (the sensor) only, or do you have a module with the sensor on it ?

Since the sensor has an anlog output, the accuracy depends not only on the sensor but also on the Arduino and the Arduino voltage reference. If you need a highly accurate temperature measurement, then you better buy a digital temperature sensor. For example the Si7051.

I suggest to use the 2.56V Internal Analog Voltage Reference.
The sensor has 1375.2mV output at -55°C and 302.8mV at 150°C.

const float aref = 2.56;  // adjust it to the actual AREF voltage
int adc_value = analogRead(A0);
float voltage = float(adc_value) * aref / 1024.0;

float t1 = voltage - 302.8;  // get rid of voltage offset
float t2 = t1 * (150.0 + 55.0) / (1375.2 - 302.8); // match range
float temperature = 150 - t2;  // negate and offset.

When you measure the AREF pin with a good multimeter and fill in the correct voltage in the calculation in the sketch, then you can get 1°C accuracy for the temperature. Perhaps you can get near 0.5°C accuracy, but no more. The sensor is more accurate than the Arduino Mega.


How to use ADC interrupt on STM32 blue pill

I couldn't find the function being called directly, but there's a good example explaining how to attach interrupts to the ADC which works well: https://github.com/rogerclarkmelbourne/Arduino_STM32/blob/master/STM32F1/libraries/STM32ADC/examples/SingleConversionInterrupt/SingleConversionInterrupt.ino
If anyone knows the actual function being called directly that would be great to add on here, but until then this example does what I need and will hopefully help others having the same problem.


Help with button library, hold>2s doA else doB

The loop() and clearScore() code that you have is like the following.

void loop() {
  clearScore(); // sets both home and away scores to 0 or enters settings menu
}
void clearScore() {
  ms = millis(); //record the current time
  clearBtn.read(); // Read the button
  if (clearBtn.pressedFor(2000)) {
    // Enter settings menu
    Serial.println("Settings Menu");
    while (clearBtn.read()!=1) {
      // do stuff
    } // End While
    return; // Don't proceed to next if
  }
  if (clearBtn.wasReleased() && !clearBtn.pressedFor(2000)) {
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

When you reset the Arduino and then hold down the clearBtn, clearScore() will be called repeatedly. clearBtn.pressedFor(2000) will not be satisfied during the first two seconds of holding the button down, and clearBtn.wasReleased() will not be satisfied either, so clearScore() will do nothing during the first two seconds.

After the first two seconds, "Settings Menu" will be sent repeatedly:  clearBtn.pressedFor(2000) is true, so the first if succeeds each time clearScore() runs, and it will run repeatedly because it is called from loop().  The while test, clearBtn.read()!=1 [which in more-idiomatic C would be written as !clearBtn.read()] fails until the clearBtn is released, so the while loop does nothing.  Also, clearBtn.wasReleased() will be false, so the other if does nothing.

When the button finally is released, clearBtn.pressedFor(2000) goes false, so the first if fails and the second executes one time.

Here is some code that should act more like what you want, as expressed in your comment,

  It's supposed to work like this: 1) hold button down for 2 seconds to enter settings menu. While in settings menu I'll code other stuff. Stay in settings menu until the clear button is pressed momentarily again. Once you press clear button again from being in the settings menu, the score should NOT be reset, and it should just return to the main loop. 2) if the clear button was not pressed for more than 2 seconds, just clear the score.

void clearScore() {
  ms = millis(); //record the current time

  while (clearBtn.read()) {
    if (clearBtn.pressedFor(2000)) {
      Serial.println("Settings Menu"); // Announce Settings menu
      while (clearBtn.read()) {}       // Await button release
      while (!clearBtn.read()) {       // Await button press
        // do  Settings menu stuff here
        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }
    return;
  }

  if (clearBtn.wasReleased()) { // See if released, after short press
    score=0;
    Serial.println("Clearing Scores");
    delay(50);
  }
}

Edit edit: To avoid  resetting the score at every settings exit, in the above code replace

        // (possibly wait for clearBtn release, to
        // avoid immediately clearing score again)
      }
    }

with

      }
    }
    while (clearBtn.read()) {} // wait for the settings-exit clearBtn release
    clearBtn.read(); // Do another read to avoid clearing score on next clearScore()

That is, right before the return, wait for clearBtn release, and read it again to be sure later reads won't register a release.  The latter read might not be needed, because clearScore() does a read when it tests the first while condition; you could experiment.


too few arguments to function 'void setColor(int, int, int)'

In the context of C/C++, the type char refers to a primitive type that can contain exactly one byte of information, or 8 bits if you like.

  the serial is correctly displaying the 3 arguments (255, 000, 000)

In your question, you do not specify how you verify that this is indeed the information that returns from Serial.read. Serial.read returns one byte, which can be cast or parsed to an Integer but cannot be interpreted as the triplet (255,000,000) in no way. If you keep calling it repeatedly, however, as long as there is data (meaning that the result is greater than -1 or Serial.available returns a number greater than 0) - you can accumulate the characters to a meaningful string, which you can later split to three different int values. For example:

String incomingData = "";

void loop()
{
    if (Serial.available() > 0) {
         delay(100);
         while (Serial.available() > 0) {
             char c = Serial.read();
             incomingData.concat(c);
         }

         // now, the string incomingData will contain "255,000,000" which you can split into 3 different integers and send to setColor.
         // so, assuming the format "ddd,ddd,ddd":

         int color1 = incomingData.substring(0,3).toInt();
         int color2 = incomingData.substring(4,7).toInt();
         int color3 = incomingData.substring(8).toInt();
         setColor(color1, color2, color3);
    }
}


I²C only works when I short-circuit my Arduino

Any ideas what I'm doing wrong?

Apart from deliberately shorting +5V to ground? Sheesh!

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

  You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".

Wire.begin() enables the pull-ups. So make sure that on the Nano side you disable them again:

  Wire.begin (4);
  // disable internal pullups for twi.
  digitalWrite(SDA, LOW);
  digitalWrite(SCL, LOW);


Infrared sending not working slight misconfiguration?

There are two basic things wrong here - one with your understanding of the timings, and the other with your understanding of how IR communication works.
First the timings - those are both ON and OFF timings. You don't just turn on for a defined length of time - you turn on for a defined length of time and then turn off for another defined length of time.
So for the timings in your code 4507,4507,573,1694,573,...etc... you would:

Turn on
Wait 4507us
Turn off
Wait 4507us
Turn on
Wait 573us
Turn off
Wait 1694us
Turn on
Wait 573us
... etc ...

You have no "off" time in your code, only ever on times.
Secondly is your understanding of IR communications. It does not involve turning an LED on or off for defined times. It's not as simple as that. Instead you are controlling the modulation of an LED.  When the LED of an IR remote control is "on" it's not just turned on - it's rapidly turning on and off. The receiver looks for the presence or absence of this rapid turning on and off light. This is the "carrier frequency" of the signal and must match what the receiver is looking for.
Typically this is between 30kHz and 50kHz depending on the receiver.
So you need some way of generating that rapid on-off signal. Normally this is done using PWM by the IR libraries and switching between 0% and 50% duty cycle for the off and on periods of the signal you want to send.
So it's far simpler to just use a library that does all this underlying work for you.


If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

If you are powering off USB leave everything alone. See the schematic:

The blue line added by me shows what is going on. The VBUS signal from the USB connector goes through a 500 mA resettable fuse (to protect the USB port from overloads). Then it goes to the P-channel MOSFET (FDN340P) which makes a decision about whether to switch on and connect VUSB to +5V signal. It does so if VIN is low, making the MOSFET conduct. If VIN is high (which it would be if you had power into the VIN part of the board) then it disconnects the USB from the +5V line.

  If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?

Definitely not. The 3.3V line is an output from the 3V3 voltage regulator. To connect it to ground would heat it up and destroy it.

  If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?

No, VIN is already connected to ground via a 10k resistor (see schematic above) and thus it is not floating.


How does the dual 5V and 3.3V output on the Uno R3 work exactly?

Pins of the UNO/Nano/Mini/Mega board are connected to GPIO pins of the MCU without any additional circuit. The ATmega MCU running at 5 V will sense 3.3 V as HIGH because of the threshold level to convert voltage to logic state.

ATmega will read the pin HIGH from 0.6 * Vcc, so at 5 V Vcc the threshold is 3 V.

Sources:

Schematics of Arduino Uno
Datasheet of ATmega328p (28.2 DC Characteristics)


How to count the voltage pulses of a digital temperature sensor using Arduino Mega Atmega2560?

There are function called pulseIn which probably need exactly what you want.

Just set a variable with the current 'time' (millis, start counting until the current time reaches 50 ms later.

So something like (not checked):

unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  pulses++;
}

PIN is a constant or variable that defines the pin number to check, LOW is to check low pulses, you also can use high, and optionally you can add a timeout. For example, you can use the timeout to check the last timeout is within the 50 ms region. Or to be more precise, check if the pulse was within the same 50 ms:

unsigned long timer = millis();
unsigned pulses = 0;
while (timer + 50 < millis())
{
  pulseIn(PIN, LOW);
  if (timer + 50 < millis())
  {
    pulses++;
  }
}


It is a very bad idea to use float.
That being said. multiply by 2 and do a standard round.
Then divide back by 2.

For example:

1.34     *2 = 2.68
round(2.68) = 3
3        /2 = 1.5

and

32.78    *2 = 65.56
round(65.56)= 66
66       /2 = 33


Wire with MCP23008 I/O expander with I2C

Everything is fine and nothing is wrong.
You are reading the GPIO register and its contents is 0x07.

The NACK at the end is not an error, it is a way to communicate between the Master and Slave.

When the Master reads data, the Master gives an ACK after each databyte from the Slave. The Master is not trying to tell the Slave that it was received, but rather it tells the Slave that another byte is going to be read.
After the last databyte, the Master send a NACK and after that a STOP.

Since only one byte is read, the Master sends a NACK and a STOP. The Master is telling the Slave that no more data is needed.

The I2C bus is only two wires. There are START, STOP, ACK and NACK conditions and the clock pulse can be stretched by a Slave. The possibilities are limited. For example when the Master wants to read 6 bytes and the Slave has only 1 byte. The Slave has no way to tell the Master that it has only 1 byte, and the Master will read those 6 bytes, valid or not.


The Atheros chip on the Yún is run off 3.3V, but the AVR chip, which is what is connected to the external pins, runs off 5V. What you are seeing is normal (a bit low though, but within spec).


How to connect more than one arduino serial port together

You can do it with two diodes and a resistor:

simulate this circuit – Schematic created using CircuitLab
You'll still have to implement some system to prevent collisions, but electrically that will be sound.


The solution:
On the image is stated plugs are solder-side. So swapping pin 2/3 does the trick


This problem was solved on Texas Instruments Forum.
Thanks.

http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/p/627185/2344271#2344271

From the TI forum:

  I noticed that you are polling data ready and then performing the data processing/serial output. The serial output operation is likely taking a long time and preventing you from capturing data at the faster data rates. You can try disabling the serial output and using an oscilloscope to see if you're able to reading data at the full throughput; however, when outputting this data over a serial interface you might not be able to capture and display all of the data...

  I would try capturing data to memory and outputting the serial data in batches (for example, output 10 samples of data at a time). This might give you a little more data throughput.


Is it possible to create an electromagnetic wave using PWM?

I had a toy project a while ago that generated AM radio.

Code

Code for Uno or any Atmega328 based boards:

const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

Wiring

Plug a wire into digital pin 9:

Theory

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 kHz, since one toggle turns the output on, and second toggle turns it off.

Then by turning the output pin on and off slowly you effectively have "keyed" output.

Obviously this would not have a long range, but you could amplify the output signal.

  What does the timer code do?

It's a bit easier to understand if you look at the datasheet. I did a summary for Timer 1 (and the other two timers on the Atmega328) a while back.

Timer 1

The lines assigning to TCCR1A and TCCR1B set various bits as per the chart / datasheet. Then OCR1A is the value that the timer counts to, zero-relative, so it counts to 10.

The prescaler is set to 1, so each "tick" is 1/16000000 of a second (62.5 ns). Count 10 of them and you have 625 ns per tick. The timer is configured to toggle an output pin automatically. Since it takes two toggles (on and off) for one frequency "cycle" the period is 1.250 µs. The inverse of that is 800000. Thus the output frequency is 800000 Hz (800 kHz).


printTemperature() is declared void (i.e., nothing returned) but it contains a return statement, and you've attempted to assign the (void) value. You probably meant to declare the function as 'float'.


No, the first lines should be:

if(temperature < baselineTemp) {
  digitalWrite(2, LOW);

Thus the else should be removed; after the first if and later else or else if conditions, statements can be placed.

Next time align your code by selecting it and select ctrl-K.

Also, your code can be much more simplified.

Hence the following (reverse engineered) requirements:

pin 2 is HIGH when temperature >= baselineTemp + 2, else LOW
pin 3 is HIGH when temperature >= baselineTemp + 4, else LOW
pin 4 is HIGH when temperature >= baselineTemp + 4, else LOW

So your entire code can be written as:

digitalWrite(2, temperature >= baselineTemp + 2 ? HIGH : LOW);
digitalWrite(3, temperature >= baselineTemp + 4 ? HIGH : LOW);
digitalWrite(4, temperature >= baselineTemp + 6 ? HIGH : LOW);


Printing Serial Readings for 2+ Parallax Ping Sensors

Your problem is in how you are working with the two sensors. At the moment you are triggering both sensors together then waiting for the first one to echo back. Only when that has responded do you then wait for the second one to echo back, and that echo has been and gone already.

Imagine you have two tennis balls. You throw them both at different walls at the same time, then attempt to catch them both. While you are catching the first ball the second one bounces off the back of your head and rolls under the table. That's what's happening with your echos.

So instead you need to treat both sensors completely separately. Trigger the first, then get the response. Then trigger the second and get the response.


Error in defining Ticker in ESP32 library

ESP32 ticker attach functions take pure function pointers with at max one argument type -- not a std::function/ std::_Bind_helper that std::bind produces.

See code and types at https://github.com/espressif/arduino-esp32/blob/master/libraries/Ticker/src/Ticker.h#L38.

For the ESP8266 however, they do use a std::function:

https://github.com/esp8266/Arduino/blob/master/libraries/Ticker/src/Ticker.h#L36

And that's why it works on ESP8266 and not on ESP32 -- either adapt the Ticker library or rework your own code to not use member functions of classes.

Edit: You can easily rewrite your code to use a static helper function with one argument (the watchdog object itself) which then just calls the member function of that object. For this to work, the called function must be public. So a rewrite like

static void watchdog_timer_triggered_helper(myIOT32* watchdog) {
   //needs to be public!
   watchdog->_feedTheDog();
}

void myIOT32::_feedTheDog()
{
  _wdtResetCounter++;
  if (_wdtResetCounter >= _wdtMaxRetries)
  {
    sendReset("Dog goes woof");
  }
}
void myIOT32::_startWDT()
{
  wdt.attach(1, &watchdog_timer_triggered_helper, this); // Start WatchDog
}

void myIOT32::sendReset(char *header)
{
  char temp[150];

  sprintf(temp, "[%s] - Reset sent", header);

  if (useSerial)
  {
    Serial.println(temp);
  }
  if (strcmp(header, "null") != 0)
  {
    pub_msg(temp);
  }
  delay(1000);
  ESP.restart();
}

Since both the ESP32 and ESP8266 versions implement the

    template<typename TArg>
    void attach(float seconds, void (*callback)(TArg), TArg arg)

templated function this should work on both platforms now.


How can I use the NRF24L01 modules without a library?

You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).

However, for this, you need to understand the library, and therefore high likely the datasheet too.

You also can start without looking at a library, but your only documentation source is the datasheet itself.

A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.


Avrdude verification error after months of successful use

Still don't know why, but now have a fix. Re-running the 'Burn bootloader' command from Arduino allowed me to then burn my firmware. Not sure if the issue is with fuses somehow being changed, or what, but this seems to have fixed the issue.

One more fun fact - I tried the same thing on a brand new Mega - same effect. First trying to burn my firmware resulted in a verification error (at a slightly different address), then burned bootloader and re-burned my firmware successfully. Wondering if an update to boards.txt or avrdude came through and changed something.


Attiny85 - Method to discard glitched ADC values?

I have no idea why they haven't used a fixed pull-up, but the pull-up
  is only done when the controller wants to read the sensor for only
  about 120us.

If you want to get a good resolution in the resistance measurement, the
resistance of your pull-up should be in the same range as the resistance
of your sensor. If your sensors have low resistance, this means the
voltage divider will draw significant current. In order to save energy,
it makes sense to power the voltage divider only while you are doing the
measurement.

  the reading window is really small (100-120us).

That's short indeed. If you analogRead() a single channel in a tight
loop, you will get one reading every 108.6 µs (128×14 CPU
cycles ÷ 16.5 MHz), and you have a small risk of missing the
window. If you are reading two channels, then you have about 50% risk of
missing the window.

Here is what I would do:

Set the ADC prescaler to 64 instead of 128. This way you will get one
reading roughly every 54 µs, and at least one sample (but more
often two) during the reading window.
Read a single channel in a tight loop, until you get a value above
your minimum. Then take one more reading and use the largest of the
two as your “good” value.
Switch to the other channel and go back to step 2.

This assumes that outside the reading window your ADC input reads close
to zero, as it is grounded through the sensor, with no pull-up. You then
have, on each channel, a train of positive pulses, and you want to
measure the height of those pulses. There is a small risk of you
sampling the rising edge of a pulse, which could give a wrong value
which is nevertheless above your minimum. If this happens, then the next
sample will be near the center of the pulse. That's why I recommend
taking one extra sample and using the largest of the two.


so I think I got it, the problem was that on a fail wire.read() returns an int -1
when that gets converted to a unint16 its a big number then it gets left shifted and overflows
the solution was:
uint16_t SparkFun_Ambient_Light::_readRegisterLight(uint8_t _reg)
{
    int lsb;
    int msb;

    _i2cPort->beginTransmission(_address);
    _i2cPort->write(_reg); // Moves pointer to register.
    if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released

        unsigned long tstamp = millis();
        while ((_i2cPort->available() < 2) && ((millis() - tstamp) < 10));

        if ((_i2cPort->available() < 2)) {
            _i2cPort->requestFrom(_address, 2); // Two reads for 16 bit registers
            lsb = _i2cPort->read(); // LSB
            msb = _i2cPort->read(); //MSB

            if ((lsb >= 0) && (lsb <= 256) && (msb >= 0) && (msb <= 256)) {
                _regValue = lsb + msb * 256;
            }
        }

        return(_regValue);
    }
    else
        return _regValue;//last read
}

This contains some extra error handling I added, but will leave in such as:

timeout on waiting for a response
checking on properly closing the bus in end transmission
checking for errors from the read

I didn't do error handling as I would need to rewrite the whole library, and for my application repeating the last reading is sufficient.


Do we really need to upload Arduino bootloader for new Atmega IC

No, you do not need the bootloader for your chip to function.  The bootloader is merely a convenience.

If you are programming through USBasp you don't even need it on a "normal" Arduino board.

All it does is allow you to program through the UART interface (or USB interface in the case of ATMega32U4 boards). If you don't want to do that then you don't need the bootloader.

If you do not provide a UART interface to the user that can be connected to then the bootloader would be pointless anyway since you cannot communicate with it.


How to connect receiver in an Arduino with a motor shield?

Adfruit Motor Shield v1 takes digital pins(D12 to D2) left only digital pins (D13,D1,D0) and all Analog pins of Arduino uno. So if you want to hookup RF receiver with Arduino then you have go this way.. connect RF Receiver output to the Digital pin D0 that is RX.

Here the schematic


Trying to determine the phase difference between two square signals

There are a few things very wrong here.

First problem: you are clocking Timer 2 with the prescaler set to 1.
This means the timer will roll over every 256 CPU cycles. Your
input signal, on the other hand, has a period of 25 µs, which is
400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you
know beforehand that the phase difference is within some window less
than 16 µs wide, your readings will be ambiguous.

You have to make sure the rollover period of your timer is larger than
the period of the input signal. This means either using a larger
prescaler (8 should do), which will decrease your phase resolution,
or using a 16-bit timer instead of an 8-bit timer.

Second problem: you are using a signed integer type for the timer
readings. This makes little sense. Worse: you are computing differences
like t2-t1, which can overflow. Signed integer overflow is undefined
behavior in C++, and
invoking it is always a bug.

You should declare t1 and t2 as unsigned, i.e. either
volatile uint8_t, or volatile uint16_t (if using a 16-bit timer).
Then you don't get overflows: you get instead a well-defined rollover
behavior.

Third problem: you are doing comparisons like if (t2 > t1). This,
again, makes no sense, if only because the timer is repeatedly
rolling-over to zero. You should instead just compute t2-t1 and work
your way from that.


dot matrix arduino turn off the intermittent led

You can't just turn them on like that.
Instead you have to turn one row on. Then the next row. Then the next. Very fast.
So you first display:
O@OO
OOOO
OOOO

Then you display
OOOO
OO@O
OOOO

Then you display
OOOO
OOOO
O@OO

And you cycle through that very fast.  Usually using a timer to run it all.  The fact that you're using '595s will slow you down and make it harder to update fast enough to look non-flickery.


What is difference between ATMEGA32 and ATMEGA328?

I can't post comments.
One difference is that the ATmega32 has JTAG; ATmega328P has not.


Welcome to Arduino.SE. The documentation that you seek on PCIFR and PINC would not be documented under Arduino, this is as these are directly related to the ATMega328 (AVR Atmel micrcontroller) which is on the Arduino, they are registers which are inside the microcontroller and PCIFR and PINC are mnemonics.

For the ATMega328 you will find the documentation to these registers in the datasheet (a good read with coffee), or in tutorials written by others explaining this information in an easy to grasp way.

The PCIFR register is the Pin Change interrupt flag register(description on pg 73 of linked datasheet), this holds the flag bit to tell the microcontroller that there was an interrupt and runs the ISR() routine that one has set out. Read this post by Nick Gammon on Pin Change Interrupts, and then read all of the post to get a better idea of interrupts in general.

The register PINC is for the inputs to the microcontroller, when one uses staus = digitalRead(A0); they are in effect using a wrapped up version of bitwise math and bit manipulation when simplified to status = PINC & (1 << PC0); thus PINx (x is for the register name ABCD) represents the state of the pin, either HIGH(1, 5V, true) or LOW(0, 0V, False). Borrowing from the below linked tutorial:

Another nice description of the input ports in this tutorial.

From the image you see that moving a bit to a position and then bitwise & that with PINx you will have a value returned if there is a 1 in that position.

 PINC      0b00001001
(1 << PC0) 0b00000001
         & __________
status  =  0b00000001

The above shows how you only get the state of the first input and how the 4th input is ignored as it was not needed. Also worth noting PIN is the register description and is not the same as a physical pin that sticks out the IC's body.


Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes

I am too building a RF24 based network there were two issues I encountered:

1) Update your libraries, use TMRh20 fork of RF24 (to make your life easier, use RF24Mesh too)

2) Add a decoupling cap to the NRF24L01+ power pins.


When you attach a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you write to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated.  That is how servos work.  They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven.

Depending on the servo you might actually damage the mechanics by driving it backwards like that.

The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.


Making Servo Motor Automatically Move Based on Input

So you have a "number" and you want to set the servo to some angle. The logic is very simple:

If number is 0 then set angle to 90
If number is 1 then set angle to 45

etc.

How you "get" the number hasn't been specified, so I will assume you just have an integer with a value between 0 and 5 inclusive.

Setting a servo's angle is as simple as writing that angle to the servo:

servo.write(45); // Set the angle to 45 degrees

So how do you join the two together?  Well, there's three different ways that spring to mind.

A string of if statements
A switch construct
An array

The first one is just like the bullet points above, just written as C:

if (number == 0) servo.write(90);
if (number == 1) servo.write(45);
... etc ...

The second method is very similar but can be more efficient when you know you only ever select one item from a list of options.  Read this to see how: http://hacking.majenko.co.uk/time-to-make-a-switch

The third option, the array, is especially good when you have a lot of options to manage and they are all the same result with a different value:

const int angles[6] = {90, 45, 315, 0, 0, 0};

// ... later ...
servo.write(angles[number]);


Reed Sensor matrix for chess board query

Almost all switch matrix keyboards use normally open / momentary contact switches. Consider this when discussing switch matrix behavior. Your initial (text) description is of a switch matrix only comprising of switches.  For such a matrix, only one switch may be closed at any given moment. This is to prevent aliasing.  A conditions where multiple simultaneous switch closures cause the incorrect key to be detected. And, in some cases, prevents harmful shorts.

Adding a forward biased diode to every switch in a matrix prevents harmful shorts.  For a design where one row is driven high and all other rows are driven low, closing two switches in a single column can directly connect the row driven high with a row driven low in a switch matrix only comprising of switches.  However, if a normally forward biased diode is placed in series with both of these closed switches, only the diode connected to the row driven high would be forward biased.  The diode connected to the row driven low would be reversed biased preventing the harmful short.

Using diodes on every switch is costly.  Most computer keyboard do not use this approach.  Instead they use clever circuitry and layouts to prevent shorts and improve their perceived performance.  In reality, almost all computer keyboard have an n-key-roll-over limit.  A point at which the keyboard fails to detect or distinguish a new pressed key while other keys are already pressed.

For a graphic example of the behavior of a forward and reversed biased diode consider this image from allaboutcircuits.com where the diode on the left is in forward biased and the diode on the right is in reversed bias:


Detecting how many button presses(single tap, double tap etc) with two simultaneous buttons

You SHOULD pay attention to the following issues:

1. Floating input problem:

Symptom: the reading value from the input pin is not matched with the button's pressing state.

Cause: input pin is NOT used pull-up or pull-down resistor.

Solution: Use pull-up or pull-down resistor. See Arduino Button (with pull-up/pull-down)

2. Chattering phenomenon

It should be considered in only some application that needs to detect exactly number of the pressing.

Symptom: Button is pressed one, but Arduino code detects several times.

Cause: Due to mechanical and physical issues, the state of the button (or switch) is quickly toggled between LOW and HIGH several times

Solution: Debounce. See Arduino Button Debounce


As long as whatever you're connecting the MISO, MOSI, and SCK pins to doesn't mind being driven externally, you can still program the ATTiny in-circuit - just break out those pins with reset to a standard 6 pin header and program them that way.

If one or more of those pins can't be driven externally (eg, because they're connected to another device that drives them and has no output disable), you'll need to add a tristate buffer IC between the MCU and the other device, or some jumpers you can remove when you want to program them.


Storing latitude and longitude floats as chars with specified precision

When formatting serial output is a concern, it's worthwhile to download and use the Streaming.h contributed library that adds some “syntactic sugar” to Arduino C.  That is, at compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  If you don't have Streaming.h installed, you can get Streaming5.zip from arduiniana.org.

At present, Streaming.h doesn't support setw() and setfill(), which in ordinary C++ set a field width and a fill character.

However, it does support  four base-conversion specifiers, _HEX, _DEC, _OCT, and _BIN; a _FLOAT function with number of decimal places specified; and endl.

Thus, to print  “Your coordinates are -23.123456, 135.123456” one would write:

Serial << "Your coordinates are " << _FLOAT(latitude,6) << ", " << _FLOAT(longitude,6) << endl;

Note that unlike the String class, use of Streaming.h does not entail any dynamic memory management – everything it does happens at compile time – and it does not increase code size – it translates stream-style operations into ordinary .print() and .println() calls.  It should result in somewhat smaller, faster, and more-robust code, by avoidance of String.  Use of dynamic memory on small-memory embedded systems can be problematic, and this avoids those problems.

Edit 1a: As Chris Stratton points out, Arduino floats don't support 9-digit precision.  I think Arduino floating-point arithmetic is intended to comply with IEEE 754, which sets out standards to be used on modern computers that support floating-point arithmetic.

In the binary32 format used to implement IEEE 754 single-precision binary floating-point, significand precision is 24 bits.  That equates to about 7.22 decimal digits (ie, 24*log₁₀(2)), so for simple calculations, 7-digit accuracy is realistic, more than that is not.

[Part of] Edit 1b:  In the larger scheme of things perhaps there's no need to create and save a formatted string like that.  It is not useful for computing – the float values are better for that.  It is not needed for communication – another streaming write can be done.

Edit 2 [replaces most of 1b]: Streaming.h  doesn't build any strings, but just delivers the text of its <<-arguments character-by-character to a stream.  However, a PString class at arduiniana can build strings from stream inputs, as in the following example code.

#include <Streaming.h>
#include <PString.h>

char buffer[28];
PString pstr(buffer, sizeof(buffer));

void setup() {
  Serial.begin(115200);
  pstr.begin();     // Empty the buffer
}

void loop() {
  int first=50, second=100;
  pstr.begin();     // Empty the buffer
  pstr << 'X' << first << 'Y' << second << 'T';
  pstr += " hihi ";
  pstr << millis() << endl;
  Serial << pstr;
  delay(1000);
}

Here's what some of its output to Serial looks like:

X50Y100T hihi 263198
X50Y100T hihi 264199
X50Y100T hihi 265199
X50Y100T hihi 266201
X50Y100T hihi 267201
X50Y100T hihi 268201

What the sample of code does is first initialize a string buffer, then build part of a character string using streaming operator <<, then part of it using concatenation, then some more with <<, then print the string.  Note that the strings involved here are in fixed buffers, rather than dynamically allocated buffers like the String class uses.


Fade In/Fade Out with multiple LED strips

Each change of brightness requires sending out 48 LEDs x 3 bytes/strip, = 144 bytes = 1152 bits of data. Each bit needs 2.5uS of data, so 2.88mS minimum at 400 KHz data rate. I don't know what rate FastLED.h uses, might be as fast as 800 KHz. How many strips? 2? So double that.

Each string needs all of its data sent out if any one LED changes, so you might change 1 LED, and leave 143 alone, all the data still gets sent out. That's just the way the addressable strips work.


Initialize object with PROGMEM constants

const char* text; is a pointer to constant not a constant pointer (char * const text is a constant pointer). So you can assign a pointer to a constant char array to const char* text; even a pointer to an array in PROGMEM.

The compiler doesn't know the difference between a PROGMEM pointer and a pointer in SRAM. It is on you to work in code with a pointer to PROGMEM the right way.

so remove PROGMEM from const PROGMEM char* text;

add constructor to initialize an object.

A(const char* _text) {
  text = _text;
}

and then

A a(PSTR("Hello World!"));

EDIT:

you could use Arduino's F() macro and __FlashStringHelper type, because it is supported by Serial print and co.

class A
{
public:
  A(const __FlashStringHelper* _text) {
    text = _text;
  }
  const __FlashStringHelper* text;
};

void setup()
{
    A a(F("Hello World!"));

    Serial.begin(9600);
    delay(30);
    Serial.println(a.text);
}

void loop()
{
}

__FlashStringHelper type is trick to distinguish PROGMEM strings from char arrays in SRAM..


You can use another library for DHT: https://github.com/markruys/arduino-DHT
Although, the library is quite old, it works fine and has auto-detection feature.


Multiple libraries were found for "WiFiClient.h" using nodemcu

Simply Switch

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

to

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>


You can't really fiddle with the power circuitry of the Due. If external sensors need more power than the due can provide through its internal 5V connection, whatever you choose that to be (dictated by the USB connection used) then you will either have to use a higher voltage to feed the barrel jack, or better, power the sensors separately to the Due. Just remember to connect the grounds.


Connect two SD cards to one Arduino board and copy from one to another

You can't do it with your Arduino-Uno (and usual SD libraries).
SD cards are organized in 512 byte "sectors". You need at least one sector for the file system itself and one sector for the data. If you try to have two files open simultaneously, all your 2048 bytes RAM are required for the SD buffers and you can't return from the file open() call any more.


Converting a standard setup/loop sketch to a low power application?

This sketch is almost identical to the powerDownWakeExternalInterrupt.ino sketch that comes with the LowPower Library. I'm using INPUT_PULLUP and a N.O. push button switch to trigger it to wake up and turn an LED on.

#include "LowPower.h"
const byte wakeUpPin = 2;

// Just a handler for the pin interrupt.
void wakeUp(){}

void setup(){

  // Configure wake up pin as input.
  // This will consumes few uA of current.
  pinMode(wakeUpPin, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // Allow wake up pin to trigger interrupt on low.
  attachInterrupt(0, wakeUp, LOW);

  // Enter power down state with ADC and BOD module disabled.
  // Wake up when wake up pin is low.
  LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

  // Disable external pin interrupt on wake up pin.
  detachInterrupt(0);

  // Do something here.
  digitalWrite(LED_BUILTIN, HIGH);
  delay(2000);
  digitalWrite(LED_BUILTIN, LOW);

}


Is there a constant for the Maximum Unsigned Long value in an Arduino compiler?

Various limits.h files in the avr-gcc hierarchy define ULONG_MAX, which may be the value you want.  For example, on my system such files have paths ending with hardware/tools/avr/lib/gcc/avr/4.8.1/include-fixed/limits.h or with hardware/tools/avr/lib/gcc/avr/4.8.1/install-tools/include/limits.h and contain definitions like the following.

/* Maximum value an `unsigned long int' can hold.  (Minimum is 0).  */
#undef ULONG_MAX
#define ULONG_MAX (LONG_MAX * 2UL + 1UL)

Note, LONG_MAX also is defined in limits.h.

Note, arithmetic done in a form like

timeDelta = micros() - prevTime;

will be correct (regardless of whether micros() overflowed) for elapsed times up to 2³² microseconds, or about 4295 seconds.


What happens if I draw too much current from ATMEGA IO pin?

There's a few crude calculations you can do using some numbers from the datasheet.

This graph is in the datasheet:

It shows the voltage dropped by the high-side MOSFET driver in the IO pin for different amounts of current draw. From that we can get its resistance R(DSON).

For instance at 10mA, at 25C, the output voltage would be 4.75V. That's a 0.25V drop from the 5V supply voltage. So we can calculate the resistance as:

R=V/I = 0.25V / 0.01A = 25Ω

Now we have that resistance we can use it to calculate the actual current from the IO pin with an 8Ω load.  Simply add the two together:

25Ω + 8Ω = 33Ω

Now we can calculate the current through that circuit:

I=V/R = 5V / 33Ω = 0.152A

That is, of course, way above what the IO pin can actually supply (or so the datasheet says).

So what happens? Well, two things, basically:

The voltage on the IO pin will be below the 4.2V specification for the minimum of an output pin when HIGH, and
It will get hot.

The actual voltage will be, of course, V=I×R = 0.152A × 25Ω = 3.8V droped, so 5 - 3.8 = 1.2V

What is more critical, though, is the heat.  152mA through a 25Ω resistance generates P=I²R = 0.152 × 0.152 × 25 = 0.5776W. That's quite a lot. Enough to melt the internal circuits in the chip and release the Magic Smoke™.

Running at 50% duty cycle, though, makes a difference. That's 50% of the power, which makes a big difference to the heat.

What would the actual allowable heat be? Well, at 40mA, with 25Ω, that is 0.04 × 0.04 × 25 = 0.04W.

So you're generating more than 14 times the amount of heat you are allowed to. Even at 50% duty cycle, that's over 7x the limit.

Will it kill the chip? Well, possibly, possibly not. It depends how rugged the chip is and how well it can withstand the heat. Short bursts may be OK since the heat doesn't build up enough to melt things. Extended use, though, will make it get too hot, and things will go pop.


Your problem is your usage of sizeof(). It doesn't do what you think it does.
sizeof() gives you the amount of memory a variable takes up. It does not give you the number of elements in an array.
For example:
const int ONE[]={2,6};

sizeof(ONE) will not give you 2. It will give you 4. An int is two bytes in size (16 bits). An array of 2 ints is, therefore, 2x2 = 4 bytes.
So when you're iterating over a 2 byte array but counting 0-3 you're overflowing your array and reading from the next bits of memory - which happen to be the first two entries of the TWO array in this case.
To get the number of entries in an array you must divide the sizeof() by the size of the variable type the array is made up of.  The most common way of doing that is:
sizeof(ONE) / sizeof(ONE[0])

It's common to set up some macros at the time of array creation so you can easily refer to it later:
const int ONE[]={2,6};
#define ONE_SIZE (sizeof(ONE) / sizeof(ONE[0]))

You should also consider using an array of byte (or better, the standard uint8_t) where the size of one element will be 1 not 2, since you don't need to store any number > 255. It's still good to do the division of the sizeof() even with a 1 byte size in case you should ever need to change the variable type in the future. It's also a good habit to get into.


ADC value changing after changing Timer1 value in program

ADC doesn't show the same value again

You are not reading the ADC correctly, so ADC_READ() can return
anything. See the comments in the code:

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;  // not needed
    word avrdata;  // not initialized
    word abcdata;  // not used
    byte i;
    for (i = 0; i < sample; i++)
    {
        adcdata = 0;  // useless
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return (avrdata/sample);
}

The big issue is avrdata not being initialized. Its initial value is
whatever was left there (in the stack or some CPU registers) by the code
that ran before. The value returned by the function is then hard to
predict and depends on what the rest of the program is doing.

The other remarks I left in the comments are not that problematic,
although they are revealing of some lack of attention to detail. Same
for some badly named variables. Here is how I would implement this
function:

word ADC_READ(byte samples, byte time, byte channel)
{
    word sum = 0;
    for (int i = 0; i < samples; i++)
    {
        sum += analogRead(channel);
        delay(time);
    }
    return sum/samples;
}


I've seen so much fake projects from "Viral science". I'm not sure whether he/she simply don't know what he/she does or if he/she simply tries to trap people. This project is a race condition itself ;-).

Besides your battery is empty. I don't think it is a big problem to use a 9V block battery, but Gerben is right, it won't do its job for very long. Have you thought about using a LiPo or LiOn Accu and a Solar loader?

There are worse things I see:

The sensor is powered by 3.3V but you read the ON/OFF signal with a 5-Volt Pin. That could be a problem, if there are other voltage drops that lead to a signal the PIN can not recognize as HIGH. Check the documentation of the moisture sensor and if it allows 5V use 5V to power it. All sensors I have found on Google have at least a range from 3.3 Volt to 5 Volt.

Check the current consumption of the relay. It must not draw more current than the Arduino PIN can provide (40mA for the UNO). And, don't use PIN13 to switch the relay. There are so many others and PIN 13 is connected to the onboard LED, which draws 10 - 20 mA on its own.


Connect my arduino with ethernet shield to new router

Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP.
It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!


Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)

Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)

Or you can use external PoE injector and extractor:

For 100Mb networks are two unused communication pairs used as power lines:


MQTT (was WiFi) interference when using two nodeMCU devices

My bad!

Although my symptoms were consistent with WiFi interference, the interference was actually at the MQTT level.

The root cause was that I hadn't realised that each MQTT client must have a unique client ID. When the 2nd nodeMCU connected, it disconnected the first nodeMCU from MQTT, which then went into a reboot sequence to recover, which then returned the favour to the other nodeMCU.


Getting a random number for electronic dice

First of all, look at this line of code:

if (analogRead(BUTTON_PIN) == HIGH)

You probably want to use digitalRead(). Note that it is okay to use digitalRead() on an analog pin, just make sure to use the right pin number (A0, etc.)

From the Arduino Source:

#define HIGH 0x1
#define LOW  0x0

(Ignore the 0x, that is just specifying that it's hexadecimal. However, 0 and 1 are the same in any base)

So, really, this function is only activated when analogRead() returns 1, which could possibly cause a problem later if it doesn't check at the right time. Note: now is a good time to remind you about debouncing...

For your actual code, since you want it to be simple, I suggest you forget that code that you wrote. Arduino has a built in random library, which works unless you have some special need for a random number.

Your final code should look like something like this in the end:

void loop() {
    if (analogRead(BUTTON_PIN) == HIGH) {
        paintDieFace(random(1, 6);
    }
}

Note that you should also use this code here in your setup (make sure that analog pin is floating: nothing should be attached to it):

randomSeed(analogRead(A1));

It actually isn't random, just pseudo-random. That means it relies on an equation to generate what seem to be random numbers. Because there has to be a default value of where the equation starts (the seed), it will repeat the same numbers every time you run it.

If you're wondering how this works, know that the analog pin is affected by a ton of external factors when there is no other electric signal attached.


A servo is not the same type of motor as a stepper. A servo is controlled by a somewhat PWM signal (somewhat, because the servos position will come from the absolute pulse length, not the duty cycle). A stepper motor needs to get the different phases driven in the correct order. This is done by a driver circuit for stepper motors and you cannot use the servo shield for this purpose without any extra circuitry.

You should use drivers explicitly meant for your type of stepper motor. Most drivers will have 2 inputs: 1 direction input (HIGH level means driving the motor in one direction, LOW level in the other) and 1 pulse pin. Everytime a pulse (pin going to HIGH, stay there for a short time and going back to low; or sometimes vice versa) is reaching this pin, the stepper will do 1 step. So to let the motor spin at a certain speed, you need to provide a specific number of pulses in a specific amount of time.

Since you want to drive all steppers individually, you need 6 drivers (one for each motor) and 12 output pins on your Arduino.


How to call C functions from Arduino sketch?

You can extern "C" #include like the following:

extern "C"{
#include "crc16.h"
};

void setup(){
}

void loop(){
  CalculateCRC16("<09M", 4);
}

And the crc16.h file could be (some minor fixes, the #pragma once, a cast):

#pragma once

#include <stdio.h>
#include <stdint.h>

uint16_t crctable[2] ={ 0x0000, 0x1189};

uint16_t CalculateCRC16( // Call example CalculateCRC16("<09M", 4);
    const void *c_ptr, // Pointer to byte array to perform CRC on
    size_t len)        // Number of bytes to CRC
{
    uint16_t crc = 0xFFFF; // Seed for CRC calculation
    const uint8_t *c = (const uint8_t *)c_ptr;

    while (len--)
        crc = (crc << 8) ^ crctable[((crc >> 8) ^ *c++)];

    return crc;
}


Do I need resistors or capacitors on this relay?

Yes, that is too simple.

The Arduino's IO pin is not designed to directly drive a relay. It needs to go through a transistor first, and you must include a diode to absorb the back-EMF generated by the collapsing magnetic field.

Google for "Arduino Relay" and you will find hundreds of thousands of examples.

In short, the circuit you need to create is this:


Control I2C relay board from two Arduino Uno

What you want is to operate in multi-master mode.  This is a supported configuration of I2C - however the Arduino API has no support for it.

It involves each master identifying if a collision has occurred and stopping transmission if it has - to then retry transmission later on.

The Arduino hardware can do it, but the software can't. You would have to bypass the software and control the I2C interface yourself (or locate a better library than the Wire library that supports multi-master).


It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.

The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.

Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your setup() function, you can enable the pull-up on your input pin like this:

pinMode(BUTTON_PIN, INPUT_PULLUP);

That will cause the input to appear HIGH when the button is not pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.


Why am I getting "fatal error: SoftwareSerial.h: No such file or directory"

According to your comment:

  after commenting out those ifdef guards, it worked

I would say that is a bug in the Adafruit_GPS library.

As a matter of fact, the DUE is not using the AVR architecture (it uses ARM), that explains why #ifdef __AVR__ in Adafruit_GPS.h never passes; but then something else should be done specifically for the DUE (missing #else or #elif).

After checking on github, there is an issue open for that; unfortunately, as of April 2014, it has not moved for 10 months.

Your best guess would be to go there and try to "reactivate" this issue.


Char* and string conversion from an ESP8266 web server

What you need to do is creating a fixed string, this can be done in two ways:

static:

char ssid[100];

Where 100 is the maximum length ever possible. Note that this will always use up 100 bytes, even if less are used (e.g. your string length is 5.
dynamic:

char* p_ssid = malloc(100);

This way a pointer is created to a dynamically created string that can hold 100 characters. Disadvantage is that using malloc in a microcontroller can cause empty memory 'holes' when freeing/mallocing a lot.

With either way you can than use a normal strncpy or strcpy (in first case use &ssid to get a pointer to the ssid).
Also don't forget to add 1 to the length because of the trailing \0 to denote the string is ended.
Thus for storing 10 characters, you need an 11 char sized array.