47Effects MIDI Library and serial debugging

I assume you have one or more Arduinos, are trying to do MIDI control, and want to know how to debug with the MIDI library having commandeered the hardware serial port.

One approach is to use I2C or SPI to communicate with a second Arduino, which uses its serial port to deliver debugging data to a host system.  See Nick Gammon's excellent page  Debugging using SPI/I2C and a second processor (gammon.com.au forum id=11329), which illustrates communication between two Arduinos, using one of them as a slave to forward information sent by I2C or SPI from a system being debugged.

Another approach might be to use a serial bridge.  I don't know the ins and outs of this or exactly what it does but have read that, for example, the Hairless bridge (which is an open-sourced software package) can display both sides of MIDI communication, possibly depending on use of Serial.write vs Serial.print.  You could designate certain note sequences as standing for various debugging cases.

A third approach is use of Arduino software serial to send debugging data to a serial port on your host system.  This would use some Arduino pins other than the hardware Rx, Tx pins.

Edit 1:  Pin Usage –

For approach 1, using I2C ties up two specific pins, SDA and SCK.  These are shared with other I2C devices, if any.  SPI typically shares three signals – SCLK, MOSI, and MISO – among all SPI devices, and generates one SS signal per device.  For pinout and protocol details, see Nick Gammon's well-organized and clearly-illustrated I2C and SPI pages.

Approach 2 would use no extra pins.

Approach 3 would use one or two extra pins:  one for half-duplex or output-only communication (which may be adequate for debugging), two for separate Rx, Tx lines.  Compared to hardware serial, software serial is CPU-intensive, does not support as-high data rates, and has a higher error rate.  It should work ok for light-weight debugging output, such as occasional text to show what tests succeeded or failed or what branch was taken, or values of a few variables.


How to use a microSD card reader with SCK instead of CLK?

SCK stands for SPI ClocK

CLK stands for SPI CLocK

Two different acronyms for the same thing.


Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno?

I think it could work, but not easily. I.e. you would need to tweak the code and anyway you will end up with really low performance.

This is the reason:

  SPI: on the ICSP header. These pins support SPI communication using the SPI library. Note that the SPI pins are not connected to any of the digital I/O pins as they are on the Uno, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Leonardo's 6-pin ICSP header, the shield will not work.

Source: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

  The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster when drawing.
  If you plan on using the SD card on the TFT module, you must use hardware SPI.
  All the examples are written for hardware SPI use.

Source: https://www.arduino.cc/en/Guide/TFT#toc4

In the end I think it would be better to get the equipment needed...

Edit: You can try with this constructor:

  When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.

#define SCLK 4
#define MOSI 5
#define CS   6
#define DC   7
#define RESET 8

TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

Source: https://www.arduino.cc/en/Reference/TFTLibrary


Code that worked in Uno is not working in Mega 2560

SoftwareSerial relies on the Pin Change interrupt. Not all pins on the Mega have pin change interrupts.

But that is all a moot point really, because when you're using a microcontroller that has lots of real hardware UARTs there is no call to be using SoftwareSerial in any case.


Arduino MKR GSM 1400: Can I tell from code if the power has tripped

VBATT/2.4B is used for measuring the batter voltage using the internal ADC of the MCU. It can't really tell if the battery is being used or not - except by maybe monitoring it over time and see if the voltage goes up or down.
However the BQ24195 is where all your hope lies.  It has a status register that can tell you all sorts of things.
For example it can tell you if there is incoming power, and what that incoming power is coming from (a USB host, a USB power adaptor, or operating in OTG mode). It can also tell you what the battery is doing - if it's charging, or not for example.
A quick google search throws up this library specifically for the purpose.


Is there any easy way to change Arduino Wifi shield to ESP8266?

Consider porting your sketch to esp8266 board like Wemos D1. The API of the ESP8266WiFi library is same as the API of the WiFi library.

To use esp8266 as network adapter, you have two wiring options.

If you have or buy an esp8266 module with SPI pins, you can connect the esp8266 over SPI like the WiFi shield is connected. Then you upload the WiFiSpiESP firmware to esp8266 and you include in your sketch WiFiSpi library instead of WiFi library.

Second option is to connect esp8266 over Serial or SoftwareSerial. The esp8266 should have AT firmware installed. The you can include WiFiEsp library in you sketch and initialize it with the Serial interface of your choice. You can find the WiFiEsp library in Library manager. Most new esp8266 modules have AT firmware installed at default.

There is one more option for Serial connection, if WiFiEsp wouldn't work for you. WiFiLink firmware and library

All mentioned libraries WiFiSpi, WiFiEsp and WiFiLink have the same API as the WiFi library so the rest of the code should work without changes.


Why is my DHT22 sensor reading 1.00% humidity?

I have 2 suggestions for you.

If you compare these 2 data sheets:
This one says "adafruit learning systems" on it
and this one is from the Adafruit website
, you'll see there is a discrepancy regarding the pull-up resistor value to use. One document says 10k ohm, the other says 1k ohm. It's a bit of a long shot, but you could try adding another 10k ohm resistor in parallel with the one you already have on the data line. This gives you an equivalent resistance of 5k ohm which works when used on a DHT11 sensor (cheaper, less accurate version of the DHT22).
There are several versions of the DHTxx library out there, so my next suggestion is to try a different one. You may have to remove the library you currently have installed before trying a new one.


From Arduino reference: random
In short:

Syntax
random(max)
random(min, max)
Parameters
min: lower bound of the random value, inclusive (optional).
max: upper bound of the random value, exclusive.
Returns
A random number between min and max-1. Data type: long.

Basically your first random returns values {1,2} and second one is even better {0}


WizNet W5100 not connecting to modern switches and routers

I think your problem is due to the MAC address that is being loading into the W5100.  Try setting the 2 low order bits of the first byte to 0.

These bits define whether the MAC address is unicast or multicast and whether it is private or universal.  Some switches appear to block ARP requests if these bits are set incorrectly.

I changed the first byte of the MAC address from x'47' to x'44' and things started working.


You are ignoring the value read by analogRead().  You are then using the value A0 (14) in your sum to calculate the voltage.

Instead:

int adcReading = analogRead(sensorValue0);
int voltage0 = adcReading * (5.0 / 1023.0);

Although I think what you really meant to write was, in total:

int sensorPin = A0;
int sensorValue0;//output coming from demux pins
int sensorValue1;
int sensorValue2;
int sensorValue3;

void setup() {
Serial.begin(9600);
  Serial.println("start");
  pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  sensorValue0 = analogRead(sensorPin);
  float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  Serial.print("voltage0 = ");
  Serial.println(voltage0);
}

Note that the value sensorPin is where you read the voltage from, and sensorValue0 is where you store that reading. Also note the use of a float type to store the calculated voltage, since an int will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).


The CNY70 is just an IR LED and IR Phototransistor.  You can treat the IR LED (emitter) portion of it just like any LED and size the resistor appropriately.

The receiver is just a phototransistor which can operate at anything from about 1V up to 32V with no need to adjust anything.  The resistor used there is merely a pullup resistor.  You can think of the receiver as a button. When enough IR light falls on it it turns "on".

On an Arduino you could even get away without the pullup resistor and use an input in INPUT_PULLUP mode.


Problem with interpretting and using the IMU data

You may want to take a look of freeimu library which take care of all needed processing and present filtered and data-fused data (not just raw data) in easy to use roll, pitch and yaw format.

http://www.varesano.net/projects/hardware/FreeIMU

see demo video in which the on screen data mirror physical motion of the sensor
http://www.youtube.com/watch?feature=player_embedded&v=rFvX3vZJHTQ

hope this helps


Combining two sketches that both work on their own, but don't work when combined

Let's step back from the Arduino for a minute and ask: assuming you know how to cook some bacon, and also how to boil some eggs, how would you simultaneously cook bacon and eggs?

Basically you would have to interleave any process (such as waiting for the water to boil) with some other process (such as waiting for the bacon to cook).

Once you have this concept in your head you can just take the two pieces of code, and wherever you are planning to wait for something to happen, see if the other thing is able to be done.

I have done a post about this: http://www.gammon.com.au/blink

  I just figured out that the original password code will still function, but only if i keep the LED toggle button held down.

Well, you need to remove any blocking loops from either part of the code.

Your code here blocks:

if (digitalRead(button) == true) {
status = !status;
digitalWrite(led, status);
} while(digitalRead(button) == true);

That's like (in my analogy) of thinking "oh the water is boiling, I'll have to stare at the eggs until they are cooked". Instead you could check the bacon, check the eggs, check the bacon again, and so on.

I'm giving you these analogies to help you solve the general problem, not this particular bit of coding.

  i understand that the code blocks, but that code also makes the LED toggle on and off like i need, so how do i integrate that in a way that it doesnt block the rest?

Replace the LED code with something like this (not compiled or tested):

void loop ()
  {
  static int oldReading = LOW;
  int newReading = digitalRead (button);
  if (newReading != oldReading)  // it changed!
    {
    oldReading = newReading;  // remember new reading state
    if (newReading == HIGH)
      {
      status = !status;
      digitalWrite(led, status);
      }  // end of a HIGH reading
    }  // end of changed state

   // password stuff here

   }  // end of loop

