compile error when using two typename in template class

In this class declaration:

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

This line is wrong:

    Map<int, String> *list = new Map<int, String>();

You can't execute procedural code when declaring a class. That has to go into the constructor or some other function.

For example, this compiles without errors:

Test.h

#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test() { list = new Map<int, String>; } ;
    ~Test();
    Map<int, String> *list;
};

#endif


Make a Robotic Arm move straight not curved

It requires doing some geometry.  Think about how you would do that with your arm.  You'd have to move more than one joint at a time.  So you have to define the line you want to follow, and back calculate from each point on the line what the angles of all the joints need to be in order to put the end there.  This will require a bit of trigonometry.  Is that something you've studied before?


Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the
avr-libc and the Arduino libraries. Also avrdude if you want to upload.
The only issue is that the commands used for the build process are quite
long (lots of options). You can see them by enabling verbose compilation
in the IDE. Thus you will probably want some way to automate the whole
thing.

There are several options for this. The most straightforward seems to be
the arduino-builder command-line tool. This is part of the Arduino
project and should ensure maximum compatibility. Otherwise you could use
a plain old Makefile. I personally use Sudar Muthu' Makefile. It can
be installed on a Debian-based Linux distribution by:

sudo apt install arduino-mk

It is not fully compatible with the classic Arduino build process
though: it does automatically include <Arduino.h> into your sketch,
but it does not add forward declarations. Some prefer it this way, as
the automatic inclusion of forward declarations is somewhat buggy and
does not play well with some C++ features.


How can I run two loops simultaneously on an Arduino Uno?

You can make the sensor return data faster by lowering it's accuracy.

tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);      /* fast but low resolution */

You can also modify the library to not power-down the sensor after each reading. Just open TSL2561.cpp, find the getFullLuminosity function, and comment out the line reading disable(); and the 12 lines reading switch (_integration){ ... }

Another solution is, to have the pixels update every 20ms using a timer. You can have the timer, interrupt the main loop every 20ms and update the pixel values.

(I can't really help you with timers, as I myself set the registers for my timers, and ISRs directly, which isn't for beginners. But there are probably libraries for it, to make it more user friendly.)


Arduino LED matrix and 2D array, data seems to be corrupting

Your initial problem can be sorted out by using a longer delay.

void updateScreen(int screen[8][8]) {

  Serial.begin(9600);
  int i;
  ........
      delay(100); //Longer time duration
      blank();
    digitalWrite(i, HIGH);
  }

}

As far as the chess pattern is concerned, it displays correctly for me.

void loop() {

  int display [8][8] = {
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1},
  {1,0,1,0,1,0,1,0},
  {0,1,0,1,0,1,0,1}
  };

  updateScreen(display);
}

Check your array declarations for errors.


How do I start a task and have it run for a set amount of time?

Use millis();

Record millis() in a long variable like below when the solenoid starts
StartTime = millis();

to switch off solenoid after 60 seconds you may do

if ( (millis() - StartTime)/1000 ) >  60
{
   // switch off solenoid
}

enjoy coding.

There are other ways as well to achieve this... but this is being easiest  and you don't have to wait caused by using delay();


Very Basic Arduino Uno Serial.readString() operation

If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".

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

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.substring(0) == "send\r\n"){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();

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

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.indexOf("send") > -1){
      Serial.println("identified");}
    else{
      Serial.println("unknown");
    }
  }
}


You can't magic more pins out of thin air.

Yes you can!

You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)

All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

You can use three (for example CD4094) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.

Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.

This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.

This way you can free most of your Arduino pins including TX and RX.


Arduino IDE does not display examples folder from my custom library

Your library.properties is lacking a line.  Emulating your library with blank files and copying in your library.properties content, and running on Linux from the command line, it reports to me:

Invalid library found in /home/matt/Arduino/libraries/ABC_Node: Missing 'url' from library

So you lack the line:

url=https://whatever.website.you.want.to/point.to