Now, whatever you do with the button, the code doesn't stop (block) so the password stuff is still executed.


Gravity fan does not work when powered by 3.3V ESP8266

The ESP can only supply 12 milliamperes of current. The fan most likely uses a whole lot more. You could for example uses a transistor to turn on the fan.


Measure audio frequency through pulse duration

Timer 1 overflows at 255 because that's how it has been configured by
the Arduino core, as it is intended to provide 8-bit PWM. If you want
to use the timer in normal mode, you should undo the Arduino's
initialization by setting TCCR1A to zero.
Two comments on the ISR:
ISR (ANALOG_COMP_vect)
  {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
  }

First, as has been stated in a previous comment, you should not print
from within an ISR. Also, if you want consistent timing, you should
never reset the timer. Just keep it freely running and use time
differences to get the signal period. Do not worry about the timer
overflowing: if you do the computation with unsigned 16-bit integers
(uint16_t), you will be immune to the overflows. If you reset the
timer you will likely loose some ticks, as you can not read it and reset
it in the same clock cycle.
Lastly, I recommend you read about the “input capture” capability of
Timer 1. This is a feature of the timer designed for solving the exact
kind of problem you have here: the timer will automatically record a
timestamp on an external event. You can have this triggered by a rising
or falling edge on input pin 8, or by the analog comparator if you
prefer. This method gives you zero jitter, which cannot be achieved with
code, even running within an interrupt.

Edit: Answering an extra question in the comment.

Could i connect the audio wire [...] directly to pin 8 and use the
input capture functionality?

It depends on the shape of the signal that comes out of this wire.
First, you have to make sure the signal always stays between the
electric potentials of GND and Vcc (i.e. 0 – 5 V), otherwise you risk
damaging the Arduino.
Note that if the signal comes from a high impedance source, it can
safely go somewhat beyond this range, as the Arduino has all of its
inputs protected by diodes. You just have to limit the current in the
diodes to less than 1 mA. In other words, for each kΩ of output
impedance, you can extend the (unloaded) acceptable voltage range by 1 V
on each side. If the source is low impedance, you can make it high
impedance simply by adding a 10 kΩ resistor in series.
Second point is, you have to make sure the signal has a large enough
voltage span to make the digital input switch between LOW and HIGH.
According to the datasheet of the ATmega328P, when powered at 5 V the
input thresholds are typically around 2.1 V for switching LOW and 2.6 V
for switching HIGH. The difference between those thresholds provides
some hysteresis, which can help cancelling noise. Note that those are
typical values. If you want guaranteed switching, the signal should go
below 1.5 V to get a guaranteed LOW reading (this is VIL) and
above 3 V to get a guaranteed HIGH reading (VIH).
Note also that, if the input thresholds of the digital pin do not fit
your needs, you can use the analog comparator as a trigger for the input
capture.


Will enabling parity bit actually decrease corruption?

Parity doesn't, and was never intended to, decrease corruption.

All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.

Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.

When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).

Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.

Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.

An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).

All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.


IGND which is mentioned on page 4 of the datasheet is apparently proportional to the output current. This accounts for about 2-5% of the total current drawn by the regulator, depending on its load. With the maximum voltage drop of 4 - 3.6 = 400mV, a switching regulator will make no real difference. I think your only option is to find another regulator that has better efficiency.


Converting of 32 bit signed hex value to dec

Since the bytes you received in the buffer are in little endian order,
and your Uno is itself little endian, you don't even need to move bytes
around: you can just reinterpret the bytes you already have as an
int32_t:

union {
    uint8_t bytes[8];
    int32_t numbers[2];
} buffer;
unsigned char len = 0;

CAN.readMsgBuf(&len, buffer.bytes);
Serial.println(buffer.numbers[0] * 1e-6, 6);

This prints -0.967824 to the serial port.

Note that this code will not work as expected on a big endian platform.
If you want something portable, the usual solution is to build the
result using bit shifts, as in Majenko's answer.


Error compiling for board Arduino Uno SIM7000

I cloned botletics comparatively gigantic repo.  They've modified the Adafruit library without changing the name.
The problem appears to be that you are working out of the current master branch.  Switch to the latest tag, 1.1.0, and the SMS_Response example will compile just fine.  I didn't try all of the others.
Direct link to the zip file for the 1.1.0 tag.


How to interrupt a Timer to Change position along a Colour Cycle

You could start with the attachInterrupt example sketch and work from there. Here is a possible solution:

enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
const int buttonPin = 2;
const int ledPin[] = { 4, 5, 6, 7 };
volatile bool reset = false;
int state = GREEN;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
}

void loop() {
   digitalWrite(ledPin[state], HIGH);
   delay(7000);
   digitalWrite(ledPin[state], LOW);
   if (state == RED || reset) {
     state = GREEN;
     reset = false;
   }
   else {
     state = state + 1;
   }
}

void doResetState () {
    reset = true;
}

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().

Cheers!


serial communication dead slow after a while

If you print from arduino to serial and you don't read it then the buffer gets full. Causing it to go in a second delay. So make sure you read as well when you send data over.

A short sleep is required between the sleep and the read for some reason. Else it hangs.

import serial
from time import sleep

ser = serial.Serial('COM3', 115200)
sleep(1)

c = 0

while True:
    c+=1
    print("ok ", c)
    numIn = "100"
    ser.write((numIn + '\r\n').encode())
    sleep(1./120)

    inp = ser.readline()
    print(inp.decode("utf-8"))
    sleep(1./120)


VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a

'Serial' was not declared in this scope

This error is not surprising when compiling for ATtiny84 because in Arduino Serial refers to the hardware serial port and ATtiny84 doesn't have one.

But you didn't use Serial in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html

So in fact your sketch is attempting to use Serial without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.

Visual Micro does allow you to change the debugging output to software serial:

http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html

but since you say you have no pins available that may not be any help.


global volatile variable not being updated in ISR

You are using pos outside of the interrupt without turning the interrupt off.  pos is two bytes, so it takes the Arduino more than one cycle to read in that variable no matter how it is handled.  If an interrupt occurs during that time, you get a corrupted value.

You need to have a cli() and then make a copy of pos to another variable and then a sei() and then use that copy in your calculations in loop.


How can I declare an array of variable size (Globally)

Your question has 2 parts actually.

1/ How can I declare the constant size of an array outside the array?

You can either use a macro

#define ARRAY_SIZE 10
...
int myArray[ARRAY_SIZE];

or use a constant

const int ARRAY_SIZE = 10;
...
int myArray[ARRAY_SIZE];

if you initialized the array and you need to know its size then you can do:

int myArray[] = {1, 2, 3, 4, 5};
const int ARRAY_SIZE = sizeof(myArray) / sizeof(int);

the second sizeof is on the type of each element of your array, here int.

2/ How can I have an array which size is dynamic (i.e. not known until runtime)?

For that you will need dynamic allocation, which works on Arduino, but is generally not advised as this can cause the "heap" to become fragmented.

You can do (C way):

// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source)
if (myArray != 0) {
    myArray = (int*) realloc(myArray, size * sizeof(int));
} else {
    myArray = (int*) malloc(size * sizeof(int));
}

Or (C++ way):

// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source or through other program logic)
if (myArray != 0) {
    delete [] myArray;
}
myArray = new int [size];

For more about problems with heap fragmentation, you can refer to this question.


How to upload a sketch to Arduino if it goes to deep sleep mode quickly

Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.

If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.

Update:

  Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. This article has more information.


Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library

Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in PCD_ReadRegister() right before the for loop, and then n bytes are read, with 0 transferred the last time to stop reading.

A quick look at the library and datasheet shows that the rxAlign argument is used in identifying the first valid bit in the first received byte. txLastBits serves a similar purpose, only for transmission of the final byte. Both are written to BitFramingReg of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.

For example, in the function you have above, if rxAlign = 3, it means only bits 7 to 3 are valid in the first received byte, extracted with bit mask 11111000. So the first valid 'byte' comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, txLastBits indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and BitFramingReg.

Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

EDIT

I'll try to answer your questions:

In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
Bit-oriented frames are necessary for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

  Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.

If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward MFRC522 UART library, which doesnt implement anitcollision, by the way.

If you still want to port the SPI-based library, then, a few suggestions:

You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like PCD_ReadRegister(), PCD_WriteRegister() and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning rxAlign and whatnot. Good luck :).


ERROR on SIM900AT comand HTTPDATA (POST method)

If you say you are going to send 90 characters you must send 90 characters. No more, no less. I count 70 there.
You have to send them immediately the modem responds DOWNLOAD otherwise it times out (10 seconds) and you get ERROR. It looks to me like you're not sending anything (except maybe a blank line) for those 10 seconds and only trying to send once it has errored.


Using an external interrupt alongside serial

Transmitting a single character via UART on the ATmega328P (and all other AVRs with a dedicated USART) cannot be interrupted since it is independently clocked. Loading the next character into the transmit buffer can be (since the INTx interrupts have priority over the USART,xxx interrupts), but this will not actually break communications, just slow it down.


Is it bad to power a arduino mega with 6V via USB?