(Or use something like http://example.com if you don't want one...)

I put that line in, and magically the library appears in the list.


The Arduino ADC clock speed is set in ..arduino-1.5.5\hardware\arduino\avr\cores\arduino\wiring.c

Here is the relevant part

#if defined(ADCSRA)
    // Set A/D prescale factor to 128
    // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
    // XXX: this will not work properly for other clock speeds, and
    // this code should use F_CPU to determine the prescale factor.
    sbi(ADCSRA, ADPS2);
    sbi(ADCSRA, ADPS1);
    sbi(ADCSRA, ADPS0);

    // Enable A/D conversions
    sbi(ADCSRA, ADEN);
#endif

For a 16 MHz Arduino the ADC clock is set to 16 MHz/128 = 125 KHz. Each conversion in AVR takes 13 ADC clocks so 125 KHz /13 = 9615 Hz.

That is the maximum possible sampling rate, but the actual sampling rate in your application depends on the interval between successive conversions calls.
Since you read the result and send it through the serial port, you are getting a delay that increases as the baud rate decreases. The lower the baud rate the longer it will take to send the same length of data and the longer it will take to call the next ADC conversion.

The actual sampling rate in your application can be determined with the use of a debugger or a simulator, but an easier solution is to toggle a digital pin every time you execute a conversion and measure the frequency that the digital pin toggles at.


There is no PROGMEM required on ARM. There is no memory bus separation between Flash and RAM, so it doesn't copy constants from flash to RAM which PROGMEM is used to prevent.


Servos require power and PWM. Servo shields come in two main forms:

Simple distribution
Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.

The second kind, more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.

Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.


You can make the ESP8266 behave as a router, see Google for details.  By default it won't do this.

You need to create two separate WIFI networks and then tell the ESP to 'route' traffic between them.

Your ESP needs to form one network (STA mode?).  Your laptop needs to be on one network with the ESP.  The laptop needs to be configured to use the ESP as the gateway and unless your ESP has a DHCP server the laptop needs a static address.

Your ESP also needs to be a client to you router's network, and needs to take an address from the Router's DHCP server.


does EEPROM reset itself when a new code is uploaded?

The esp family chips do not have EEPROM. Instead they just dedicate a small section of flash to pretend to be EEPROM.
That flash section, depending on the core version, is either a dedicated EEPROM partition, or a dedicated key in the nvram partition. Either way it's separate to the wi-fi credentials, which are stored in their own key in the nvram partition.
EEPROM can be erased when you upload code if the partition layout changes. It's less likely to be erased if it's a newer version of the core where it's stored in the nvram.
For safety, don't change the partition size, and ideally use ArduinoOTA which will never change the partitions or erase the nvram.


Error passing a `time_t` and `struct tm`, ESP32

void myIOT32::convEpoch(time_t in_time, struct tm *convTime)
{
  convTime = gmtime(&in_time);

Here you are overwriting the parameter convTime. There is no point in
passing such a parameter if you are not going to use the value provided.

void sendnewNotif()
{
  struct tm *newtime;
  time_t t=182423032;
  iot.convEpoch(t, newtime); // <--- Using the conversion

newtime is initially uninitialized. The call to iot.convEpoch()
doesn't change that (the parameter is passed by value, not by
reference).

  Serial.print(newtime->tm_year);

This is dereferencing an uninitialized pointer, which is undefined
behavior and can crash the program.

The simplest solution I see is to have myIOT32::convEpoch() return the
pointer it got from gmtime(). Note that this points to static storage,
which makes the method not reentrant.

Example (not tested):

struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  // ...
  return convTime;
}

void sendnewNotif()
{
  time_t t = 182423032;
  struct tm *newtime = iot.convEpoch(t);
  Serial.print(newtime->tm_year);
}


Why can this color sensor not recognize green?

Check that you've connected all the Arduino pins correctly to the sensor. In particular, make sure pin 4 on the Arduino is connected to S2 on the sensor.

It's the combination of signals on S2 and S3 which determines which colour is being detected:

S2    S3    Colour
----  ----  ------
Low   Low   Red
Low   High  Blue
High  Low   Clear
High  High  Green

If S2 is always low then you can only detect red and blue.

If the connections are definitely correct, then ensure you haven't made any code modifications which could interfere with it. You may also want to test pin 4 on your Arduino (e.g. using a multimeter) to make sure it's working properly. If necessary, you could use a different pin instead. However, you'll need to modify the #define S2 line in the code to match.


The else case is executed every time the other if and else if conditions are not true. That means if it is not 5 sec and not 30 sec and no button is pressed, the relay is switched off.

To achieve what you want is not that easy, because you have to synchronize button press and button release with the timer actions. First you must specify what you exactly want to do. e.g What happens if you have already pressed the button and release it in the time interval between 30 and 5. Releasing the button would switch off the light but should it stay on because you are within the on-time? This is just an example of what to think about.

I wrote a little code for fun doing the things as I would do it:

#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc( SDA, SCL );
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5;

int timerPhase = -1;
int relayState = LOW;

void setup()
{
 lcd.begin( 20, 4 );
 rtc.begin();

 pinMode( relay_3, OUTPUT );
 pinMode( 8, INPUT_PULLUP );
}

void loop()
{
  t = rtc.getTime( );

  int button_4 = digitalRead( 8 );

  lcd.setCursor( 0, 1 );
  lcd.print( rtc.getTimeStr( ) );

  // this only works if the off time is
  // less than the on time. (OffSec < OnSec)
  timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

  if ( button_4 == HIGH )
  {
    // a button overrides the timer phase
    relayState = HIGH;
  }
  else
  {
    if ( timerPhase == 0 )
    {
      relayState = LOW;
    }
    else
    {
      relayState = HIGH;
    }
  }

  digitalWrite( relay_3, relayState );

  lcd.clear();
}

I could not try the code because I don't know which libraries you used and therefor got compiler errors. So there might be syntax errors in my code but I hope I wrote correct code. It would be nice if you report errors here, if you find one/some ;-).

The line

timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

uses a ternary operator. It means if the condition ( (t.sec > OffSec) && ( t.sec < OnSec ) ) is true, take the first alternative 0 and assign it to the variable timerPhase, if it is false choose the second alternative '1'.


Quadrature Encoder:Interrupts: Reset Count

Is it possible to implement the reset of the main pulse count with a
  second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19,
which is interrupt 4 on the Mega, so you can simply

attachInterrupt(4, reset, RISING);

in setup(), where reset() is a function that resets the counter:

void reset()
{
    count = 0;
}

  I'm thinking there might be a problem here to implement this approach
  as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being
serviced when a second interrupt fires, the second one will just wait
for the first one to finish. This approach works fine as long as you do
not have interrupt handlers that take too long to execute.


The issue you face is that RCSwitch does not seem to support receive mode for ATtiny.

This is what you can find in RCSwitch.h:

// At least for the ATTiny X4/X5, receiving has to be disabled due to
// missing libm depencies (udivmodhi4)
#if defined( __AVR_ATtinyX5__ ) or defined ( __AVR_ATtinyX4__ )
#define RCSwitchDisableReceiving
#endif

Then all methods related to receptions are not defined in RCSwitch class for ATtiny MCUs:

#if not defined( RCSwitchDisableReceiving )
void enableReceive(int interrupt);
void enableReceive();
void disableReceive();
bool available();
void resetAvailable();

unsigned long getReceivedValue();
unsigned int getReceivedBitlength();
unsigned int getReceivedDelay();
unsigned int getReceivedProtocol();
unsigned int* getReceivedRawdata();
#endif

I am really not sure if there is a way to work around it, I have not looked at the code in RCSwitch.cpp.

Maybe you best option would be to find another RC library.

For instance, if you can use Infra-Red RC, then there are libraries out there that could work for ATtiny:

https://github.com/shirriff/Arduino-IRremote


One should appreciate that the Arduino is an Embedded Processor. Specifically that it has limited resources of RAM and ROM(aka Flash/program space).

Often is the case I see coding use the "int" defaultly. Almost sloppily. If that works great.

BUT!!!!
You can run out of room REAL FAST with only 2K of RAM.

I would recommend that you size down your type to the minimum of what it needs to be describing it. One also gets a better understanding of what it really is and its limitations. There is no need for an array of int(16bits) from bytes that were recieved from the SPI, UART or I2C. Or a matrix of RGB's that consume 3 bytes each, being int's. You cut your capacity in half.

The pro/con: PRO: using default int everywhere makes it more inter changeable. The CON is that such interchangeability can lead to unintentional casting errors.

I would also recommend using C99 type def's which can be found at "avr_stdint.html">http://www.nongnu.org/avr-libc/user-manual/group_avr_stdint.html" and elsewhere. It makes things vivid, regards to this aspect. Hence a "int" would be a "int16_t", "unsigned long" be "uint32_t" etc...

It is worth knowing that in some cases a byte or char can not be replaced with int8_t, as such when used with string array functions. But they are still just as vivid.


Volatile.

Essentially any variable declared within global scope (anything you declare before you get to setup()) MUST have the volatile qualifier if you want to use it within an interrupt service routine otherwise it will not be correctly utilised/implemented/instantiated.

As your code stands, you need to add voltatile to all four of your global variables:

volatile int counter = 0;     // if you're stopping at 470, int is all you need
volatile long rpm = 0;
volatile long z = 0;          // this isn't necessary, see below!
volatile long ini_time = 0;
voltaile long end_time = 0;

Your ISR includes some wasteful instructions, which will increase the time it takes for the routine to complete. As @jfpoilpret suggested, you may be constantly interrupting loop(). Cutting the time down may solve this:

Firstly, z = counter; rpm_counter(z); . Pointless, if I'm honest. Why not just call rpm_counter with counter?

Secondly, rpm_counter() function... it doesn't use the arguement you sent! "x" is not used anywhere within the function, so why are you sending it?

Thirdly, even if my second point wasn't valid rpm_counter() doesn't really need to be a function in its own right. Unless you're going to be calling it from lots of different places, just inline the contents of the function to into A_RISE():

else if (counter>470)
{ //470 is ticks per revolution
    end_time = micros() - ini_time;
    rpm = (60*10^6) / end_time;
    counter = 0;
}

That could save a great deal of execute cycles.


Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call?

Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, it is not Ethernet2 library. The new Ethernet library supports W5500 and has client.remoteIP().

example

  if (client.connect(server, 80)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());

  New features in version 2.0.0
  Auto-detection of W5100, W5200, and W5500 Ethernet hardware.


Making your own is quite possible, especially if you own a router (or even better a router table). You need a V shaped 90 degree router bit, a tube of proper perspex glue and some acrylic sheet. The glue is hard to find, but plastic sign manufacturers generally will sell it. Unless you are a DIY expert, I suggest the gap filling type of glue rather than the watery product that only fills perfectly matched surfaces. Try searching Youtube on "acrylic box making". There are several videos. My first two efforts were pretty bad, but the last couple are fine, and are of course exactly the right size.


8 bit arduinos: What happens to the data in registers during a function call? During an interupt?

The compiler is capable of analyzing which registers are used by the function or ISR, so it generates prologue and epilogue code that saves the registers on the stack on entry and restores them on exit.


Arduino and ESP8266 communication over wifi

On the Uno with Ethernet shield you start an EthernetServer on port 23 or 2323. See ChatServer example.

On esp8266 you create a WiFiClient, connect it to IP address of the EthernetShield and port 23 (or 2323). Everything you print to WiFiClient will be send to EthernetServer's EthernetClient.

You can test the server with Telnet client.


Toggle Button For LED Strip not executing properly

If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:

There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:

There are other possible techniques as discussed on this page.

One is to change:

   pinMode(inPin, INPUT);//this time we will set the pin as INPUT

to:

   pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT

Then wire the switch to ground, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.


Measuring time between two photoresistors and printing time on lcd

The most accurate approach is via In out capture on your timer.

Alternatively you can use an interrupt to start and stop the timer.

The worst approach is to poll

However, phtoresistors are slow and generally inconsistent. This can lead to errors in reading. S phototransistor or diode works better.

Edit: it is crazy to try to read the signal in analog. Instead design the circuitry so that it breaches the digital low or high thresholds so you can use digitalRead instead.

You can simply use millis or micros to time stamp the events and calculate the difference.

If you want more precise timing measurements, Google ticks implementation.

edit 2:

here is what I tried:

if (dtime_running==0) {             //event 1 has not arrived
    if (EVENT_ON(EVENT1_PIN)) {     //event 1 has arrived
        dtime = time_now();         //time stamp the event
        dtime_available = 0;        //data not yet available
        dtime_running = 1;          //time measurement running
    }
} else {                            //event 1 has arrived and now wait for event 2
    if (EVENT_ON(EVENT2_PIN)) {     //and event 2 has arrived
        dtime = time_now() - dtime; //calculate the timing difference
        dtime_available = 1;        //data now available
        dtime_running = 0;          //stop taking measurement
    }
}

On two pulses that are 500ms apart, here is the measurement:

Notice that in the box on the upper right, dtime has a value of 500, just as we expected.

the risk with this approach is that if the loop has other tasks, jitters to the measurement will show up. but for slow events, or long time measurements, it may not matter that much.


Unable to receive and print SMS on the serial monitor with Arduino Uno and SIM900A

The Arduino UNO that you are using only supports one Serial connection (over the TX and RX pins). Since you are using these pins to talk to the device, you cannot also send data over Serial.

Read this article to see more about Serial and how it works on different boards.


Unable to set LCD contrast using DAC pin on ESP32

The DAC in the ESP32 is ok for sourcing current but not so good at sinking current, and that is what you need.

A amplifier set up as a voltage follower would work.


Erroneous sensor reading while connecting extra load

If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.

It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.

To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.

Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.

To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.

A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.


ok guys - found the answer: this post here at electronics-stackexchange gave the right hint: Watch-Dog Timer. And my gut feeling was right as well - i simply use a NPN-Mosfet that is being triggered by an Arduino-PIN (which easily can be done while sleeping as well as sleeping means waking up every 8seconds anyway) that connects the capacitor to ground and therefore discharges the guy. Awesome.
This solution can be used as a real fallback in case of whatever happens, while operating the system with built in watchdog-functions while everything is ok.


How Do I Send An Email WITHOUT An Ethernet or WiFi Shield

If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.

You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.

Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.


No, your Mac doesn't have I2C support. It was pointed out in the comments that there might be some legacy port, but it won't be usable due to driver limitations.

You're getting a few things confused. USB is it's own technology, separate from I2C/UART/SPI. I'm not sure how you would even wire I2C to your Mac. The serial monitor in Arduino is for USB COM ports, not related to I2C.

As far as debugging, there's a few options. First of all, there are a few ways to debug I2C using an oscilloscope. If that's too expensive, you could also get away with a logic analyzer. The one I just linked was at Sparkfun for $150. If that's still too expensive and you're willing to risk $30, you can find cheap ones on eBay (most with little/no documenation).

I don't know your code, so I can't advise you on how to fix it. If you need to debug at such a low level, extra hardware is needed.

It doesn't seem like a maximum of 255 that odd, since that's the maximum number that you can do with one byte. You might have to split data up into multiple bytes with some sort of delimiter character. With some quick mental math, it seems as two bytes can give you numbers up to 65,535 if you combine both bytes (i.e. 10101010 + 01010101 = 1010101001010101).

Edit: this seems like the Arduino code you want:

#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int num1 = 0;
int num2 = 0;
int state = 0;
boolean secondByte = false;

void setup() {
    pinMode(13, OUTPUT);
    Serial.begin(9600);         // start serial for output
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);

    // define callbacks for i2c communication
    Wire.onReceive(receiveData);
    Wire.onRequest(sendData);

    Serial.println("Ready!");
}