The Absolute Maximum Operating Voltage of the ATMega2560 is 6.0V. The same applies to the ATMega8u2 that does the USB to Serial on the Arduino Mega board.
Recommended maximum voltage is 5.5V
So yes, you can run it at 6 Volts, but you are right on the edge, so I wouldn't recommend it.
Possible risks are a decreased lifespan of the Arduino, and there might be some stability issues.
If the application isn't safety critical, and you don't mind having to replace the board after it failed in, say, two year of operation, it could be an acceptable risk (if there are no easily available alternatives)
PS you might want to measure you power supply. It may say it's 6V but could give out 6.2V. The output voltage of some supplies also vary with the load that's across it.


Is there a way to setup an interrupt to trigger at n number of clock cycles from now?

Use a timer to count the system clock and preload the counter with an offset that overflows in the desired cycles.
Use a timer to count the system clock and set a compare match a desired number of cycles out.

To expand the number of cycles, you can do fancier processing in thee Isr but the basic gist IS the same.

Other approaches also exist but the two outlined here are easier.


How does coordinator XBee receive data from router?

When you have one working as AT mode, it puts out whatever comes in, it is also called transparent mode.

You should first define which mode you want to use them and start coding.

If you choose AT, load the firmware for both and use Arduino to check the commands and execute tasks (supposing it is connected to the router).

If the task was done correctly, you send an okay message, otherwise, send error. This is a simple task in AT mode, just use Serial:

if (led == 1)
   Serial.println("ok");
else
   Serial.println("error");

If you choose API mode, it is a little bit different, where you have to mount the packet for sending data and put a message inside it. There are some libs out there you can achieve this.

On the other side, the coordinator will receive the message and interpret it.

If it is in AT mode, just read the serial. In API, you have to decode the packet and check the payload field where the data is located.


The "Serial" is a object/class and that makes it possible to have more than one function for Serial.print(). According to the type of the parameter the proper Serial.print() is selected.

This is the include file for the Serial.print(): Print.h
And these are the possibilities:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

The reference for Serial.print() is short, but it explains pretty well that those different parameters are possible.

Your Serial.print(88, DEC); does not use a string of text, it uses the integer number 88.

As soon as a string of text is used, it should be zero-terminated.
The line char buff[3] = "ABC"; is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.


You need to design your device to permit In Circuit Serial Programming - ISP.  This will let you continue to refine the program once the chip is in the circuit, and it will also be your primary method of programming and testing small production quantities.

Basically this means that the ISP and reset pins of your processor need to be able to be externally contacted - either by a header, pads for "pogo pin" spring contacts, an SOIC test clip, or perhaps micrograbbers hooked onto individual pins.

It also means that anything connected to those pins needs to not interfere with or be harmed by the programming process.  That particularly means that anything which could drive any of these pin needs to not do so while the MCU is being programmed, nor load them, nor get lastingly confused by operations the programmer does on them.

You'll also need an ISP programmer.  Proper ones are sold, but beware of cheap clones and marginal designs as these often give users plenty of trouble.  Fortunately, you can use an everyday Arduino running the ISP sketch to program ATtiny chips.  Do beware though, that if your target is powered at 3.3v it is not safe to use a programmer with 5v signals on it - you might get away with it a few times, but eventually it will cause issues.  So if you want to use an Arduino to ISP a lower voltage target, you either need an Arduino that runs at 3.3v, or to implement level shifting.

Do spend some effort to verify that you have the software support resources you may need for the ATtiny84A - it's one of the less common chips so it won't have the same degree of community support.

A further possibility is to use ISP to put a serial (or other) bootloader into the chip and then rely on that, however this won't cover all eventualities - if you discover you need to change the fuses, you'll need ISP for that, as it's something a bootloader can't do.


What phone carriers are available in the USA that are compatible with a sim900 breakout board

SIM900 should be compatible with both AT&T and T-Mobile. T-Mobile uses 1900Mhz for 2G and AT&T uses 850Mhz and 1900Mhz. Although both carriers are upgrading to 4G, they still support 2G devices. My personal experience is that most quadband 2G devices still work with AT&T and T-Mobile and there is no technical reason why SIM900 shouldn't work. However, there can be issues with incompatible data plans that are compatible only with their own devices. You need to be careful when selecting the contract and buying the sim card.

Nextel and Ting uses Sprint's network which is CDMA and thus wouldn't work. However Vodafone seems to be using T-Mobile's network and may work.


message received from GSM contains parenthesis instead of curly braces

One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.


Digispark don't work when I power it by 5v and GND inputs and chip starts heating

You connected the power backwards - so all the current is being shunted straight through the ESD protection diodes (and likely other routes too) generating lots of heat and risking permanent damage to the MCU.

Take better care next time...


Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.


Arduino has a library tutorial here: http://www.arduino.cc/en/Hacking/LibraryTutorial

and a formal specification here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

these explain the specifics to making arduino libraries, like the propeties files, the keywords file, and the directory structure. Most of that is unnecessary though.

Anyway, there are not many differences between the actual code in an arduino library and the normal code you write for arduino sktech. The only major ones being that

The arduino preprocessor doesn't generate function declarations - you have to make your own header file
You can't use setup or loop

Other than that, its just normal c++ code that exposes a particular interface and provides an implementation. If you want the library to work well for a lot of users, you will need to put in the extra work to make it run on all the different arduino hardware variants.

Making libraries for c++ often involves creating .a, .so, .dll etc. files of compiled code that new programs can link against, but arduino compiles everything from source for every sketch so you don't need to worry about that here.


Print with round towards zero instead of round to nearest

A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by 10.0f again:

float myVal = 123.89f;
myVal = (long)(myVal * 10) / 10.0f;
// = ((long)1238.9) / 10.0f
// = 1238 / 10.0f
// = 123.8

You can then print this modified number to the serial monitor.

This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

Note: You don't have to actually dynamically compute pow(10, numDecimalPlaces), you can also create macros for each decimal precision from 1 to x and simply precompute that value (100, 1000, 10000, ..).

The same can also be achieved by using the standard library function trunc from math.h:

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

See http://www.cplusplus.com/reference/cmath/trunc/.

Here's a small sketch in which it is demonstrated:

#include <Arduino.h>

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

void printValueFormatted(float value, int numDecimalPlaces) {
    //format correctly
    char buf[20];
    char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

    //skip over empty chars
    while(*res == ' ')
        res++;

    //print buffer
    Serial.println(res);
}

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

void loop(void)
{
    float myVal = 123.8978f;
    printValueFormatted(myVal, 4);
    printValueFormatted(TRUNCATE(myVal, 1), 1);
    printValueFormatted(TRUNCATE(myVal, 2), 2);
    printValueFormatted(TRUNCATE(myVal, 3), 3);
    printValueFormatted(TRUNCATE(myVal, 1), 4);
    printValueFormatted(TRUNCATE(myVal, 2), 4);
    printValueFormatted(TRUNCATE(myVal, 3), 4);
    delay(1000);
}

Prints

123.8978
123.8
123.89
123.897
123.8000
123.8900
123.8970


Why does my lcd screen work fine and then display random characters?

The problem was that I was adding ":" to the printed string on the lcd without making it a String object. That only occurred if I had double digit hours and minutes.

Incorrect way:

lcd.print(hours+":"+minutes);

Correct way:

lcd.print(hours+String(":")+minutes);


Can I use an Arduino Uno to support an RFID reader, Zigbee module and a touch screen at the same time?

Also I don't know what the RFID, zigbee and touch screen uses (generic GPIO pins, I2C, SPI, something else)?

You always can combine multiple inputs/outputs using a multiplexer (i.e. 74HC165, 74HC595), although it will mean extra software and less performance.

About the touch screen, that might be problematic regarding performance and memory usage, since the Uno has only a few KB and even the more expensive Arduino's do not have that much memory you might need.


My Arduino Fingerprint Sensor FPM10A is not working with an Arduino Nano with Atmega168 processor

Did you buy the arduino board Nano Atmega168 on Aliexpress? Sometimes the cheapest arduino compatible boards are okay, but sometimes they are stripped of decoupling capacitors or the polyfuse is missing (on a uno board). Sometimes they put a Atmega168 on the board, it is a few cents cheaper.

If you buy the cheapest nano compatible board, look at the photo if the quality is reasonable. The newer arduino boards have a ARM Cortex processors. The Atmega328p is still okay for small projects. I suggest to use the Atmega328p as the minimum.
A Arduino nano Atmega328p clone at Aliexpress costs about 2 dollars, so there is no reason to buy an Atmega168.

When the compiler tells you that "Low memory available, stability problems may occur" for the ram, then you can almost be sure that it will not work.

I try to keep about 300 bytes ram available for local variables, stack and the heap. It depends how much memory the libraries require. I also don't use the String objects for the Arduino uno or nano.
For a beginner, you can try to keep at least 500 bytes ram available.


Powering from 3V coin cell to VCC, using I/O pin as supply GND

Can I use a I/O as (input/supply) GND?

You can use an I/O pin as a supply for another (low power) device, but
you should power the Arduino itself from its Vcc and GND pins.

  I could use the reset button, but would it still give me "random
  enough" numbers?

You will likely see the very same sequence every time you reset it.
There are ways around this:

You can seed the random number generator (RNG) at startup with an
analogRead() from an unconnected pin, but it's not clear how much
entropy you can expect from this.
You can save the RNG's entropy into the .noinit memory section, this
way it will not be wiped up during the program startup.

I would recommend, however, that you use a normal I/O pin to trigger the
dice, if only for one reason: the time when the user presses the button
(that you read with micros()) is a very good entropy source for
seeding the RNG.

For example, whenever the user presses the button you could:

srandom(random() ^ ((uint32_t) analogRead(0) << 22) ^ micros());

This way you combine the entropy from the button press with the entropy
from the analog pin (if any), with whatever entropy may already by in
the RNG.

Edit: More on entropy gathering.

As you seemingly already know, random() is a pseudo-random number
generator intended to produce a sequence of numbers that look random.
Unless you have some other source of randomness in your program, every
time you restart the Arduino you will get the very same sequence of
numbers. Getting true randomness (also called “entropy”) on an Arduino
is not so easy. Here are some ideas you may want to explore.

Read from an unconnected analog input

This trick seems to be pretty popular. It can even be found in the
Arduino documentation on
randomSeed():

  use randomSeed() to initialize the random number generator with a
  fairly random input, such as analogRead() on an unconnected pin.

In my experience, this seems to be a very poor entropy source. I wrote a
test program that prints out the output of analogRead(0) and it seems
to cycle through the same few values in an almost predictable way.
I estimate this gives around one or two bits of entropy per call. On the
plus side, each call takes just over 100 µs.

Read from an analog noise source

There is a lot of literature on building analog noise sources. Such
sources are used inside crypto-grade random number generators, but the
circuits are likely to be more complex than you would like. There seems,
however, to be a very simple alternative. In a comment to this
post, CharlieHanson wrote:

  Connecting the analogue input to the collector of a run-of-the-mill
  transistor, with the emitter grounded and base open helps to make a
  noisy input.

I have not tested this idea, but it is certainly worth exploring.

Time user input

If the user is required to press a button to throw the dice, the timing
of the button press is probably the best entropy source you can have.
With a 8 MHz clock, the micros() function has a resolution of
8 µs (64 clock cycles). Assuming the user is unable to control his
timing better than 0.1 seconds, then you have more than
13 bits of entropy per button press.

If, instead of micros(), you use timer 1 running at the full CPU
speed, then you would have 16 bits of entropy per button press. And
you would not need random() at all, as you could just output
1+TCNT1%6. That would be like throwing a dart at a carnival wheel
spinning at 80 million RPM (8 MHz / 6)!

Measure clock drift

The drift of a clock relative to another clock can be used as an
entropy
source.
The ATmega chip in your Arduino has two independent clocks: the internal
“calibrated” 8 MHz RC oscillator, and the 128 kHz oscillator
used by the watchdog timer. Both are low-accuracy clocks subject to
somewhat unpredictable drift, which is a good thing for this
application. You can gather entropy from this by configuring the
watchdog timer as a periodic interrupt source, and using timer 1 at full
speed to time the interrupt arrival times:

#include <avr/wdt.h>
#include <util/atomic.h>

// Configure Timer 1 for counting CPU cycles and the watchdog as an
// interrupt source firing (roughly) once a second. Call once in
// setup().
void configure_timers()
{
    // Timer 1.
    TCCR1A = 0;          // normal counting mode
    TCCR1B = _BV(CS10);  // prescaler = 1

    // Watchdog. This is a timed sequence.
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        WDTCSR = _BV(WDCE)  // enable changing the prescaler
               | _BV(WDE);  // ditto
        WDTCSR = _BV(WDIF)  // clear interrupt flag
               | _BV(WDIE)  // enable interrupts
               | WDTO_1S;   // timeout ~ 1 second
    }
}

volatile uint16_t wdt_time;
volatile bool wdt_fired;

// Watchdog interrupt service routine.
ISR(WDT_vect)
{
    wdt_time = TCNT1;
    wdt_fired = true;
}

// Add entropy to the RNG from the timing of the last WDT interrupt.
// Call periodically in loop().
void get_wdt_entropy()
{
    if (!wdt_fired) return;  // No WDT event since last time.
    uint16_t wdt_time_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        wdt_time_copy = wdt_time;
        wdt_fired = false;
    }
    srandom(random() ^ wdt_time_copy);
}

I have tested this idea by plotting the time differences between
successive interrupts. On an Arduino Uno clocked at 16 MHz, I see
short-time fluctuations with an amplitude of about 300. That should
provide around 8 bits of entropy per second.

Save the entropy pool across reboots

Once you have spent some effort to gather entropy from the environment,
it would be a pity to lose it all at power down. It is common practice
to save the entropy pool to disk when a computer shuts down, and restore
it at boot time. This avoids the problem of the RNG always starting in
the same predictable state. On the Arduino, you have no disk, but you
can use the EEPROM instead. The problem is you cannot know in advance
when the user is going to switch the device off. Then, ideally, you
would save the entropy every time the user requests a new dice value.
The new problem is that the EEPROM is only guaranteed to work reliably
for 100,000 write/erase cycles. This may not be a serious problem
(100,000 is plenty of throws), but it can nonetheless be mitigated by
using a wear-leveling scheme, where you distribute the writes across the
whole EEPROM instead of always overwriting the same bytes.

Wear-leveling can add significant complexity to your program, but it
turns out there is, in this particular case, a wear-leveling scheme that
is trivial to implement: just write at a random location! At startup,
you do not know what was the last location written to, but you do not
need to: you read and mix the whole contents of the EEPROM:

#include <avr/eeprom.h>

// Save the entropy to EEPROM. Call this every time the user requests a
// new value.
void save_entropy()
{
    uint32_t *address = (uint32_t *)(random() & E2END & ~3);
    eeprom_write_dword(address, random());
}

// Restore the entropy from the EEPROM. Call once in setup().
void restore_entropy()
{
    uint32_t seed = 0;
    for (uint32_t *address = 0; address < (uint32_t *) E2END; address++)
        seed ^= eeprom_read_dword(address);
    srandom(seed);
}

Combine the entropy sources with the XOR operator

As you probably already noticed, the bitwise xor operator (^) is used
every time one wants to combine entropy sources. The main reason is
that, if a and b are independent random variables, then a^b is at
least as random as the most random of a and b. Which means that
XORing a “good” random variable with a “bad” one is harmless. This is
somewhat formalized as the piling-up
lemma.

As an example, doing randomSeed(analogRead(0)) at program startup is
fine, but doing it repeatedly during program execution is a terrible
idea: most of the time this will put the RNG in one of a very few
states. If instead you

srandom(random() ^ analogRead(0));

then you are combining the current randomness of the RNG with the output
of analogRead(), and putting this back into the RNG. And this is
harmless even if analogRead() is quite predictable.

A side note on randomSeed(): Arduino releases prior to 1.6.5 had a
bug that would truncate to 16 bits the entropy provided with
randomSeed(). On those releases it is better to use the avr-libc
srandom()
function.
The bug has since been
fixed.


How to sample incoming 600khz pin and divide it by 4 and generate low frequency signal at output pin of arduino

This is probably too fast to have have software involved in the loop.
You should try to use a hardware-only solution. Note the Arduino timers
should be usable as hardware frequency dividers:

configure a timer to be clocked off the input signal, so that it
behaves like a counter.
configure it for delivering a PWM output with a period of 4 timer
clock cycles and a duty cycle of 50%.

You may try this, but beware I have not tested it:

void setup()
{
    // Configure Timer 5 as a frequency divider:
    //   input: digital pin 47 = PL2 = T5
    //   ouput: digital pin 46 = PL3 = OC5A
    DDRL  |= _BV(PL3);    // set pin PL3 as output
    TCCR5A = 0;           // undo the Arduino core's configuration
    TCCR5B = 0;
    ICR5   = 4 - 1;       // period = 4 timer clock cycles
    OCR5A  = 2 - 1;       // output HIGH for 2 timer clock cycles
    TCCR5A = _BV(COM5A1)  // non-inverting PWM on pin OC5A
           | _BV(WGM51);  // mode 14: fast PWM, TOP = ICR5
    TCCR5B = _BV(WGM52)
           | _BV(WGM53)
           | _BV(CS50)    // clock on rising edges of T5
           | _BV(CS51)
           | _BV(CS52);
}

void loop(){}


Using the Broadcom AFBR-S50 with Arduino

I recently looked into this again, and it turns out that Broadcom had released a porting guide for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.
I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.
P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.


What is the maximum power consumption of the Arduino Nano 3.0?

Well, it depends on what you have attached to the Arduino. If you are using the pins to do things you will definitely require more current.

If you ONLY want to power the Arduino, then I calculated what I think it should be below. (You should also check with someone who owns this device for an experimental value, and not just a calculated value. )

Based on the datasheet (fig 30-8, p 319), I would say the the processor will draw around 2.4 mA at 5 volts.
http://www.atmel.com/images/doc2545.pdf

The USB chip draws around 15 mA depending on several things (p 18)
http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf

Then you have 2 LEDs with 680 ohm resistors. (Assuming 2 volt drop for each led)
(5-2)/680  = around 4 mA per led.

So depending on how much you use the serial port, and the LEDs I would guess around (2.4 + 15 + 4*4) = 33.4 mA

33.4 mA * 5V  = 0.167 Watts