void loop() {
    delay(100);
}

// callback for received data
void receiveData(int byteCount){
    while(Wire.available()) {
        if(secondByte) {
            num2 = Wire.read();
            number = (num1 << 8) + num2;

            Serial.print("data received: ");
            Serial.println(number);

            if (number == 1){
                if (state == 0){
                    digitalWrite(13, HIGH); // set the LED on
                    state = 1;
                }
                else{
                    digitalWrite(13, LOW); // set the LED off
                    state = 0;
                }
             }
         } else {
             num1 = Wire.read();
         }
         secondByte != secondByte;
    }
}

// callback for sending data
void sendData(){
    Wire.write(num1);
    Wire.write(num2);
}

The Python code will have to do the similar thing. Note: the first part of the number (reading left to right) will be sent first.


Arduino UNO two SoftwareSerial ports communication

This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

UPDATE - Here is the most reliable configuration:

Your code will have something like this:

#include <AltSoftSerial.h>
AltSoftSerial BT; // 8 is RX, 9 is TX

#define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

void setup()
{
  WIFI.begin( 115200 );
  BT.begin( 9600 );
}

void loop()
{
  if (BT.available) {
    char c = BT.read();
    // do something with the character
       ... save them until '\n' arrives?
         ... then parse some values?

    if (values all received) {
      Serial.print( F("Sending values") ); // this is the WIFI port, but
          //  the ESP8266 ignores this debug print because it doesn't
          //  start with "AT".

      WIFI.println( F("AT+ ...") ); // all the AT commands
          ...
      WIFI.print( btValue1 );    // and the BT values
          ...
    }
  }
}


Define a string with single quotation marks?

No, you cannot. This rules comes from the basic C++ syntax on which the Arduino platform is built.


Possible to "inline" PROGMEM strings into a structure array initialization?

If the strings are similar size you can, like this:

const int NUMBER_OF_ELEMENTS = 10;

typedef struct {
   char description [12];
} descriptionType;

const descriptionType descriptions [NUMBER_OF_ELEMENTS] PROGMEM = {
 { "Furnace on" },
 { "Furnace off" },
 { "Set clock" },
 { "Pump on" },
 { "Pump off" },
 { "Password:" },
 { "Accepted" },
 { "Rejected" },
 { "Fault" },
 { "Service rqd" },
 };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    // make a copy of the current one
    descriptionType oneItem;
    memcpy_P (&oneItem, &descriptions [i], sizeof oneItem);

    Serial.println (oneItem.description);
    }   // end of for loop

  }  // end of setup

void loop () { }

This is a bit wasteful of program memory, because you need to allow for the largest string (your example had them all similar sizes) but what you save is not needing a two-byte pointer for each string, so if they are all similar lengths, it will take about the same memory.

See my page about PROGMEM.


NodeMCU v1.0 high power consumption in deepsleep

Consider the TI TPL5110 timer chip with power control MOSFET. Set the timer period with a resistor then the TPL5110 powers on the NodeMCU periodically. Deep sleep is not used. RTC RAM will be lost so use SPIFFS for persistent data.

Adafruit has a breakout board. Take a look in Adafruit's forum for user comments because it has a few limitations.


How to make two WIR 1186 RF transceivers communicate over serial communication?

If you use pin 2 and 3 for serial communication you have to use SoftSerial, because Serial is hardwired to pin 0 and 1.


How to connect Arduino to headphone jack?

This project connects the headphones directly to a digital pin.  Here is the schematic:

I would, however, be more cautious and add a limiting resistor.  The output of an Arduino pin should be limited to 20mA as stated here. So, using

  V=I*R

  5 = 0.02 * R

  R = 5 / 0.02

  R = 250ohms

So I would add a ~250ohm resistor in series with the head phone.  Especially if I were debugging my code.  That is, in case I accidentally left the output pin high for an extended period of time.

The head phones should have some DC resistance.  If the sound is not loud enough you might measure that DC resistance of the head phones and subtract it from the 250 ohm resistance calculated above and use a limiting resistor of that value instead.


RGB LED strip green LEDs cannot be dimmed to less than 50%

analogWrite only works on pins that support PWM. Those are the pins with the ~ next to it.

On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.


Genuino 101 - Can't upload my sketch - Timeout Error

Is the Genuino 101 board been recognized by the OS? Sounds like your board is not being recognized by the system.

For windows, open up your device manager before plugging into the PC. After plugging in, the device manager should refresh and display the board in the COM Port section.

For Linux (in your case Ubuntu), you can use the dmesg | tail cmd to check whether your board is being detected when you plug in the Genuino 101 board.


Can I power an NodeMCU trough VIN providing 5v

Can I use the micro usb's 5v to power the board through the VIN or do any solution require more equipment than that ?

Yes. That is the pin's purpose.  You can use any voltage from about 4.5V up to 20V, although higher voltages will cause more heat from the on-board 3.3V regulator.

VIN just connects to the 5V of the USB.


Pressing button stops listening on nrf24l01

@Gerber remarked:

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

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


Adafruit Motor Shield steppers not turning

The missing line was afms.begin(); which starts communication with the adafruit motor shield.


Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.


Connecting BMP280 sensor to microcontroller

The capacitors are just decoupling capacitors. The value is not that critical. 100nF are good values to use.  On the breakout they have used just one pair of decoupling capacitors but use that pair for both power pins. The datasheet has one decoupling capacitor for each pin. You can do it either way. Personally I'd do it the datasheet way, but for a small board it really doesn't make much difference.
The resistors are a different matter. The BMP280 can work in a number of communication modes, and which mode you have it in dictates what resistors are needed.
R1 is used to place it into I2C mode. R4 is used to set the I2C address. R2 and R3 are the pullup resistors on the I2C bus. They aren't really part of the BMP280 circuit, but part of any I2C circuit in general.
R1 and R4 could be replaced by direct connections to VCC and GND respectively, but by having resistors gives you the ability to override them and use SPI instead of I2C should you wish it.


What Ohm Termination Resistor is needed for this schema ? What, Where and How?

For low data speeds, like 9600bps, termination is usually not necessary.


I have solved the issue by selecting,
Tools > Processor > ATMega (Old bootloader)
@Juraj, Thank you for suggestion.


Disclaimer: I do not have access to one of these devices to test this on.
Section 3.4.1 of LinkIt's developer's guide (which you linked to) seems to indicate that it is necessary to install COM port drivers on OS X before you can communicate with the board. The [txd] report is communication from your computer to the board, so it seems like you are never establishing a connection. The suggestions in the developer's guide are as follows:

If you are using a LinkIt ONE development board on Mac OS X 10.10, then a USB driver is required to enable connectivity with and firmware updates on the LinkIt ONE development board. The OS X 10.10 built-in generic CDC ACM USB driver is not compatible with three ports available on the LinkIt ONE development board. The steps to install a custom driver to enable the BROM port for Firmware Updater are as follows:

Extract the content of the zip file available in LinkIt ONE SDK software’s Driver folder (see 2.3.2, “Installing LinkIt ONE SDK”) named MacOS_USB_COM_Driver_BM_xxx.xx.x.zip.

Run the installation package (BMCDCACM_Driver_v115.05.0.mpkg) and click Next to install it.

Wait until driver installation has finished, then restart your Mac.

BROM USB driver installation is now complete and you have access to the MTK USB Serial ports.


For an array of size 7, the indexes start from 0 (ND_MAC[0]) and end at 6 (ND_MAC[6]) as @MikaelPatel commented.

So the solution to your issue would be changing the condition in for loop to

for(i=0;i<7;i++) //Changed 8 in your code to 7

Here, the loop iterates from i = 0 to 1 < 7 (i.e., till 6)
and it should work. :)


Does porting code to different MCU clock frequency affect serial baud rate?

Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both fosc (aka FCPU) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.


Instantiate class in the constructor rather in the top end?

There's numerous ways of doing this. The best is probably to have a DHT object as a class property and set it up with an initializer list:
#include "DHT.h"

class DhtLib {
    private:
        DHT dht;

    public:
        DhtLib(int dhtPin) : dht(dhtPin, DHT22) {}
        void begin();
        void doSomeStuff();
};

void DhtLib::begin() {
    dht.begin();
}

void DhtLib::doSomeStuff() {
    float temp = dht.readTemperature();
}

DhtLib thing(7);

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

void loop() {
    thing.doSomeStuff();
}


Is it safe to use the same power source for Arduino and its Motor shield?