I suspect you want to know to the total amount of power the Arduino can source, which is a bit harder to calculate.

The pins can provide up to 200 mA. (p 303 http://www.atmel.com/images/doc2545.pdf)
So 33.4 + 200 = 233.4

I would also add a 20% safety margin (around 50 mA)
So I would want a 280 mA supply, if I was going to attach the Arduino to different things.

280 mA * 5 = 1.4 Watts

Let me know if my numbers are way off.

P.S.: Be careful making your own supply. It is critical that the voltage be very stable. An unstable supply can/will destroy an Ardiuno. I suggest using a linear regulator, like the LM7805. or maybe the LM317


You really need to know the current being drawn rather than the instantaneous voltage. A voltage drop profile of a battery changes depending on the current draw, and just using the voltage is very very hard indeed.

You could measure the voltage over time, and try and calculate the slope of the voltage and attempt to predict when it would reach a specific pre-determined cut-off point, but since that change in voltage will be non-linear it's not really something that can easily be calculated.

But, if you can measure the current instead, and you know the Ah of the battery, then you can get a better estimate of how long the battery will run until it's considered flat.


The examples I can see from Adafruit say

#include "DHT.h"

or

#include <DHT.h>

But you wrote

#include <dht.h>

They aren't the same.

Further, the examples for the Adafruit library show usage like:

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

But you call DHT.temperature and DHT.humidity.

If you are meaning to use the Adafruit library, you have to write your code according to their documentation.

Also of note, you have defined the type of the object as dht and the name as DHT, but for Adafruit, the type is DHT.

EDIT:

The example on the website you note has a downloadable zip file for the DHT library they use. You cannot assume that all libraries for interfacing a certain sensor will all have the same programming interface.


Getting an error while uploading a code to the Arduino when ethernet shield is attached

I fixed the problem by cleaning the soldering near the SD card slot on ISCP, see image below.


Is it possible to setup a system based on Arduino Due running QNX?

Since Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU and QNX® Neutrino® RTOS supports that processor, I was wondering if it is possible make them work together.

Does QNX really support ARM Cortex-M3? I believe that is not possible as the processor does not have the necessary hardware support.

Please see the BSP list.

Cheers!


Can I use an Arduino Uno-style Shield with the Arduino Mega, Tre, or Zero? How about the Intel Edison?

Zero, Mega and Tre all have the same basic pinout layout as Uno, which provides at least physical compatibility for the pins. Sparkfun has a breakout board for the Intel Edison.

Mini, Micro & Nano obviously have a different pin layout. I would consider them mainly for projects that have challenging space requirements, since their main advantage is their small size. The Micro should be the easiest to plug'n'play (native USB COM serial). Nano is still stuck with FTDI drivers, so it's going to require separate drivers from the Uno/Mega family. And finally Mini doesn't have USB at all.

Maybe take a look at Wikipedia list of Arduino boards and compatible systems to evaluate better what suits your needs best.


Problems with serial communication from Arduino to Bluetooth HC-05

If you use software serial for Bluetooth, you need to set the baud rate and the default baud rate of HC-05 is 38400.

You can change this baud to the desired with AT command.


How do we connect 2 FSR sensors to an Arduino Mega?

Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.

You can use several copies of  the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).

To connect up multiple 5V and ground connections, you can:

•  use almost any popular shield
•  use breadboards like those illustrated above
•  cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
•  connect to the extra 5V and Gnd pins on Uno or Mega boards.  (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)

The diagrams above right show the location of the 5V pins on the programming headers found on the Uno.  Most Arduino boards have at least one AVRISP header like that.


SD.begin() causes SD card to pull 20mA in idle mode. Seem high?

You should look here and see if it helps. Basically:

Ensure that SD.begin() returns true because the card won't sleep if not properly initialized.
I don't know if it's been fixed but the SD library may still have a bug that prevents it from letting SD cards sleep. So try the SdFat library instead.
Try another SD card, from a reliable source.
Connect external pullups or use the Arduino's internal pull-ups with the MOSI, SCK and SS pins so they don't float.


The answer thanks to Trevor_G was:

use digitalWrite(4, HIGH); before pinMode(4, OUTPUT);


Performance tuning PORTB manipulation - mask

4 cycles:

IN Rd,PORTB
CBR Rd,7
ORI Rd,x
OUT PORTB,Rd

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.


FYI, these ISD chips sample audio and store a variable charge on a single flash like cell. They do not convert a sample to a numerical value. There is no data to be read from the chips nor (AFAIK) is there an opportunity to write data to play back to the chips. AFAIK, for us common people, each ISD chip needs to have its recording entered individually. Think of it like duplicating cassette tapes. Think about this when considering how to go about building your project.


It is a version of Pro Mini.
here in DIY MORE shop

The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.

To determine the frequency, look at the resonator (the component next to pin 2).

EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.


Problems with controlling LED with soil moisture sensor

A good way to start debugging this sort of problem is to print out debug statements that say what the hardware should be doing. If the debug statements print out as expected then it's probably hardware, if not, then it's probably your code, e.g.

if (percent < threshold){
  Serial.prinln("LED on.");
  digitalWrite(LED_BUILTIN,HIGH);
}
else {
  Serial.prinln("LED off.");
  digitalWrite(LED_BUILTIN,LOW);
}


How can I create a battery level circuit

Firstly, if I understand your schematic right, you're not "dividing" anything there. If the ringed red symbol is where you are connecting the ADC then either you will see near 4V on there (if it's only connected to the ADC), or 0V (if it's connected to ground).

You should be connecting the ADC between the resistors to get a reading.

Secondly, you should be using a P-channel MOSFET, not a PNP transistor. You can use a PNP transistor, but you will have to subtract the voltage drop imposed by the transistor from your calculations to get any meaningful reading. With a P-channel MOSFET, the on-resistance would be (or should be if you choose a sensible one) negligible compared to the resistance of the voltage divider.

You are right that you can't exceed 1V on the ADC, so you will have to size your resistors accordingly. You aren't restricted to just using a pair of 10K resistors - you can choose any values you like that yield the correct result.

simulate this circuit – Schematic created using CircuitLab

In this example, 10K and 2.2K give you no more than 0.9V from a 5V input. (Tip: choose an input voltage slightly higher than you expect to give a small safety margin).

I calculated those by:

Use the voltage divider formula R2 = R1×(1/((VIN/VOUT)-1)) to calculate the lower resistor (2500Ω).
Choose the next lowest "common" resitor (2200Ω)
Re-calculate the new output using the chosen resistor values using VOUT = (R2/(R1+R2))×VIN (0.9V)


how to read arduino board info serial no programmatically

You can't. The serial number is burned into the ATMega16U2 chip and is only available to the computer over the USB interface.  There is no method for you to get it from the UART interface that connects the two MCUs together.

To stop people copying your code there are two things you need to do:

Don't allow anyone access to the source code or any compiled code files, and
Enable the "code protection" facility of the ATMega328P.

The latter will stop people being able to read the code from the Arduino. It would also be beneficial to remove the bootloader and program the board directly. That way there is no other possible route for getting at your code.

You enable code protection by setting the correct fuse bits.


Program around this while loop not working as expected

Instead of setting i=1, you could use a 'break' command to break out of the while loop.  That way you don't need 'i' at all, you can just do 'while(true)'


If you look at line 762 of 'ArduCam_ESP8266_FileCapture.ino' you should see it is looking to read two bytes from the camera to check that the model number is either a '2641' or '2642'.

You are seeing the error because you are not getting those values back.  So between 761 and 762 insert some debug and print what you are getting back:

Serial.print ("vid = ");
Serial.println (vid);
Serial.print ("pid = ");
Serial.println (pid);

I guess you will either get 00 00 or a different valid (maybe) model number.  If you think its a valid model number add another condition to the if statement and see if it works.

Oh and don't forget to post the results, because I'm going to give it a chance too when I get time :)


How can I update global variable within a loop from outside the loop?

You have multiple problems here. First one:

You have a global variable:

unsigned int frqON;

However in your exec function you're creating a variable of the same name and writing to it. This doesn't change the global variable.

else if (strcmp_P(command, PSTR("ReportFRQ")) == 0) {
       //creates new local variable "frqOn" which overshadows global variable
       int frqON = atoi(strsep(&cmdline, " "));
       Serial.println(frqON);
}

To solve this and change the global variable, simply omit the int decleration.

Also your if check is wrong:

if (frqON = 1) {
        frq=FreqCounter::f_freq;            // read result
       if (frq<1) Serial.println("OFF");
       if (frq>1) Serial.println(frq);
 }

When you do if(frqOn = 1) you set the variable frqOn to 1. You however want to compare the values, i.e. use the comparison operator ==.


From your code:

void isr()
{
  Serial.println(F("Interrupt"));
  mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
}

Do not do serial prints inside an ISR! They will eventually hang it. What you need to do is have a volatile variable (eg. a bool), set that in the ISR, and then check that in loop. If it changes, display it. Eg.

volatile bool cardPresent;

void loop()
{
  if (cardPresent)
    {
    Serial.println(F("Interrupt"));
    mfrc522.PCD_WriteRegister(MFRC522::ComIrqReg, 0x80); //Clear interrupts
    cardPresent = false;
    }

}