In my case, when I was running my DC motors at full load, I noticed a large voltage drop in the circuit. This could affect the signals or transmission of data on the Arduino.

It is definitely recommended to power the arduino and motor shield with separate power source. Make sure the the share a common GND.


Digispark Micro (ATTINY85) not working on Macbook Pro 2016

Digisparks are known to have problems with USB3 ports (which your USB-C adaptor probably provides). Try using a cheap USB2 hub between the DigiSpark and the adaptor.

It's always a good idea to use a cheap USB hub between whatever experimental device you want to connect and your machine, so that if you wire something up incorrectly you don't end up frying an expensive laptop. This is particularly true for a device such as the digispark which does not have a real USB interface but really bit-bangs the protocol out of ordinary I/O pins.

There is no guarantee that the hub will protect you from all wiring mistakes, but it's an added level of protection.


When choosing wire for your project the main consideration is the amount of current. Second would be the distance.

For LEDs the current is generally low (milliamps) so something like a 20 or 22 gauge wire would be fine. You should be able to get it at a local hobby electronics shop or Amazon of course.

FYI, Wire gauge numbering is such that the lower the number the thicker wire. Thus 20 is thicker than 22.

You may find this AWG (American Wire Gauge) table helpful: http://www.powerstream.com/Wire_Size.htm


You can try decoupling the power for the bluetooth:

The resistor value should be tiny - 10Ω is a good value to use - don't go much higher than that.  The capacitor should be nice and big - I have shown 100µF, but bigger is better - whatever you have that's nice and big.  (Make sure you wire it the right way round - check which pin is marked as -)  You might also want to add a small capacitor (say 100nF) in parallel with the large one.


Run Code Based on Time From GSM Module (SIM900)

I'm imagining SIM900 is a serial stream that supports input methods available() and read().  The hour portion of the response string is a two-digit integer delimited by a comma and a colon.  The following snippets of code assume you trigger a response and then start a listen() to connect to the software serial input.  Since listen() discards old data, presumably a message like +CCLK: "17/02/14,16:58:25-20" will be the next data to arrive.

This code converts any string of digits that it sees into a number.  Whenever it sees a non-digit character, it treats it as a delimiter.

When the previous and current delimiters are ',' and ':', it checks if the current number value is in the desired time range, and if so, it sets a flag, else clears a flag.

When the previous and current delimiters are '-' and '"', it assumes it is done with the parse.  Or one could, possibly, end the parse as soon as the hour field has been processed.

void loop() {
  // ...
  // somewhere within loop()
  byte num, dell;       // Currrent number and left delimiter
  byte timeFlag, readMore, foundTime;
  //...

  // Send string to elicit +CCLK and tell parser to handle response
  SIM900.listen();      // Discard old input
  SIM900.write("AT+CCLK?"); // Elicit new input
  readMore = true;
  timeFlag = foundTime = false;
  num = 0;
  dell = 0;
  // Read and parse +CCLK input; set or clear timeFlag
  while (readMore) {
    while (!SIM900.available()) {}; // Wait for a character
    char c = SIM900.read();
    if (c >= '0' && c <= '9') { // Is c a digit?
      num = 10*num + c-'0'; // Yes, add it to num
    } else {   // Not a digit, so check for Hour field or End of parse
      if (dell=='-' && c == '"') {
        readMore = false;
      } else
        if (dell==',' && c == ':') {
          timeFlag = (num < 6) || (num >= 18);
          foundTime = true;
        }
      dell = c;            // Record left delimiter of next number
      num = 0;             // Get ready to evaluate next number
    }
  }
  // If foundTime, then timeFlag is true for time in 6 PM to 6 AM, else false
  // ...
  // etc
}


If you have an existing CNC, you may have to abide by its comm protocol.  Otherwise, if the Arduino is part of a CNC you are building, and it is supposed to accept commands from a host computer, the first thing to do is make sure your baud rate is set higher than the default.  I have found 115200 to be a good choice for stability.  Next, you should avoid sending TTY-type text strings, and send binary values instead. You'd send an initial byte or word to specify the command type, followed by the data.  In my open-source DaqPort sketch for high-speed data acquisition https://www.daqarta.com/dw_rraa.htm I use the high nybble of the command to specify the general type, and the low nybble to specify more detail like channel number.  The sketch uses a big loop with if(Serial.available() > 0) to read the first byte, and a switch/case to determine what to do.  The the specific command reads the proper number of bytes and does whatever.  This is way faster than having to parse text and convert to binary.


Some code is shown below to illustrate a method for treating three events independently.
This code might not be completely applicable as-is, because the problem description isn't clear about what should happen when a button is pressed and about whether other events to be added to the code are like the one shown there now.  However, if you understand how it works you probably can adjust it to meet any special requirements of your application.
During each pass through the loop() routine, the code does the following for each type of event:

If the event is not currently active (as denoted by states[i] < debounced), the code checks whether the event's button has been pressed (or, if its sensor has turned on).  If so, the code increments a debounce counter.  If the event's counter gets up to debounced, then the output for the event is turned on, and the event's end-time is stored in an array entry.
If the event is currently active (as denoted by states[i] >= debounced), the code tests if the event's end-time has arrived; if so, it turns off the event's output bit and resets its state to 0.

The last statement in loop() busy-waits until milliseconds() returns a different value than before.  This is done so that switch-debouncing samples are taken at least a millisecond apart.  If your inputs don't need debouncing, you can remove debounce code .
/* Process three asynchronous activities: Upon a given input going
true, activate its associated output(s) for specified lengths of time.
*/

enum { nkinds=3, debounced=5 }; // # of activity kinds;  debounce-criterion
const byte outPins[nkinds] = {2, 4, 6}; // Output pin numbers
const byte inPins[nkinds]  = {3, 5, 7}; // Input pin numbers
const unsigned int actLens[nkinds] = {345, 678, 323}; // Activity lengths, ms
byte states[nkinds] = {0, 0, 0};
unsigned long actEnds[nkinds] = {0, 0, 0};

void setup() {
// Set input/output modes of pins
  for (byte i=0; i<nkinds; ++i) {
    pinMode(outPins[i], OUTPUT);
    pinMode(inPins[i], INPUT);
  }
}

// Once per millisecond, for each kind of activity
// check for new beginning or deal with ongoing action
void loop() {
  unsigned long now = millis();
  for (byte i=0; i<nkinds; ++i) {
    if (states[i] < debounced) {  // Is activity off?
      // It's off, look for a turnon
      if (digitalRead(inPins[i])) {
        ++states[i];        // Button is closed at the moment
        // See if button has been debounced
        if (states[i] >= debounced) { // If so, start its action
          digitalWrite(outPins[i], HIGH);
          actEnds[i] = now + actLens[i];
        }
      }
      else {
        states[i] = 0;      // Button is not closed at moment
      }
    }
    else { // It's on, see if end-time has arrived
      if (now >= actEnds[i]) {
        digitalWrite(outPins[i], LOW); // Clear output when done
        states[i] = 0;        // Return to button-seeking state
      }
    }
  }
  while (now == millis()) {};       // Finish current millisecond
}

The code above compiles ok in the Arduino IDE but I haven't tested it on an Arduino device.
Note, larger systems with numerous events will use priority queues to implement lower-overhead versions of the same ideas.


Why does this code show me a lot of space?

From the point of view of what you print, your loop boils down to:

if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.print(celsius);
}
Serial.println("\n");

You are printing two newlines on every loop iteration. One is written
as "\n", the other is the “ln” of Serial.println (“println” means
“print some stuff followed by a new line character sequence”). Instead,
you probably want to print a single newline, and only when there is
actual data being printed:

if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);  // notice the ln in println
}

But since you are doing nothing else in loop(), you could simplify a
bit and avoid having everything inside a big if statement:

if (millis() - startTime < MEASURE_PERIOD)
    return;

startTime += MEASURE_PERIOD;
sensorValue = ...;
celcius = ...;
Serial.print(sensorValue);
Serial.print(",");
Serial.println(celsius);

Edit: Here is a simple test demonstrating this logic. In both the
second and the third case, it generates an output in the requested
format.

const uint32_t MEASURE_PERIOD = 250;

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

void loop()
{
    static uint32_t startTime;
#ifdef SECOND_CASE
    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    }
#else  // third case
    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    int sensorValue = random(695, 699);
    float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius, 3);  // notice the ln in println
#endif
}


I have looked into something very similar and I think the reason you are finding it difficult to find information is you are viewing the full system.  Break it down into smaller chunks and you will get more chance of finding a match.  So lets look at the camera and then the rest of it.

I think that the reason you can't get an answer for this is that you can't do what you want with what you have.  My research seems to say that the OVO7670 camera needs a separate micro processor and 'special' RAM to work (can't remember what is special about the RAM at the moment).  There is a board that does this called a 'PIXY', but its not cheap.

On the plus side, connecting an Arduino to Android via blue tooth should be quite simple there should be lots of examples on how to set up the Arduino side.  You then need to define to convey your messages between your server an client and I know you aren't asking how to turn a LED on and off from an Arduino. (If you are please see the Example Blink).

Hope that helps

EDIT

I think you should have 18 pins on you OV7670.

3v3 - 3.3v
Gnd - Ground
SIOC - Input - I2C Clock
SIOD - I/O - I2C Data
VSYNC - Output - Vertical Synch
HREF - Output - Horizontal Synch
PCLK - Output - Pixel Clock
XCLK - Input - System Clock
D7 - Output - Data bit 7 (MSB)
D6 - Output - Data bit 6
D5 - Output - Data bit 5
D4 - Output - Data bit 4
D3 - Output - Data bit 3
D2 - Output - Data bit 2
D1 - Output - Data bit 1
D0 - Output - Data bit 0 (LSB)
RESET - Input - RESET - Low to reset
PWDN - Input - Power Down - High to activate


Arduino ultrasonic sensor to trigger LED when path is blocked

Based on this
You need at least 10mS delay from each readings to prevent unstable readings.

void loop() {
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance = duration/58.2;

    if (distance >= maximumRange || distance <= minimumRange) {
        Serial.println("Nothing Happens");
        digitalWrite(LEDPin1, LOW);
    } else {
        Serial.println("Trigger");
        digitalWrite(LEDPin1, HIGH);
    }

delay(10);
}


Can removing lines of code destroy a motor driver and make it catch fire?

It all depends on how the circuit works and how it is controlled.  A basic H-bridge looks like this:

Normally you have one MOSFET from each side turned on and one turned off - so for example Q1 and Q4 on to make the motor turn one way, or Q2 and Q3 to make it turn the other. Turning on Q2 and Q4 for example would make the motor "brake".

However, if it is possible for your driver to turn on both Q1 and Q2 at the same time, or Q3 and Q4, then they will form an almost dead short circuit and massive amounts of current will try to flow. At that point things will start to get hot and the Magic Smoke™ will try and escape.


Yes, reading 4 SHT31 is possible with an ESP32.
If you have the analog version, readout is quite trivial: you simply use 8 analog inputs (2 for each) to read the signal.
If you have the digital version, which has an I2C interface, you need to control each sensor's address pin separately to select the specific sensor you want to read. Otherwise, there will be an address collision on the bus.


Read speed between two ultrasonic sensors

There are several issues with these ultrasonic modules and your code:

How fast are these objects moving? If you don't have any reflection, it'll take almost 20ms for one measure. So precision will be low.
What if the object is moving in oposite direction?
What if the object stucked between?

and so on.

Anyway Laser interrupter circuit (or similar) would be much more suitable for this job.

Or if you want to use ultrasonic, you can use Doppler effect. But it's not possible with those PING))) modules (or clones).


You configure serial pins as output, this may be your issue.

also, you're calling some digitalRead() before setup call, you would have to do that in the loop.


Arduino Uno versus Arduino Nano power consumption

A Uno which isn't doing anything useful except being turned on will use about 50 mA of current from the power jack at 9V.

If you use 3 x alkaline AA batteries (giving a nominal voltage of 4.5V) directly into the 5V pin of the Arduino then you might get 2500 mAh which would be 50 hours at 50 mA per hour.

You can save a considerable amount of power by using sleep modes as I describe on my page about power. It also helps to use a bare processor (no voltage regulator, no LEDs).

I made a temperature and humidity sensor which runs from 3 x AA batteries. Using sleep mode, plus various other techniques, that is running for over a year without needing new batteries.

  I would like to know which one will be power efficient?

Both the Uno and the Nano use the same Atmega328P processor. Thus the technical considerations would be the same. Both have a voltage regulator and a "power on" LED which alone would use a lot of current, compared to everything else.

It's not that hard to make a minimal board. I have a page about doing that. Example of all you need:

If you use a deep sleep mode, combined with using the watchdog timer to wake every 8 seconds (and check the time, say every 10 times it wakes) you can reduce power consumption right down.

My temperature sensor uses an average of 42 µA which is a lot less than 50 mA. (A thousand times less). Thus your 50 hours run time becomes 50,000 hours which is 2083 days. Your batteries will probably self-discharge sooner. :)


OSX upload error: avrdude: ser_open(): can't open device "/dev/cu.mydev" : Resource Busy

I think my available serial ports were insufficient or something. I installed the ch34* driver which allowed an additional device showing up. Here's the download: http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Then I selected this port and I finally could upload.


Arduino Nano Atmega328P doesn't work on Macbook

I was be able to solve the issue.

By looking for the serial chip my board has: CH340G I found this blog post:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

So I downloaded the signed driver for my chip and now it works :D

Driver: http://kiguino.moos.io/downloads/CH34x_Install.zip


The reason for signal not going back to LOW

The pin is not configured as OUTPUT.

By default, all of the GPIO pins on pretty much any microcontroller are configured as inputs following reset. This prevents the chip from "fighting" an external device that might be driving any of those pins before the firmware has had a chance to configure the GPIO correctly.

On the MCU used on the Arduino, the output latch controls the state of an internal pullup resistor when the pin is configured as an input. Your code was simply enabling and disabling this resistor. When you set the pin low, it makes the pin open-circuit, and you see a slow decay of voltage through your oscilloscope probe.


If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)

Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is where do those 5V come from. Basically, from 2 possible sources:

USB. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.
Barrel connector (wall adapter). It accepts 7-12V and brings it down to 5V using a linear regulator whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, preference is given to the wall adapter. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.

This is done not only for convenience purposes (so you have more current available), but also for protection. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.

I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.


Is it possible to generate an exact 15 kHz clock pulse using an Arduino?

You can get pretty close if you program Timer 1 directly (not
through the library), and have it run with the prescaler set to 1.
Ideally, you want the period of the timer in clock cycles to be:
F_CPU / 15 kHz = 16,000 kHz / 15 kHz ≈ 1066.67 CPU cycles
If you round this to the nearest integer, you get
F_CPU / 1,067 = 16,000 kHz / 1,067 ≈ 14.9953 kHz
This is about 0.03% too slow, well within the tolerance of the ceramic
resonator clocking the Uno.
Here is my attempt at this. I have tested it.
constexpr float PWM_FREQUENCY = 15e3;  // 15 kHz
constexpr uint16_t PERIOD = round(F_CPU / PWM_FREQUENCY);

void setup() {
    // Configure Timer 1 for 15 kHz PWM on pin 9 = PB1 = OC1A.
    DDRB  |= _BV(PB1);    // set pin as output
    TCCR1B = 0;           // stop timer
    TCCR1A = _BV(COM1A1)  // non-inverting PWN on OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS10);   // clock @ F_CPU
    ICR1   = PERIOD - 1;  // period
    OCR1A  = PERIOD / 4;  // duty cycle
}

void loop(){}


How can I make my custom board use the programmer selected in "Tools->Programmer" when the Upload button is pushed?

Make sure you do not have a protocol listed in the boards.txt file. If the uploader sees protocol is null then it will fall back to using the same code that "Upload using programmer" does.

Relevant code in SerialUploader.java:

    if (usingProgrammer || prefs.get("upload.protocol") == null) {
      return uploadUsingProgrammer(buildPath, className);
    }


Installing MariaMole (Alternative IDE) on Mac

Note: I haven't tried this myself so YMMV; this is just from my general experience and reading; all information comes with citations.

To start, I would recommend opening an issue on GitHub to ask for detailed instructions. I noticed that the website says:

  Linux and Mac distributions are still experimental, but MariaMole is working fine on both systems.

so they should have a known recipe for how to do it.

In the mean time, here's how I would proceed. Given that there's a file called CMakeLists.txt in the root directory, you need to:

download and install CMake

Then, install the dependencies listed on the wiki:

Qt 5.2
QScintilla 2
QSerial

After that, I presume just cloning the repo and running cmake in the root directory should do the trick. If you have any further questions, please open an issue on GitHub with your compilation error message for further assistance.


I'm going to assume your library structure is like this because the structure you described above would not cause that error:

AAA
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the 1.5 library format. Putting all the source files in the src subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:

AAA
|_library.properties
|_src
    |_AAA.h
    |_BBB.h
    |_CCC.h
    |_BBB.cpp
    |_CCC.cpp


Controlling op amps amplification ratio by arduino

The basic principle is easy to implement.  A non-inverting configuration has a resistor Ri from the inverting input to ground, and a feedback resistor Rf from the same input to the output.  The signal is applied to the non-inverting input.  The gain is 1+Rf/Ri.  You can control the gain by changing Ri, which can be done via a CD4016 quad analog switch and 4 resistors.
HOWEVER, the Arduino is a 0-5V device.  The CD4016 can handle 15V, but to switch it the digital input must pass through half the supply.  The op-amps you mention will require bipolar supplies to handle AC signals (which I assume is what you want), so you could run them with +/-7.5V, with the CD4016 powered between them.  Then to get the Arduino 0-5V to toggle the CD4016 you'd need some level-shifting transistors to get it to +/-7.5.  The upshot is that this is surely going to be more trouble than it's worth.
However, if you are willing to drop the ancient op-amps and use a modern single-supply type (MCP6021, LT1013, etc) that runs on 0-5V, you can use input and output capacitors to convert the signal to AC, then just use the CD4016 as-is. Or JFET transistors, or even bipolars to switch the gain resistor under Arduino control if you don't need audiophile quality.


Not sure if this is what you mean, but:

const int FP = 0;  // force probe analog pin
const int OFFSET = 10; // your deadband depending on your sensors consistency too
int init_read = 0;  // initial read
int curr_read = 0;  // this will be constantly updated till zeroing is done

void setup(){
  Serial.begin(9600);
  //the rest of your setup()
}