void isr()
{
  cardPresent = true;
}

The other thing I would do is put a scope or logic analyzer on the IRQ pin and see if it is actually changing. It should trigger the interrupt if it does.


How do I choose proper diodes for a 74HC595 shift register with a wired OR connection?

For this, almost any diode will work.  Searching, it turns out that the 1N4148 is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

  Maximum rated forward current has to be higher than whatever current a
  single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

  The V_F forward voltage drop has to be as low as possible to make sure
  that a HIGH from the shift register has still a voltage high enough to
  result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

  Switching time has to be low enough to match the shift register's
  frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.


analogRead() returns 0x0000 to 0x03ff

If the max data 0x03ff is shifted to the right by 3 bits (or divide by 8),
then 0x03ff becomes 0x007f, or 127.

I think this will do it:

desiredMax = analogRead(A0) >> 3; // divide 1023 max by 8, becomes 127 max


Why does an RGB LED between VCC and PWM work?

This is a common arrangement and is known as Common Anode, and the I/O pin is said to be sinking current.

To better understand what is happening here it's best to think of an I/O pin as a two-position switch:

When the I/O pin is HIGH point 1 is connected to point 2. When the I/O pin is LOW point 1 is connected to point 3.

So when HIGH the circuit is Vcc -> D1 -> R1 -> Vcc (or the other way around - I have done it that way because of the polarity of the LED), and no current can flow since it has nowhere that isn't at a lower potential than Vcc to flow to.

But when the I/O pin is LOW the circuit is now Vcc -> D1 -> R1 -> GND and so current can flow through it all to ground.  As a result the LED now lights up.

One thing you may have noticed now is that the operation is backwards.  Set the IO pin to LOW to turn the LED ON. That has the effect, as well, that PWM duty cycles are reversed.  analogWrite(ledPin, 0) will be full brightness and analogWrite(ledPin, 255) will be off.


Arduino: pins still active after entering sleep mode

The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).

When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really.  So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.

The solution? Manually turn off the backlight just before you sleep.

digitalWrite(9, LOW);

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.

The same goes for any other external hardware that takes a power supply.

A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.


How do I proceed with a fall detection sensor?

Find the derivative of acceleration over time, also known as jerk. Falling will have a specific jerk pattern, whereas normal shaking and banging will have a completely differrent pattern.


For starters, take a close look at this line:

while (resState == LOW;)

That is not the correct syntax. But the real issue is how is this while loop terminated? The value is never set again?

Cheers!


Linear actuator jitters/vibrates when getting PWM from Arduino Mega 2560 through JKR 21v3 motor controller

I got this working using the Servo library.

You set the input method to PWM.
Connect your RX on the motor controller and hook it up to the servo pin.
Connect the ground of the Arduino to the ground of the JRK 21v3.
Then use the knob servo sample by hooking up a pot to a Arduino.
The calibrate the JRK 21v3 by selecting learn.

Now you can use the actuator as a servo.


You have to find IP address of your Yùn on your local network.
What I do in this case:
- look on the Home router if you can see your Yùn and it's ip, or,
- there is a sketch in Arduino Ide / exemple / bridge / wifi status which can help you to get ip, or
-  open the Arduino Ide software, upload serialTerminal sketch and open serial monitor. It allows you to access the Linux part of the Yùn and type 'ifconfig' to get the IP from the Yùn.


There are huge differences. The most important ones are:

SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).


How to generate Chirp Signal using Arduino

If you're ok with starting with square wave signals, this can be done on an Arduino.
You need to do the following:

Configure a 16-bit Timer to CTC mode
Select the right prescaling
Add a RC low pass filter to the output and voltage divider

Configure a 16-bit Timer to CTC mode

Assuming I'm using Timer 1 and OCR1A:

TCCR1A |= (1<<COM1A0); // Toggle OC1A on match
TCCR1B |= (1<<WGM12); // Clear to Compare mode
TCCR1B |= (1<<CS10); // No prescale

Select the right prescaling

In case you're wondering, prescales are used when the MCU clock is much faster than the output you desire.
Without prescaling, the highest frequency is 16MHz/2 = 8MHz, and the lowest frequency would be 8MHz / 2^16 = 122Hz . Which covers the range of frequencies that we want.

Setting OCR1A value to 80 gives you a frequency of 100kHz
Setting OCR1A value to 2667 gives you a frequency of 2.9996kHz

You can then control the chirp like so:

// Linear rise in wave period
int x = 10;
for (int x=80; x < 2668; ++x){
  OCR1A = x;
  delay(10); // 10ms delay
}

Add a RC low pass filter to the output and voltage divider

Making the perfect sine waves may be too troublesome, so we'll resort to the poor man's sine wave.

Here's the poor man's implementation by TI (still require quite a few parts.)

Personally, I'm cheap so I'd go for the RLC approach. ;-)


There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.

Read Power saving techniques for microprocessors for a considerable number of tips about saving power.

Also see related threads about this question such as What are (or how do I use) the power saving options of the Arduino to extend battery life?


Forget using serialEvent(). It is one of the more stupid things that Arduino implemented.  It is nothing more than a function that gets called (wrapped in a check to Serial.available()) once per iteration of the main loop() function.

It is not really an "event" function at all.

To have anything happen inside your while loop you have to manually implement that thing within your while loop.  Nothing outside of the while loop (with the exception of interrupts) can affect the operation of the while loop.


Is there a good Arduino enclosure for that works with the Olimex MIDI shield

Your best bet is to 3D print the enclosure.

There are many places that will 3D print your enclosure for you and most will mail it to you as well. I would recommend Shapeways as they are fairly reasonable in price and ship worldwide.

If you are a handy DIY person you could use SketchUp or Tinkercad to design your enclosure. Also there are many Arduino enclosures on Thingiverse that you could use as a starting point.

Alternatively there are often places that will design (and then 3D print) the enclosure for you, you just have to supply your hardware. There are often a few places like this in each city.


now() is a function that is specific to Intel Curie based boards.

It returns an unsigned long (which on a 32-bit system is the same as an unsigned int) and so can provide the number of seconds since 1/1/1970 up until the year 2106, at which point it will roll over.

If you plan on having your system run continuously for more than the next 88 years you will have to deal with that rollover correctly, including:

Using subtraction to "wrap around" your calculations
Not trying to calculate any periods longer than 136 years


C++ is not Java. You can't just assign structs like that - it copies them (if anything).

Boid b = boids[I]; // <<<<<<<<<<<<< this line!
b.start_animate_time = 456;

Instead just access the array slice directly:

boids[i].start_animate_time = 456;

And later on as well:

Serial.println(boids[i].start_animate_time);

Basically, you create a "Boid" variable called "b", copy the content of boids[i] to it, set a value in that variable, and then throw it away. Hence the "not used". If you want to reference a specific array slice as a separate variable either get a pointer to it:

Boid *b = &boids[i];
b->start_animate_time = 456;

Or use a reference:

Boid &b = boids[i];
b.start_animate_time = 456;

Of the two I prefer using a pointer, but I come from a C background and understand pointers, but it took me many years of trial and error to get to that point...


You could try the K30 CO2 sensor. There is also a guide using it to make an arduino CO2 detector here.

I've also seen people use the MG-811 module, you can buy them from dfrobot.com . There is also good documentation for how to use the MG-811 with arduino here.


How to continuously monitor range finder and immediately interrupt code to run a different code in pedestrian traffic lights setup?

digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

   digitalWrite(yellow_light, HIGH);
   delay(100);
   digitalWrite(yellow_light, LOW);
   delay(100);

...

You really need to read up on "for" loops. Make a loop that does it 10 times, don't copy and paste 10 times.

As for your other issue, at the very least you could test the proximity sensor after each delay. Read up on millis. Just imagine how you might do it in real life. Would you really delay for two seconds? Or would you check the clock to see if two seconds had elapsed and also check if a pedestrian had arrived?

And better still, replace delay with a loop which tests elapsed time, and also tests the distance sensor.

I'm not writing more specific code because clearly the exercise is for you to learn how to do this. I already know how to do it, and if I just posted the exact answer you wouldn't have learned how to do it.


Problems with inputting into serial monitor

You have hit a bug in the implementation of parseFloat().
This function reads the number you send as an integer, ignoring
the decimal point, and stores it in a long. It then multiplies it by a
scaling factor (a power of 0.1) in order to get the correct value. The
problem is, if you provide too many significant digits, the integer
overflows, and you get garbage. For example "44.64978683" is interpreted
as
(long) 4464978683 * 0.00000001

but (long) 4464978683 overflows and rolls over to 170011387, hence the
result you get.
Simple workaround: do not provide so many significant digits. They are
irrelevant anyway given the resolution of a float.
Edit: I did not find any bug report for this issue, so I submitted my own to the Arduino dev team.
Update: Per request of a maintainer, I submitted a pull
request with a failing unit test revealing this bug. We then worked
on a fix, which has now been merged to master. It should be published on
the next release of ArduinoCore-API.
Note, however, that the AVR core does not yet use the common API
repository. In the meantime, it may be worth submitting a pull request
to ArduinoCore-avr that cherry-picks the fix from ArduinoCore-API.


How do I print multiple variables in a string?