void loop(){
  if (Serial.available() && (Serial.read() == 'z')){  // if you sent anything with the monitor and if 'z' is present
    init_read = analogRead(FP); // initial read from sensor before 'zeroing' begins
    while (abs(curr_read - init_read) < OFFSET){ // here you indicate the condition that would mean the probe has been zeroed
      // make your adjustments or whatever
      curr_read = analogRead(FP);  // take a new reading and check in the next iteration
    }
    Serial.print("Zeroing is done.");
  }
}

z is the command you send from the serial monitor to begin zeroing.


Arduino WiFi/ESP8266 WiFi Password Changed

The WiFiManager library was written for exactly this purpose.


nRF24L01 6TXA_1RXA network + 6TXB_1RXB network with arduino

You can use the RF24 library that you can install right away from the Arduino IDE. It provides you all you need. Just use two instances of RF24 with different CSN and CE pins assigned to get started.

RF24 radioA(7, 8); // CE, CSN
RF24 radioB(5, 6); // CE, CSN

Use the simple ping sketch as a starting point and add a second radio to it.


The PCM libary won't work on an Arduino Nano

I guess the Nano had a sketch which was setting pin 11 HIGH (using SPI?) as you turned it on with a 4 Ohm speaker attached without any other resistance. It created a short circuit and damaged the pin's circuit.
Using tone() or the PCM library with a speaker connected without additional resistor doesn't damage the pin immediately because it is then HIGH only for very short moments, but it stresses the pin circuit too.
The linked page recommends to use direct speaker connection because it is much louder then with a resistor in series, but this is a wrong advice. It should recommend an amplifier module for example with LM386 IC.
A piezo speaker has higher resistance so it can be connected directly to Arduino pin, but a piezo sounds loud only in high frequencies so with the PCM library the sound is like whispering.


Teensy to Teensy serial communication via USB connector

Note: The Teensy you pictured is an ARM based (NXP MK20DX256) Arduino which is very different from well established legacy Arduinos. There have been (and, maybe, still are) "bugs" in some ARM Arduino code.  So Teensy pins used outside their normal (expected) purpose my or may not work like similar pins on legacy Arduino platforms.

In order for 2 USBs to talk to each other, one needs to be a USB Host and the other a USB Device.  There can be multiple USB Devices so the USB protocol is made more complex to handle this feature.  There can be many types of USB Devices each with their own underlying protocol so the USB protocol is made more complex to handle this additional feature.  A serial port USB Device uses the CDC or Communications Device Class protocol.

So, in order to have two Teensy board to talk to one another using the USB CDC protocol, one of the Teensy boards needs to be turned from a USB Device to a USB Host.  Which is not trivial.  Most developers will turn to the OEM of the processor.  As most processor OEMs offer free software for such purposes to promote the sales of their hardware.


Grbl on Arduino Uno (Elegoo) with DM542 + nema24 stepper motor not working

As you wrote, that you connected the positive pins of ENA, DIR and PUL to 5V, I guess you use the common anode connection scheme from the DM542's datasheet (the driver seems to have optocouplers for the inputs). That would mean the inputs are active low (a Pulse would be a transition from HIGH to LOW and then back to HIGH).

GRBL v1.1 has by default an active high pulse signal:

  By default, a step signal starts at normal-low and goes high upon a step pulse event. After a step pulse time set by $0, the pin resets to low, until the next step pulse event.

(from the GRBL github wiki). I guess, this is the problem. Please try to set GRBL for inverting the pulse signal with $2 (you may well find a corresponding setting inside bCNC.

Be sure, that GRBL is outputting the signals, that your driver is expecting in your connection scheme.


I2C_tx(bitmask |= (1<<RS));
I2C_tx(bitmask &= ~(1<<RW));
I2C_tx(bitmask = data & 0xF0 | 0x08);

RS is overridden in the third line, so the solution is:

I2C_tx(bitmask = data & 0xF0 | 0x08 | (1<<RS));

And delete the first two lines :)


How can I power a NeoPixel ring and strip through Arduino MKR1000?

The on-board regulator of an Arduino can supply a maximum of 500 mA when connected to USB, and up to 1000 mA when connected to an external power supply (see Maximum current from Arduino 5V power pins).

If your components are drawing more current than that, then you will need to use an additional separate power supply for the NeoPixel ring - ensuring that the ground lines of the Arduino's supply and the NeoPixel's supply  are connected.

If the Arduino has been smoking then it may already be damaged. Did you see which part was smoking? If it was a capacitor as shown in Is my Arduino dead?, then this answer may help.


Missing character when introducing delay in the code

If serial data is coming in, and your code is doing a delay, the incoming data is stored in a buffer (of 64 bytes). But if you wait too long, the buffer will fill-up. Once it's full, any further incoming serial data isn't stored, and will be lost.

In your third output example, you get exactly 63 characters. Which is the maximum size a 64-byte cyclic buffer can store.


Using Servo.h it is possible to run a servo from just about any pin.....obviously the more pins the more servos...hence the question " how can I do this with a MCP23017?

The Servo library could be modified to allow toggling of GPIO pins on a MCP23017 but there are some issues with timing.

The library uses Timers and Interrupt Service Routines (ISR) to handle the pulse width. The servo pin is toggled in the ISR.

At 100 KHz (100 Kbps) I2C at least 3 bytes need to be transmitted to the MCP230017 to toggle a pin. That is approx. 300 us and not possible to do from the Servo ISR. Another execution pattern is required.

Cheers!


Firmata: how to set a particular pin to high on boot?

It would seem you are right. If I understood the source correctly,
Firmata initializes all digital pins as OUTPUT LOW. Hard to believe, as
this seems like a silly thing to do... My understanding is that:

setup() calls systemResetCallback() in order to set the initial
pin configuration (line 779)
systemResetCallback() loops over all pins and calls
setPinModeCallback(i, OUTPUT) for every pin i that is not an
analog pin (line 732)
setPinModeCallback() calls pinMode() to set the pin to OUTPUT
(line 325).

If my understanding is correct, then the simplest solution would seem to
patch systemResetCallback() and replace OUTPUT by INPUT on
line 732.


How can you determine the duration of a timer interrupt?

The timer takes its time from the system clock. That may be, typically, 16MHz. We call this F_clk_io for the Frequency of the IO CLocK.

Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.

So first you need to divide the F_clk_io by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.

So say you have selected a 1:4 prescaler.  The timer's frequency is then F_clk_io / 4, or if it's 16MHz you're running at, then the timer's frequency is 16/4 = 4MHz.

So at 4MHz each tick lasts for 1/4000000 = 250ns.

If you want 20ms you need to know how many ticks that would be.

20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.

Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.

Set the prescaler to 1:8 and see what happens...

16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.

That fits.  See how doubling the prescaler has simply halved the number of ticks you get in the same time?

So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.

Except it doesn't.

It gives you 20.0005ms.

Why? Because the interrupt triggers and the counter resets when it reaches the target count, not when it passes the target count.  And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.

So the finished formula is:

ticks = ((F_clk_io ÷ Prescale) × time) - 1

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible.  If it's not, then there are other tricks you can use.  My favourite is a manual pre-scale:

Run the timer at a multiple of your target frequency (10x is easy)
Count the number of times the interrupt triggers
When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count.  Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.


Let's start by getting rid of the templates, as they make things more confusing. In the following, I replaced T with int.

void Fill_With(int target_array, int value){
    int Array_Size = sizeof(target_array) / sizeof(int);
    for(int l = 0; l < Array_Size; ++l){
        target_array[l] = value;
    }
}

Let's try it out! I pasted this into the Arduino IDE and compiled it. Here is the output:

sketch_aug01a/sketch_aug01a.ino: In function 'void Fill_With(int, int)':
sketch_aug01a:4: error: invalid types 'int[int]' for array subscript
         target_array[l] = value;
                       ^
exit status 1
invalid types 'int[int]' for array subscript

This is telling us that we're trying to subscript (that's the term for the [] syntax) a variable of type int with a variable of type int. In C++, a pointer to the start of an array has type int *, not int. Let's fix the type of target_array in the function signature:

void Fill_With(int *target_array, int value){

It compiles, but if you ran it you would quickly run into a bug:

When given an expression, the sizeof operator will return the number of bytes in the type of the expression. The type of the expression target_array is int *, so sizeof(target_array) == sizeof(int *). On 32-bit systems, sizeof(int *) == 32/8 == 4.
When given a type, the sizeof operator returns the number of bytes in the type. So sizeof(int) gives the number of bytes in an int, which is guaranteed to be at least 2 bytes (16 bits), but is usually 4 or 8 (it depends on the system).

Together, this means that Array_Size ends up being some small number like 0 or 1, regardless of the contents of target_array. To fix this, you can instead pass in the length of the array as a parameter:

void Fill_With(int *target_array, int array_size, int value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With(array1, 4, k);

Now you can put the templates back in:

template <class T> void Fill_With(T *target_array, int array_size, T value){
    for(int l = 0; l < array_size; ++l){
        target_array[l] = value;
    }
}

int array1[4] = {1,2,3,4}, k = 0;
Fill_With<int>(array1, 4, k);

By the way, C++ already has this function built in. It's called std::fill. Here's how to use it:

#include <algorithm>

int array1[4] = {1,2,3,4}, k = 0;
std::fill(array1, array1 + 4, k);


As a sort of prologue to this overly long answer...

This question got me deeply captivated with the problem of interrupt
latency, to the point of loosing sleep in counting cycles instead of
sheep. I am writing this response more for sharing my findings
than for just answering the question: most of this material may actually
not be at a level suitable for a proper answer. I hope it will be
useful, however, for readers that land here in search of solutions for
latency problems. The first few sections are expected to be useful to a
wide audience, including the original poster. Then, it gets hairy along
the way.

Clayton Mills already explained in his answer that there is some latency
in responding to interrupts. Here I will focus on quantifying the
latency (which is huge when using the Arduino libraries), and on the
means to minimize it. Most of what follows is specific to the hardware
of the Arduino Uno and similar boards.

Minimizing the interrupt latency on the Arduino

(or how to get from 99 down to 5 cycles)

I will use the original question as a working example, and restate the
problem in terms of interrupt latency. We have some external event that
triggers an interrupt (here: INT0 on pin change). We need to take some
action when the interrupt is triggered (here: read a digital input). The
problem is: there is some delay between the interrupt being triggered
and our taking the appropriate action. We call this delay "interrupt
latency". A long latency is detrimental in many situations. In this
particular example, the input signal may change during the delay, in
which case we get a faulty reading. There is nothing we can do to avoid
the delay: it is intrinsic to the way interrupts work. We can, however,
try to make it as short as possible, which should hopefully minimize the
bad consequences.

The first obvious thing we can do is take the time-critical action,
inside the interrupt handler, as soon as possible. This means calling
digitalRead() once (and only once) at the very beginning of the
handler. Here is the zeroth version of the program upon which we will
build:

#define INT_NUMBER 0
#define PIN_NUMBER 2    // interrupt 0 is on pin 2
#define MAX_COUNT  200

volatile uint8_t count_edges;  // count of signal edges
volatile uint8_t count_high;   // count of high levels

/* Interrupt handler. */
void read_pin()
{
    int pin_state = digitalRead(PIN_NUMBER);  // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (pin_state == HIGH) count_high++;
}

void setup()
{
    Serial.begin(9600);
    attachInterrupt(INT_NUMBER, read_pin, CHANGE);
}

void loop()
{
    /* Wait for the interrupt handler to count MAX_COUNT edges. */
    while (count_edges < MAX_COUNT) { /* wait */ }

    /* Report result. */
    Serial.print("Counted ");
    Serial.print(count_high);
    Serial.print(" HIGH levels for ");
    Serial.print(count_edges);
    Serial.println(" edges");

    /* Count again. */
    count_high = 0;
    count_edges = 0;  // do this last to avoid race condition
}

I tested this program, and the subsequent versions, by sending it trains
of pulses of varying widths. There is enough spacing between the pulses
to ensure that no edge is missed: even if the falling edge is received
before the previous interrupt is done, the second interrupt request will
be put on hold and eventually serviced. If a pulse is shorter than the
interrupt latency, the program reads 0 on both edges. The reported
number of HIGH levels is then the percentage of correctly read pulses.

What happens when the interrupt is triggered?

Before trying to improve the code above, we will take a look at the
events that unfold right after the interrupt is triggered. The hardware
part of the story is told by the Atmel documentation. The software part,
by disassembling the binary.

Most of the time, the incoming interrupt is serviced right away. It may
happen, however, that the MCU (meaning "microcontroller") is in the
middle of some time-critical task, where interrupt servicing is
disabled. This is typically the case when it is already servicing
another interrupt. When this happens, the incoming interrupt request is
put on hold and serviced only when that time-critical section is done.
This situation is hard to avoid completely, because there are quite a
few of those critical sections in the Arduino core library (which I will
call "libcore" in the following). Fortunately, these sections are
short and run only every so often. Thus, most of the time, our interrupt
request will be serviced right away. In the following, I will assume
that we do not care about those few instances when this is not the case.

Then, our request is serviced immediately. This still involves a lot of
stuff that can take quite a while. First, there is a hardwired sequence.
The MCU will finish executing the current instruction. Fortunately, most
instructions are single-cycle, but some can take up to four cycles.
Then, the MCU clears an internal flag that disables further servicing of
interrupts. This is intended to prevent nested interrupts. Then, the PC
is saved into the stack. The stack is an area of RAM reserved for this
kind of temporary storage. The PC (meaning "Program Counter") is an
internal register holding the address of the next instruction the MCU is
about to execute. This is what allows the MCU to know what to do next,
and saving it is essential because it will have to be restored in order
for the main program to resume from where it was interrupted. The PC is
then loaded with a hardwired address specific to the request received,
and this is the end of the hardwired sequence, the rest being
software-controlled.

The MCU now executes the instruction from that hardwired address. This
instruction is called an "interrupt vector", and is generally a "jump"
instruction that will bring us to a special routine called an ISR
("Interrupt Service Routine"). In this case, the ISR is called
"__vector_1", a.k.a. "INT0_vect", which is a misnomer because it is
an ISR, not a vector. This particular ISR comes from libcore. Like any
ISR, it starts with a prologue that saves a bunch of internal CPU
registers on the stack. This will allow it to use those registers and,
when it is done, restore them to their previous values in order not to
disturb the main program. Then, it will look for the interrupt handler
that was registered with attachInterrupt(), and it will call that
handler, which is our read_pin() function above. Our function will
then call digitalRead() from libcore. digitalRead() will look into
some tables in order to map the Arduino port number to the hardware I/O
port it has to read and the associated bit number to test. It will also
check whether there is a PWM channel on that pin that would need to be
disabled. It will then read the I/O port... and we are done. Well, we
are not really done servicing the interrupt, but the time-critical task
(reading the I/O port) is done, and it is all that matters when we are
looking at latency.

Here is a short summary of all the above, together with the associated
delays in CPU cycles:

hardwired sequence: finish current instruction, prevent nested
interrupts, save PC, load address of vector (≥ 4 cycles)
execute interrupt vector: jump to ISR (3 cycles)
ISR prologue: save registers (32 cycles)
ISR main body: locate and call user-registered function (13 cycles)
read_pin: call digitalRead (5 cycles)
digitalRead: find the relevant port and bit to test (41 cycles)
digitalRead: read the I/O port (1 cycle)

We will assume the best case scenario, with 4 cycles for the
hardwired sequence. This gives us a total latency of 99 cycles, or
about 6.2 µs with a 16 MHz clock. In the following, I will
explore some tricks that can be used to lower this latency. They come
roughly in increasing order of complexity, but they all need us to
somehow dig into the internals of the MCU.

Use direct port access

The obvious first target for shortening the latency is digitalRead().
This function provides a nice abstraction to the MCU hardware, but it is
too inefficient for time-critical work. Getting rid of this one is
actually trivial: we just have to replace it with digitalReadFast(),
from the digitalwritefast
library. This cuts the latency almost by half at the cost of a small
download!

Well, that was too easy to be any fun, I will rather show you how to do
it the hard way. The purpose is to get us started into low-level stuff.
The method is called "direct port access" and is nicely documented on
the Arduino reference at the page on Port
Registers. At this
point, it is a good idea to download and take a look at the ATmega328P
datasheet.
This 650-page document may seem somewhat daunting at first look. It is,
however, well organised into sections specific to each of the MCU
peripherals and features. And we only need to check the sections
relevant to what we are doing. In this case, it is the section named
I/O ports. Here is a summary of what we learn from those readings:

The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on the
AVR chip.
We get the whole port D at once by reading a special MCU register called
"PIND".
We then check bit number 2 by doing a bitwise logical and (the C ‘&’
operator) with 1 << 2.

So, here is our modified interrupt handler:

#define PIN_REG    PIND  // interrupt 0 is on AVR pin PD2
#define PIN_BIT    2

/* Interrupt handler. */
void read_pin()
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Now, our handler will read the I/O register as soon as it is called. The
latency is 53 CPU cycles. This simple trick saved us 46 cycles!

Write your own ISR

The next target for cycle-trimming is the INT0_vect ISR. This ISR is
needed for providing the functionality of attachInterrupt(): we can
change interrupt handlers at any time during program execution. However,
although nice to have, this is not really useful for our purpose. Thus,
instead of having the libcore's ISR locate and call our interrupt
handler, we will save a few cycles by replacing the ISR by our
handler.

This is not as hard as it sounds. ISRs can be written like normal
functions, we just have to be aware of their specific names, and define
them using a special ISR() macro from avr-libc. At this point it would
be good to have a look at the avr-libc's documentation on
interrupts,
and at the datasheet section named External Interrupts. Here is the
short summary:

We have to write a bit in a special hardware register called EICRA
(External Interrupt Control Register A) in order to configure the
interrupt to be triggered on any change of the pin value. This will be
done in setup().
We have to write a bit in another hardware register called EIMSK
(External Interrupt MaSK register) in order to enable the INT0
interrupt. This will also be done in setup().
We have to define the ISR with the syntax ISR(INT0_vect) { ... }.

Here is the code for the ISR and setup(), everything else is
unchanged:

/* Interrupt service routine for INT0. */
ISR(INT0_vect)
{
    uint8_t sampled_pin = PIN_REG;            // do this first!
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

void setup()
{
    Serial.begin(9600);
    EICRA = 1 << ISC00;  // sense any change on the INT0 pin
    EIMSK = 1 << INT0;   // enable INT0 interrupt
}

This comes with a free bonus: since this ISR is simpler than the one it
replaces, it needs less registers to do its job, then the
register-saving prologue is shorter. Now we are down to a latency of 20
cycles. Not bad considering that we started close to 100!

At this point I would say we are done. Mission accomplished. What
follows is only for those who are not afraid of getting their hands
dirty with some AVR assembly. Otherwise you can stop reading here, and
thank-you for getting so far.

Write a naked ISR

Still here? Good! For proceeding further, it would be helpful to have at
least some very basic idea of how assembly works, and to take a look at
the Inline Assembler
Cookbook
from the avr-libc documentation. At this point, our interrupt entry
sequence looks like this:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR prologue: save regs (12 cycles)
first thing in the ISR body: read the IO port (1 cycle)

If we want to do better, we have to move the reading of the port into
the prologue. The idea is the following: reading the PIND register will
clobber one CPU register, thus we need to save at least one register
before doing that, but the other registers can wait. We then need to
write a custom prologue that reads the I/O port right after saving the
first register. You have already seen in the avr-libc interrupt
documentation (you have read it, right?) that an ISR can be made
naked, in which case the compiler will emit no prologue or epilogue,
allowing us to write our own custom version.

The problem with this approach is that we will probably end up writing
the whole ISR in assembly. Not a big deal, but I would rather have the
compiler write those boring prologues and epilogues for me. So, here is
the dirty trick: we will split the ISR in two parts:

the first part will be a short assembly fragment that will

save a single register to the stack
read PIND into that register
store that value into a global variable
restore the register from the stack
jump to the second part

the second part will be regular C code with compiler-generated
prologue and epilogue

Our previous INT0 ISR is then replaced by this:

volatile uint8_t sampled_pin;    // this is now a global variable

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    push r0                \n"  // save register r0
    "    in r0, %[pin]          \n"  // read PIND into r0
    "    sts sampled_pin, r0    \n"  // store r0 in a global
    "    pop r0                 \n"  // restore previous r0
    "    rjmp INT0_vect_part_2  \n"  // go to part 2
    :: [pin] "I" (_SFR_IO_ADDR(PIND)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges >= MAX_COUNT) return;     // we are done
    count_edges++;
    if (sampled_pin & (1 << PIN_BIT)) count_high++;
}

Here we are using the ISR() macro to have the compiler instrument
INT0_vect_part_2 with the required prologue and epilogue. The compiler
will complain that "‘INT0_vect_part_2’ appears to be a misspelled
signal handler", but the warning can be safely ignored. Now the ISR has
a single 2-cycle instruction before the actual port read, and the total
latency is only 10 cycles.

Use the GPIOR0 register

What if we could have a register reserved for this specific job? Then,
we would not need save anything before reading the port. We can actually
ask the compiler to bind a global variable to a
register.
This, however, would require us to recompile the whole Arduino core and
libc in order to make sure the register is always reserved. Not really
convenient. On the other hand, the ATmega328P happens to have three
registers that are not used by the compiler nor any library, and are
available for storing whatever we want. They are called GPIOR0, GPIOR1
and GPIOR2 (General Purpose I/O Registers). Although they are mapped
in the I/O address space of the MCU, these are actually not I/O
registers: they are just plain memory, like three bytes of RAM that
somehow got lost in a bus and ended up in the wrong address space. These
are not as capable as the internal CPU registers, and we cannot copy
PIND into one of these with the in instruction. GPIOR0 is interesting,
though, in that it is bit-addressable, just like PIND. This will allow
us to transfer the information without clobbering any internal CPU
register.

Here is the trick: we will make sure that GPIOR0 is initially zero (it
is actually cleared by hardware at boot time), then we will use the
sbic (Skip next instruction if some Bit in some I/o register is Clear)
and the sbi (Set to 1 some Bit in some I/o register) instructions as
follows:

sbic PIND, 2   ; skip the following if bit 2 of PIND is clear
sbi GPIOR0, 0  ; set to 1 bit 0 of GPIOR0

This way, GPIOR0 will end up being 0 or 1 depending on the bit we wanted
to read from PIND. The sbic instruction takes 1 or 2 cycles to execute
depending on whether the condition is false or true. Obviously, the PIND
bit is accessed on the first cycle. In this new version of the code, the
global variable sampled_pin is not useful anymore, since it is
basically replaced by GPIOR0:

/* Interrupt service routine for INT0. */
ISR(INT0_vect, ISR_NAKED)
{
    asm volatile(
    "    sbic %[pin], %[bit]    \n"
    "    sbi %[gpio], 0         \n"
    "    rjmp INT0_vect_part_2  \n"
    :: [pin]  "I" (_SFR_IO_ADDR(PIND)),
       [bit]  "I" (PIN_BIT),
       [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));
}

ISR(INT0_vect_part_2)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

It should be noted that GPIOR0 has to always be reset in the ISR.

Now, the sampling of the PIND I/O register is the very first thing done
inside the ISR. Total latency is 8 cycles. This is about the best we can
do before getting stained with terribly sinful kludges. This is again a
good opportunity to stop reading...

Put the time-critical code in the vector table

For those still here, here is our current situation:

hardwired sequence (4 cycles)
interrupt vector: jump to ISR (3 cycles)
ISR body: read the IO port (on 1st cycle)

There is obviously little room for improvement. The only way we could
shorten the latency at this point is by replacing the interrupt vector
itself by our code. Be warned that this should be immensely distasteful
to anyone who values clean software design. But it is possible, and I
will show you how.

The layout of the ATmega328P vector table can be found in the datasheet,
section Interrupts, subsection Interrupt Vectors in ATmega328 and
ATmega328P. Or by disassembling any program for this chip. Here is how
it looks like. I am using avr-gcc and avr-libc's conventions (__init
is vector 0, addresses are in bytes) which are different from Atmel's.

address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ jmp __vector_1  │ a.k.a. INT0_vect
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

Each vector has a 4-byte slot, filled with a single jmp instruction.
This is a 32-bit instruction, unlike most AVR instructions which are
16-bit. But a 32-bit slot is too small to hold the first part of our
ISR: we can fit the sbic and sbi instructions, but not the rjmp.
If we do that, the vector table ends up looking like this:

address │ instruction     │ comment
────────┼─────────────────┼──────────────────────
 0x0000 │ jmp __init      │ reset vector
 0x0004 │ sbic PIND, 2    │ the first part...
 0x0006 │ sbi GPIOR0, 0   │ ...of our ISR
 0x0008 │ jmp __vector_2  │ a.k.a. INT1_vect
 0x000c │ jmp __vector_3  │ a.k.a. PCINT0_vect
  ...
 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect

When INT0 fires, PIND will be read, the relevant bit will be copied into
GPIOR0, and then the execution will fall through to the next vector.
Then, the ISR for INT1 will be called, instead of the ISR for INT0. This
is creepy, but since we are not using INT1 anyway, we will just "hijack"
its vector for servicing INT0.

Now, we just have to write our own custom vector table to override the
default one. It turns out it is not so easy. The default vector table is
provided by the avr-libc distribution, in an object file called
crtm328p.o that is automatically linked with any program we build.
Unlike library code, object-file code is not meant to be overridden:
trying to do that will give a linker error about the table being defined
twice. This means we have to replace the whole crtm328p.o with our
custom version. One option is to download the full avr-libc source
code, do our
custom modifications in
gcrt1.S,
then build this as a custom libc.

Here I went for a lighter, alternative approach. I wrote a custom
crt.S, which is a simplified version of the original from avr-libc. It
lacks a few rarely used features, like the ability to define a "catch
all" ISR, or to be able to terminate the program (i.e. freeze the
Arduino) by calling exit(). Here is the code. I trimmed the repetitive
part of the vector table in order to minimize scrolling:

#include <avr/io.h>

.weak __heap_end
.set  __heap_end, 0

.macro vector name
    .weak \name
    .set \name, __vectors
    jmp \name
.endm

.section .vectors
__vectors:
    jmp __init
    sbic _SFR_IO_ADDR(PIND), 2   ; these 2 lines...
    sbi _SFR_IO_ADDR(GPIOR0), 0  ; ...replace vector_1
    vector __vector_2
    vector __vector_3
    [...and so forth until...]
    vector __vector_25

.section .init2
__init:
    clr r1
    out _SFR_IO_ADDR(SREG), r1
    ldi r28, lo8(RAMEND)
    ldi r29, hi8(RAMEND)
    out _SFR_IO_ADDR(SPL), r28
    out _SFR_IO_ADDR(SPH), r29

.section .init9
    jmp main

It can be compiled with the following command line:

avr-gcc -c -mmcu=atmega328p silly-crt.S

The sketch is identical to the previous one except that there is no
INT0_vect, and INT0_vect_part_2 is replaced by INT1_vect:

/* Interrupt service routine for INT1 hijacked to service INT0. */
ISR(INT1_vect)
{
    if (count_edges < MAX_COUNT) {
        count_edges++;
        if (GPIOR0) count_high++;
    }
    GPIOR0 = 0;
}

To compile the sketch, we need a custom compile command. If you have
followed so far, you probably know how to compile from the command line.
You have to explicitly request silly-crt.o to be linked to your program,
and add the -nostartfiles option to avoid linking in the original
crtm328p.o.

Now, the reading of the I/O port is the very first instruction executed
after the interrupt triggers. I tested this version by sending it short
pulses from another Arduino, and it can catch (although not reliably)
the high level of pulses as short as 5 cycles. There is nothing more we
can do to shorten the interrupt latency on this hardware.