ardprintf is a function that I hacked together which simulates printf over the serial connection. This function (given at the bottom) can be pasted in the beginning of the files where the function is needed. It should not create any conflicts.

It can be called similar to printf. See it in action in this example:

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

void loop()
{
  int l=2;
  char *j = "test";
  long k = 123456789;
  char s = 'g';
  float f = 2.3;

  ardprintf("test %d %l %c %s %f", l, k, s, j, f);

  delay(5000);

}

The output as expected is:

test 2 123456789 g test 2.30

The function prototype is:

int ardprintf(char *, ...);

It returns the number of arguments detected in the function call.

This is the function definition:

#ifndef ARDPRINTF
#define ARDPRINTF
#define ARDBUFFER 16
#include <stdarg.h>
#include <Arduino.h>

int ardprintf(char *str, ...)
{
  int i, count=0, j=0, flag=0;
  char temp[ARDBUFFER+1];
  for(i=0; str[i]!='\0';i++)  if(str[i]=='%')  count++;

  va_list argv;
  va_start(argv, count);
  for(i=0,j=0; str[i]!='\0';i++)
  {
    if(str[i]=='%')
    {
      temp[j] = '\0';
      Serial.print(temp);
      j=0;
      temp[0] = '\0';

      switch(str[++i])
      {
        case 'd': Serial.print(va_arg(argv, int));
                  break;
        case 'l': Serial.print(va_arg(argv, long));
                  break;
        case 'f': Serial.print(va_arg(argv, double));
                  break;
        case 'c': Serial.print((char)va_arg(argv, int));
                  break;
        case 's': Serial.print(va_arg(argv, char *));
                  break;
        default:  ;
      };
    }
    else
    {
      temp[j] = str[i];
      j = (j+1)%ARDBUFFER;
      if(j==0)
      {
        temp[ARDBUFFER] = '\0';
        Serial.print(temp);
        temp[0]='\0';
      }
    }
  };
  Serial.println();
  return count + 1;
}
#undef ARDBUFFER
#endif

**To print the % character, use %%.*

Now, available on Github gists.


How do I code my arduino to return a throttle servo to idle?

If your terminal program uses key-repeat, then let each 't' operate the throttle for just slightly longer than the repeat period (slightly longer than twice the period, if you want to tolerate single dropped characters). After that period without another 't', close the throttle. One implementation would be to (re-)start a countdown timer every time you see a 't', and close the throttle when the timer goes to zero.

No auto-repeat? You'll have to simulate it with your finger (and code for a somewhat longer repeat interval, of course).


Probably because the pump will use more current (mA) than a GPIO pin of the Arduino can deliver.

A GPIO pin on the Arduino can deliver 20 mA, or 40 mA max (but not advised for longer time).

Therefore, a separate power supplyis used, where the base pin of a transistor is connected to a GPIO pin (with a resistor) to 'switch' the transistor on and off.
The transistor base can be very low current (way within a GPIO's current range), which result in a much bigger current from the collector (connected to the power supply) to the emitter (connected to GND). The pump is somewhere between the external power supply and GND).

If you search for 'transistor as a switch' you will find many examples.

You also can use a relay if you don't need to switch it on often. Relay's are typically used for net-powered devices (110+ volts) and/or high current. See also Duncan's comments for additional notes regarding relays.


Updating mysql data using SIM900 and Arduino

I have faced a similar issue. It happened due to an SSL issue. You can find all info about it here - https://stackoverflow.com/questions/62950561/sim800l-gsm-module-working-with-http-and-shows-error-with-https-why


I think it is because of power consumption.
If the LEDs consume lots of power, the LED on Arduino(typically mini red LED) will be off or faded.
So before you connect the  LEDs, check the  mini red LED which is on Arduino and after connection the LEDs, check ones again.
If the red LED is faded or off, the problem must be power consumption.
Connect 12v or 5v to vin to powering the Arduino, and also to LEDs
The important thing is you should not connect LEDs to Arduino 5v.


How do I set the motor state to "HIGH" at the beginning of this sketch?

I would appreciate any insight into this problem, as well as an intuition for the practical use of millis().

I have a lengthy tutorial about this at How to do multiple things at once ... like cook bacon and eggs.

However as this site frowns upon link-only answers (the link might go down) I'll try to explain as well, here.

millis() is like having a wristwatch. You glance at it from time to time to see if it is time to do something, like catch a bus to work, put the dinner on, take the cake out of the oven, that sort of thing.

If you delay() all the time, you can only do one thing at a time. For example, if your cake takes 30 minutes to cook, and you do this:

PutCakeInOven ();
delay (30UL * 60 * 1000);  // delay 30 minutes
TakeCakeOutOfOven ();

This is fine, but you aren't also cooking some eggs at the same time, or doing the dishes, right?

With millis() you can do lots of things! Win-win! The basic technique is to note the time when you started, and then when time is up, you do whatever-it-is you need to do. Like this:

unsigned long BakeStartTime;
const unsigned long CookingTime = 30UL * 60 * 1000;  // 30 minutes
bool CakeInOven = false;

void setup ()
  {
  PutCakeInOven ();
  BakeStartTime = millis ();  // when the cake went into the oven
  CakeInOven = true;
  }

void loop ()
  {
  if (CakeInOven && (millis () - BakeStartTime >= CookingTime))
    {
    TakeCakeOutOfOven ();
    CakeInOven = false;
    }

  // do a whole lot of other stuff, like cooking some eggs

  }

You can expand this technique to do dozens of things "at once".


How to user timer interrupts for times longer than can TNCTx can keep track of?

By maintaining your own second-level prescaler you can quite easily keep track of longer periods.

The most efficient method is to use a "divide and multiply by two" scheme.

Start with a custom pre-scaler of 1.
While the count period is > 65535:

Multiply the pre-scaler by 2.
Divide the count period by 2

uint16_t ps = 1;
uint32_t period = 429864;

while (period > 65535) {
    ps <<= 1;
    period >>= 1;
}

Then you can load the count period register with the now divided count period and use a variable to count the number of times the interrupt has been triggered. When it equals your custom pre-scaler value you reset the count to 0 and run your actual interrupt routine.

The left and right shifts multiply by two and divide by two respectively in a very efficient manner. Far more than multiplying by 10, or dividing the period by 65536 and using that as a prescaler.


String is evil and should be avoided at all costs (http://hacking.majenko.co.uk/the-evils-of-arduino-strings)

The author of u8glib knows that and has refused (quite rightly) to implement them.

You should not use String either.  If you really must for some obscure reason then you will have to pass the internal "C string" reference to the drawStr function instead of the whole String object:

u8g.drawStr(22, 37, name1.c_str());

The only reason people use String is because they are too lazy to learn the proper way of handling textual data in C.


Issue sharing MISO with multiple RC522 RFID Readers

I am joining this conversation VERY late, however maybe my answer can help someone who is just now looking into this.
I was able to get SEVEN RC522 readers working on one Arduino! My solution was very similar to your idea, except instead of the SS pin, I used the MISO pin.

If you look into how the pins work, all of them are outputs going from the master (Arduino) to the slaves (RC522), EXCEPT for the MISO pin which is an input going from the slaves to the master.
So I gave each RC522 scanner it's own MISO pin on the Arduino, and the rest of the pins were shared with all the scanners.
To get it working with the code, the simplest solution I found was to initialize a new RFID using the corresponding MISO pin each time I wanted to read from one of the RC522s.
This worked for the Arduino because you can set several of the digital pins as MISOs, however I haven't figured out how to get this working on a Raspberry Pi yet (without using a multiplexer) because the Pi has a few specific pins that are used for MISO.
I was using the old Sunfounder library. At the bottom of this page (http://wiki.sunfounder.cc/index.php?title=Mifare_RC522_Module_RFID_Reader), if you download the "RFID-RC522_test_experiment" zip file it will have the library included. Just copy and paste the RFID1 folder into your Arduino Library folder. Here is a simple tutorial for that library: https://www.sunfounder.com/learn/RFID_kit_V1_for_Arduino/lesson-29-rfid-entrance-guard-system-rfid-kit-v1-0-for-arduino.html
Here is some example code. It is pretty ugly but it worked.
void checkRFID(int i){
  if(i==0){
    rfid.begin(2,4,5,7,3,6);
  }
  if(i==1){
    rfid.begin(2,4,5,8,3,6);
  }
  if(i==2){
    rfid.begin(2,4,5,9,3,6);
  }
  if(i==3){
    rfid.begin(2,4,5,10,3,6);
  }
  if(i==4){
    rfid.begin(2,4,5,11,3,6);
  }
  if(i==5){
    rfid.begin(2,4,5,12,3,6);
  }
  if(i==6){
    rfid.begin(2,4,5,13,3,6);
  }
  delay(100);
  rfid.init();
  uchar status;
  uchar str[MAX_LEN];
  // Search card, return card types
  status = rfid.request(PICC_REQIDL, str);
  if (status != MI_OK)
  {
    return;
  }
  // Show card type
  rfid.showCardType(str);
  //Prevent conflict, return the 4 bytes Serial number of the card
  status = rfid.anticoll(str);
  if (status == MI_OK)
  {
    memcpy(serNum, str, 5);
    rfid.showCardID(serNum);//show the card ID
    Serial.println();
    Serial.println();
  }
  delay(100);
  rfid.halt(); //command the card into sleep mode
}


What are the unused pins in an Arduino L293D motor shield?

Check out this Link. Here, you can find this explanation in Code. I hope it will helpful for you.

Pin usage with the Motorshield
---------------------------------------
Analog pins: not used at all...
A0 ... A5 are still available...
They all can also be used as digital pins.
Also, I2C (A4 = SDA and A5 = SCL) can be used.
These pins have a breadboard area on the shield.
Digital pins: used: 3,4,5,6,7,8,9,10,11,12
Pin 9 and 10 are only used for the servo motors.
Already in use: 0 (RX) and 1 (TX).
Unused: 2,13
Pin 2 has an soldering hole on the board, easy to connect a wire.
Pin 13 is also connected to the system led.
I2C is possible, but SPI is not possible since those pins are used.


how many processor cycles/time does it minimaly take to transmit 1 Byte via Serial?

No, it is not true.

You are assuming (wrongly) that the CPU is doing the UART communication.  It isn't.

The UART is a completely separate piece of hardware inside the chip.  It runs by itself.  The CPU merely places the byte to transfer into a special function register (SFR).  The UART then takes that and clocks it out through the IO pins at the right rate for the serial communication.  While that is going on the CPU is free to perform other operations.

The CPU can then either consult another SFR to determine if the transmission has finished, or utilize an interrupt that the UART will trigger when the transfer has been completed.


Adruino Yun's Linux environment not working

You might need to re-flash the operating system. Unfortunately it's not a trivial task.

I had to do something similar with a Dragino shield (like a Yun on a shield) that uses the same OS and core chip. Instructions were scarce and hard to follow, plus I run Linux, so there's even less instructions. I worked it out, though, and wrote a tutorial here.

While that is for Linux and the Dragino shield I am sure the basic principles are the same for the Yun - just make sure you get the right image file for your Yun (don't get the Dragino one I link to).

The main thing is to gain access to the boot manager (dr-boot, or whatever the Yun has), which means setting up a wired (ethernet) network and messing with UDP sockets (using nc in Linux - no idea what you can use in Windows).

I'm sure you can find a tutorial for fixing the Yun from Windows (or whatever OS you use) to help you get into the boot manager and upload a new OS image.


Can I safely connect my A6 GPRS module to this 5V 2A phone adapter

The standard output for USB is 5V but there are some such chargers that will output more for enhanced charging output on devices that support it.
In this case the adapter will default to 5V and will only upgrade to 9V if the device requests it.  The GPRS module will not request 9V and so the adapter will continue to provide only 5V which is what you want.


AutoConnect module does not broadcast SSID on ESP32 Dev Board

It looks like your ESP32 is already successfully connecting to an access point as a STA (station) and does not start its own Access Point (AP). You probably have already previously configured an SSID and password and the ESP32 is successfully reusing those, so it will not start the Captive Portal (as its own AP).

You should force AutoConnect to start up the Captive Portal or to forget its pre-programmed SSID and password. This can be achieved by On-demand starting of the Captive Portal like described on this page. According to the documentation you should put the following lines in your code (I have not tested this myself):

Config.autoRise = true;
Config.immediateStart = true;
Portal.config(Config);
....
Portal.begin();

NOTE: The documentation actually states Config.autoRise = false but it seems this does not have the desired effect.


What about a digital potentiometer
Digital Pot

Many types available, generally controlled via a serial interface e.g SPI


How to enable exception handling on the Arduino Due?

First, we must make sure the "-fno-exceptions" compiler flag is overwritten with "-fexceptions". In addition, we must link a separate library that includes the compiler support functions for stack unwinding.
Navigate to C:\Users\<UserName>\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.12 and create a new file platform.local.txt with this content:

compiler.cpp.extra_flags=-fexceptions
linker.elf.extralibs=-lsupc++

recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb {compiler.c.elf.flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group {compiler.combine.flags} {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -lgcc {linker.elf.extralibs}

The last line should match the corresponding line in platform.txt, with an extra {linker.elf.extralibs} at the end (upgrading the toolkit might update that line, so you may need to compare the other parameters).
These lines add the -fexceptions to the compiler command line and the supc++ library to the linker input (otherwise you'll get errors about unresolved externals). After these changes, you can rebuild your project and use exception handling.
Some usage hints
The exception support on the Due requires about 40k of extra flash memory. Given it has 512k, this is usually acceptable. A bit of extra RAM is also used, but that seems to be small enough as well.
Since there are no standard exception classes defined (and the ArduinoSTL library doesn't compile on the due out-of-the-box), you'll have to write your own exception classes, i.e something like this:
class Exception
{
  private:
  const char* _msg;
  public:
  Exception(const char* msg)
  {
    _msg = msg;
  }

  const char* Message() const
  {
    return _msg;
  }
};

Use as:

void ThrowExceptionFunc()
{
  throw Exception("Something bad happened");
}

void ValidateExceptionHandling()
{
  try
  {
    ThrowExceptionFunc();
    Serial.print("Exception was not thrown:");
  }
  catch(Exception& ex)
  {
    Serial.print("Exception happened:");
    Serial.println(ex.Message());
  }
}

Note that Unhandled exceptions will terminate the program. An unhandled exception will cause the due to output a corresponding message to the serial console and then enter a deadend fail state.


Can an Arduino be used to read data from a serial port?

Yes, it can, and the wiring diagram you have drawn works perfectly for me using minicom in Ubuntu.

The majority of serial communication is bi-directional anyway - especially when using it to program a device.

There is absolutely no difference between interfacing the built-in USB->UART adaptor to an external device of your choice and interfacing it with the ATMega328P chip. Just because the ATMega328P chip is on the same board doesn't make it in any way special - it is just a UART interfaced device.

If your setup is not working you can try:

Physically remove the ATMega328P chip to see if that is interfering even when held in reset
Check for software that may be interfering with your communication, such as the notorious ModemManager.


if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }                           //<--
  Serial.print("Distance: ");
  Serial.println(distance);

}

There is a duplicate } after the else clause is closed. Remove it and your code will compile.


ULN2803 and common-anode RGB strip; how am I doing it wrong?

The COM pin on the ULN2803 is for protection when driving inductive loads, which means motors, solenoid.  For an LED, nothing needs connect to COM.

The chip you are using is a low side driver.  That means it connects between the low side of the load (your LED) and ground.  When you drive +5 to the input pin, the transistors will conduct, connecting the output pin to ground.

So for your LED strip make the following connections:

Arduino output pin -> driver input, 1B = pin 1
driver output, 1C = pin 18 -> LED strip R G or B
+12 -> LED strip common power
ground -> GND = pin 9

Without the ground connection on the driver chip, no surprise that odd things happened.  There are diodes designed to protect the input and output pins (see chip data sheet).  Without the ground connection to the driver chip, the input protection diode might have been conducting back to the microcontroller output pin.


Reading HMC5883L hex values in 2's compliment C code

2's complement is the normal signed values in any modern system, including Arduino.

Just place the bytes into a signed variable of the right size in the right positions and there is your value.

In I2C, to read a register, you typically have to make two transactions. The first is a write to set the register number you want to access, the you follow that with a read transaction to get the data.


waiting for a set number of inputs in an array to be reached

If the call to MIDI.read() is a blocking call (it stays in there until it has a value) then you are pretty close:

const int NumberOfInputs (42);
for (int index = 0; index < NumberOfInputs; ++index)
{
    MIDI.read();
}

You can simplify you handler by post incrementing the learnindex counter as you use it.  (Post increment will happen after the value has been 'used')

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
    learn[learnindex++] = pitch;
}

When you increment a variable on its own line its usually better to pre increment it, because you aren't using the value and it might result in quicker execution.  However remember you are increasing the value before using it, so if you use it as above you end up accessing the array element one higher than you intended to!

int learnIndex = 0;
++learnindex;            // Pre-increment it to 1
learn[learnIndex++] = 1; // Set element 1 to 1.
learn[++learnIndex] = 3; // Set element 3 to 3.


Lost AT+ commands on ESP8266 after flashing with "blink" sketch

Thank you Juraj!

I had attempted to update the firmware multiple times and after 6hrs of trying was giving up. I really thought I had trashed my ESP-01. My post here was my last attempt to resolve the issue. I tend to have a problem of not asking for help until I'm frustrated. I saw your comment, and even though I had already attempted to reflash with new firmware I realized that you knew something I did not, and hopefully I could still salvage the ESP-01. So I downloaded documents about the esp8266 and decided to give it another try. What I found is my ignorance had let me believe that the esp-01 was broken when it was functioning as it should. Anytime you upload new firmware it will replace the old (including the at commands, but that's what it suppose to do). I then found this page that brought to my attention the mistake I was making. I was flashing the files to the wrong address, and there are multiple locations where the "blank" file needs to be flashed to.     So all is back to normal. At commands have returned. Now I have to remove them again to upload my program :).

https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now

I almost forgot to mention, I also had to hard wire my GPIO0 pin to ground before flashing. I was originally pulling GPIO0 to ground with a button. However, even though the serial console showed that I had booted in flash mode the flash tool failed. Only after hardwiring the GPIO0 to ground would the flash tool work.