How to change i2c address of Lidar Lite v3 using LidarLite library (Solved)

You probably need to use LIDARLite_v3HP.h. The setI2Caddr() function is not same between LIDARLite_v3HP.h and LIDARLite.h.
The datasheet you provided, has the instruction on how to update the I2C address. LIDARLite_v3HP.h's setI2Caddr() followed those instructions.
To check, if you go to this line of the source code of LIDARLite.h, you will see the function doesn't write 0x08 to 0x1e, instead writes 0x00. Either that's how it was in the earlier versions or maybe it's a bug.
Also, it is mentioned in the datasheet that, if you power cycle the Lidar the address will be restored to default.

Update
After I gone through the library more carefully I noticed that writing `0x08` into `0x01` is actually handled but differently in the `LIDERLite.h'.
Here is the setI2Caddr() code from the library (check the last two lines):
void LIDARLite::setI2Caddr(char newAddress, char disableDefault, char lidarliteAddress)
{
  byte dataBytes[2];

  // Read UNIT_ID serial number bytes and write them into I2C_ID byte locations
  read ((0x16 | 0x80), 2, dataBytes, false, lidarliteAddress);
  write(0x18, dataBytes[0], lidarliteAddress);
  write(0x19, dataBytes[1], lidarliteAddress);

  // Write the new I2C device address to registers
  dataBytes[0] = newAddress;
  write(0x1a, dataBytes[0], lidarliteAddress);

  // Enable the new I2C device address using the default I2C device address
  dataBytes[0] = 0;
  write(0x1e, dataBytes[0], lidarliteAddress);

  // If desired, disable default I2C device address (using the new I2C device address)
  if (disableDefault)
  {
    dataBytes[0] = (1 << 3); // set bit to disable default address
    write(0x1e, dataBytes[0], newAddress);
  }
}

All you have to do is set disableDefault to any positive int when you call setI2Caddr().


I have simulated your circuit and it seems sound enough to me.

It is a little confusing having the transistors there though.  I would prefer to convert the three open drain outputs to logic level outputs (each having its own pullup resistor) then use a digital 3:1 MUX (or discrete logic gates) to select the signal to sample.


L298N Dual Motor Controller Enable Pin has power but motors not working

I found this thread for a similar problem,
I realized that my scratch (taken from here) wasn't able to works..
After many and many tries, I found that:
the scratch works only using Serial Plotter, and not using Serial monitor.
In my case it was not necessary to connect 5vout of L298N with arduino,
(clearly you need to connect ground to battery supply and to arduino ground too).
I don't know why the scratch works properly (make motors turn) only by Serial Plotter and it doesn't work by Serial monitor.
I really would like to understand it!! (if someone could explain this oddity I would be very grateful).
Hope this could help.
UPDATE:
I found why it doesn't work on Serial monitor..
In the serial monitor, by using:
int inByte = Serial.read();

you must select "no line ending".
:)
it's always human error!
NOTE:
the 5V pin let to power Raspberry and this is it use.
I don't know if that solution should be risky..
In the Datasheet it's said:

A non-inductive 100nF capacitor must be connected between this pin and ground

I searched about this solution on Raspberry but, after many readings, I just don't know if this could be a safe solution to power it.
I can't suggest it as a secure way.


As I wrote in the comments, I can't recreate this problem again. So I apologize for wasting everyone's time. But I still find it weird how the -Os flag works. I assumed it meant smallest possible size. But I now think it means "fairly small, but also make it run fast". Look at the code below, and how using the noinline attribute makes the code smaller. I added the -Os compiler flag to be sure, but I think it is already on by default.

class InlineClass
{
public:
    void __attribute__((noinline)) testFunc(int arg1)       // 570 bytes
    //void testFunc(int arg1)               // 602 bytes
    //inline void testFunc(int arg1)        // 602 bytes
    {
        _var1 = arg1 + 1;
        _var2 = arg1 + 2;
        _var3 = arg1 + 3;
        _var4 = arg1 + 4;
        _var5 = arg1 + 5;
    }

private:
    volatile int _var1 = 0;
    volatile int _var2 = 0;
    volatile int _var3 = 0;
    volatile int _var4 = 0;
    volatile int _var5 = 0;
};

void setup()
{
    InlineClass ic;
    ic.testFunc(1);
    ic.testFunc(2);
    ic.testFunc(3);
    ic.testFunc(4);
    ic.testFunc(5);
}


The crc8 function calculates the Cyclic Redundancy Check (8-bit) value for the data you provide. It is then up to you to compare that calculated value with the CRC you have received.

The ? you are seeing in the serial terminal is an unprintable character. It is representing an 8-bit value that doesn't lie within the 32-127 range of normal ASCII characters, or 32-255 of the extended ASCII character set.


Any advice on how to repeat the song 6 times instead of infinitely?

Assuming, the program can stop after playing 6 times, put another for loop in the loop function:
void loop()
{
   for (int nTimes = 0; nTimes < 6; nTimes++)
   {
      // Existing loop code
   }

   while(true) {};
}

A less crude way is to create a global variable:
int _timesPlayed = 0;

And change the for loop:
void loop()
{
   if (_timesPlayed < 6)
   {
      // Existing loop code

     _timesPlayed++;
   }
}


It can be done with two N-channel MOSFETs or one P-channel MOSFET (depending on what you have locally / can get / is in your bits box):

simulate this circuit – Schematic created using CircuitLab

In the left schematic the first MOSFET acts like a NOT gate, and the second is a simple low-side switch. The pair together make an active-low low-side switch.

The right hand schematic, which is somewhat simpler, uses a single P channel MOSFET as a high-side switch. This is normally driven with an N-channel MOSFET to invert the logic, since it is naturally active-low. You don't want that, so you can just connect direct to the gate.

Note that all MOSFETs are "logic level" with a threshold voltage below 3V (or -3V in the case of the P-channel).


Take two 10K or so resistors:

    +5V
     |
    10K
     |
Pin2-+---> output
     |
    10K
     |
    GND

The following program does the trick:

const uint8_t kPin = 2;
const uint32_t kDelay = 10;  // 100Hz

void setup() {
}

void loop() {
  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, HIGH);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);

  pinMode(kPin, OUTPUT);
  digitalWrite(kPin, LOW);
  delay(kDelay);

  pinMode(kPin, INPUT);
  delay(kDelay);
}

When Pin2 (or any other pin for that matter) is set as INPUT, it is in high-impedance state (theoretically), so effectively you have a voltage divider giving you 1/2 Vcc. When it is set as OUTPUT, and now assuming that its output impedance is << 10KΩ, it drives the output to either +5V or 0V.


WebSocket client for ArduinoHttpClient conditional if with readString() incoming data buffer

this workes:

if (messageSize > 0) {
      //Serial.println(client.readString());
      String input = client.readString();
      Serial.println(input);

looks like reading from the method readString() empties the buffer hence cant use it again, what I did is store it on a String object variable "input" and use that.

It worked.


How to choose between AM230x and DHT22 temperature and humidity sensors?

The AM2301 and the DHT22(AM2303) are similar in a number of ways, both in price, specs, ranges and power consumption. They are usually cased a bit of a differently, with the DHT22/AM2303 being packaged with four pins (only three are in use), and the AM2301 (formerly called DHT21) is packaged with three cables and a small plug inside of the case.

I would choose based on the usage, if I'm going to use the sensor on a breadboard or a socket (going for the DHT22 pinned version), or if I'm going to have it standalone (the cabled one).

Here are links to the datasheets:

https://kropochev.com/downloads/humidity/AM2301.pdf

https://www.adafruit.com/datasheets/DHT22.pdf


Why the need to use the volatile keyword on global variables when handling interrupts in Arduino?

First, it's volatile not Volatile. I cover these concepts in my page about Interrupts however to avoid giving a link-only answer I'll repeat the relevant bits.

What are "volatile" variables?

Variables shared between ISR functions and normal functions should be declared volatile. This tells the compiler that such variables might change at any time, and thus the compiler must reload the variable whenever you reference it, rather than relying upon a copy it might have in a processor register.

For example:

volatile boolean flag;

// Interrupt Service Routine (ISR)
void isr ()
{
 flag = true;
}  // end of isr

void setup ()
{
  attachInterrupt (0, isr, CHANGE);  // attach interrupt handler
}  // end of setup

void loop ()
{
  if (flag)
    {
    // interrupt has occurred
    }
}  // end of loop

Critical sections ... accessing volatile variables

There are some subtle issues regarding variables which are shared between interrupt service routines (ISRs) and the main code (that is, the code not in an ISR).

Since an ISR can fire at any time when interrupts are enabled, you need to be cautious about accessing such shared variables, as they may be being updated at the very moment you access them.

First ... when do you use "volatile" variables?

A variable should only be marked volatile if it is used both inside an ISR, and outside one.

Variables only used outside an ISR should not be volatile.
Variables only used inside an ISR should not be volatile.
Variables used both inside and outside an ISR should be volatile.

eg.

volatile int counter;

Marking a variable as volatile tells the compiler to not "cache" the variable's contents into a processor register, but always read it from memory, when needed. This may slow down processing, which is why you don't just make every variable volatile, when not needed.

Atomic access

Consider this code:

volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }

void setup ()
  {
  }

void loop ()
  {
  count++;
  }

The code generated for count++ (add 1 to count) is this:

 14c:   80 91 00 02     lds r24, 0x0200
 150:   8f 5f           subi    r24, 0xFF     <<---- problem if interrupt occurs before this is executed
 152:   80 93 00 02     sts 0x0200, r24   <<---- problem if interrupt occurs before this is executed

(Note that it adds 1 by subtracting -1)

There are two danger points here, as marked. If the interrupt fires after the lds (load register 24 with the variable count), but before the sts (store back into the variable count) then the variable might be changed by the ISR (TIMER1_OVF_vect), however this change is now lost, because the variable in the register was used instead.

We need to protect the shared variable by turning off interrupts briefly, like this:

volatile byte count;

ISR (TIMER1_OVF_vect)
  {
  count = 10;
  }  // end of TIMER1_OVF_vect

void setup ()
  {
  }  // end of setup

void loop ()
  {
  noInterrupts ();
  count++;
  interrupts ();
  } // end of loop

Now the update of count is done "atomically" ... that is, it cannot be interrupted.

Multi-byte variables

Let's make count a 2-byte variable, and see the other problem:

volatile unsigned int count;

ISR (TIMER1_OVF_vect)
  {
  count++;
  } // end of TIMER1_OVF_vect

void setup ()
  {
  pinMode (13, OUTPUT);
  }  // end of setup

void loop ()
  {
  if (count > 20)
     digitalWrite (13, HIGH);
  } // end of loop

OK, we are not changing count any more, so is there still a problem? Sadly, yes. Let's look at the generated code for the "if" statement:

 172:   80 91 10 02     lds r24, 0x0210
 176:   90 91 11 02     lds r25, 0x0211  <<---- problem if interrupt occurs before this is executed
 17a:   45 97           sbiw    r24, 0x15
 17c:   50 f0           brcs    .+20

Imagine that count was 0xFFFF and was about to "wrap around" back to zero. We load 0xFF into one register, but before we load the second 0xFF the variable changes to 0x00. Now we think count is 0x00FF which is neither the value it had before (0xFFFF) or now (0x0000).

So again we have to "protect" the access to the shared variable, like this:

void loop ()
  {
  noInterrupts ();
  if (count > 20)
     digitalWrite (13, HIGH);
  interrupts ();
  }  // end of loop

What if you are not sure interrupts are on or off?

There is a final "gotcha" here. What if interrupts might be off already? Then turning them back on afterwards is a Bad Idea.

In that case you need to save the processor status register like this:

unsigned int getCount ()
  {
  unsigned int c;
  byte oldSREG = SREG;   // remember if interrupts are on or off

  noInterrupts ();   // turn interrupts off
  c = count;         // access the shared variable
  SREG = oldSREG;    // turn interrupts back on, if they were on before

  return c;          // return copy of shared variable
  }  // end of getCount

This "safe" code saves the current status of interrupts, turns them off (they may already be off), gets the shared variable into a temporary variable, turns interrupts back on - if they were on when we entered the function - and then returns the copy of the shared variable.

Summary

Code may "appear to work" even if you don't take the above precautions. That is because the chances of the interrupt occurring at the exact wrong moment is fairly low (maybe 1 in 100, depending on the code size). But sooner or later it will happen at the wrong moment, and your code will either crash, or occasionally return the wrong results.

So for reliable code, pay attention to protecting access to shared variables.


Is there any way I can light up a candle with an Arduino?

A simple solution is too use nichrome wire which when a current is passes through it will heat up. You could wrap some of this wire around the wick on the candle and then power it either straight from your arduino or you could include a capacitor.
This is much safer than some of the other methods which use potentially dangerous high voltages.

I tested the nichrome wire approach and it works! See following video clip. 2 Ohm resistance and 19V for 1 second.  https://1drv.ms/v/s!AvcBubMtAczvifYZwoESAhUodOoqRA


Arduino Micro serial communication is not working after wake from power down

I found the answer on this related question: Starting usb on pro micro after deep sleep (ATmega32u4)

Which itself was a link to a sparkfun forum

Note: it requires you to close and open the serial monitor at proper timings.

// disable the USB prior going to sleep
USBCON |= _BV(FRZCLK);  //freeze USB clock
PLLCSR &= ~_BV(PLLE);   // turn off USB PLL
USBCON &= ~_BV(USBE);   // disable USB

// and wake it up after
//routine to properly wake up
sleep_disable();
delay(100);
USBDevice.attach(); // keep this
delay(100);
Serial.begin(9600);
delay(100);


Is there possible implement websocket using AT Command?

Yes, you can @Imanuel. You just need to establish a Simple TCP connection and then send the HTTP headers for upgrading the normal HTTP connection to WebSockets.


Can I do something like this to simplify the code for arduino?

There are indeed some errors.

First, you cannot assign a function body to a variable.

So you have to rewrite the Blink function:

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

Also for calling a function, even without parameters, you should use ( and ):

void loop()
{
    blink();
}

Also you need to use the correct capitals or not:

int led = 13;

You can make it constant since it does not change:

static const int led = 13;

So all together you get:

static const int led = 13;

void setup()
{
    pinMode(led, OUTPUT);
}

void loop()
{
    blink();
}

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

I suggest you read a book about C or C++ to get used to the syntax.

Also, note that int is written as int, not Int. Case matters.


How can I discover attached motor shields in code?

If you configure each I2C device to have a unique address, then it's easy to determine which ones are connected.

This sketch is derived from the I2C Scanner sketch found here: I2cScanner

// This sketch tests the standard 7-bit addresses.
// Devices with higher bit address might not be seen properly.
#include <Wire.h>
byte shieldOneAddress = 0x27;
byte shieldTwoAddress = 0x32;
byte error, address;

void setup(){

  Wire.begin();
  Serial.begin(9600);
  Serial.println("Scanning for shields...");

  for(address = 1; address < 127; address++){

    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if(error == 0){
      if(address == shieldOneAddress){
        Serial.println("Shield One is connected.");
      }
      if(address == shieldTwoAddress){
        Serial.println("Shield Two is connected.");
      }
    }

  }
  Serial.println("Scan complete.\n");
}

void loop(){}


Software Serial and multiple shields for Arduino Uno

SoftwareSerial can use any pins. That's the whole point of it. However, some shields are wired to use specific pins. If two shields try and use the same pins then you can't use them together. Not stacked, anyway. You will have to use flying leads, or physically alter the shield (cutting tracks, soldering in "bodge" wires) to use them together.

That said, though, you can only use ONE SoftwareSerial port reliably at a time. That means, regardless of what pins they use, you can't use two shields together that require pins other than 0 and 1 (hardware serial).

To use them both you will need a board with multiple hardware UART ports and modify the shields (as mentioned above) to use the correct pins for those UART ports.


I bet your problem has nothing to do with “smoothness” (whatever that
means), but is entirely due to lack of message framing. The serial and
bluetooth links do not transmit messages: they transmit only a stream of
bytes, with no built-in notion of where a message ends and the next one
starts. Relying on the timing of the received bytes to tell the messages
apart is very unwise. You should instead use some kind of delimiter for
your messages.

For text-based transmissions like yours, the most natural choice is to
send a line terminator at the end of each message. Typically a CR+LF
pair. The Serial object has the println() methods designed precisely
for this purpose: they send their arguments immediately followed by
CRLF:

Serial.print(x); Serial.print(","); Serial.println(y);

At the receiving end, you have to buffer all the incoming characters
until you see the line termination. Then you know the message is
complete and you can process it.


Use a button on LCD shield to pause the code

You are not saying much about how buttons is valorized or its data type, but assuming it is a numeric variable which gets somehow set by, let's say a readButtons() function, then consider the following snippet replacing your while-loop:

do {
  delay(10);
  // re-evaluate whatever sets the buttons variable
  buttons = readButtons();
while(!(buttons & BUTTON_DOWN));

The loop above will continue until the button down is pressed and it's a little resilient regarding contact bouncing, but not 100% reliable, so I assume the readButtons() performs also some debouncing.


How to get code to respond to a certain time from the DS3231 RTC?

the easiest is to set up the alarm in rtc.

alternatively, keep reading the rtc until the desired time has passed. not terribly efficient.


Reasons why it is not OK to connect a relay directly from an Arduino digital pin

Processor pins have strictly limited current drive capability.

The rated values may vary depending on whether you want a high or low drive.
Some processors will supply only a few mA and the most you will usually officially get is in the 20 to 30 mA range.
There is usually a total current limit for the processor and only a few pins can provide peak current simultaneously.
Processor pins have significant effective resistance and a high voltage will "drop" as increasing current is drawn and a low voltage will rise as load increases. Pins MAY be specific with a maximum short circuit current but at that point a high pin will be pulled low and a low pin will be pulled high so short circuit current has limited applicability.

Even if you have a say 25 mA per pin rated processor the power available is small. 25 mA · 4V say (1V drop on 5V Vcc) = 100 mW. Most motors will take more than that and only very small motors will run well when powered only by a pin.

Electric motors and inductors will generate significantly high voltages when current is interrupted - voltages of tens of volts can easily result and 100+ volts can happen. Connecting a motor of inductor to a processor pin directly is an invitation to destruction. Murphy will often oblige.

A transistor (bipolar or MOSFET) that will drive typical hobby motors costs 10's of cents (or free from scrapped equipment) and allows the port pin current drive to be buffered and "amplified". Use of a transistor or other buffer is an extremely good idea if you have one or a few processors and do not wish them to die semi-randomly.

MOSFET motor driver - from here - section 8.

Voltages and part numbers are for their example - select to suit.
A NPN biploar could be used with the addition of an input resistor to the transistor base.

Bidirectional driver - if you want the driver to be able to drive a load high and low this circuit will work. from here
The input gate is in this case the internal processor driver. The two MOSFET gates connect directly to the processor pin. Vdd should usually be no higher than processor Vmax_drive_out. Slightly higher can be made to work with suitable design. Much higher voltage loads can be driven with this circuit (or similar) plus one extra transistor.

A buffer such as a ULN2803 (and other family members) will drive 8 channels x 500 mA/channel and several can be paralleled.

A ULN2803 is essentially 8 x "Darlington" transistors with emitters connected to a common ground, 8 x "open collector" (unconnected) collectors, and 8 flyback diodes to deal with over voltage spikes (use optional). (There is a ULN280x family with slightly different input characteristics).

This device provides a reasonably priced means of providing 8 x 500 mA pull down drivers. A load connected from an output to V+ is turned on when the input pin is driven high. Once you've used one a few times you'll find them trivially easy to use and very useful. (There is also a ULN200x family with 7 channels per package).

YouTube "how to" video

Driving a stepper motor

Also here

Driving small DC motors - and quite a lot else.

A zillion examples

Digikey - available in 1's if desired $0.72/1, $0.29 in 1000's.

ULN2803 datasheet

For sale at Sparkfun  - can be had rather cheaper but these are available


Communication between Arduino and raspberry Pi

You can't make the Arduino just run the Python script on the Pi. Instead you will have to run some software (probably of your own devising) on the Pi that listens for instructions from the Arduino.

The simplest way is probably to modify your existing Python script so that it runs all the time but sits idling waiting for instructions through the serial port (using pySerial). When it gets the instruction to perform the task you need it then goes off and runs the main bulk of its code. When that is done it can then return the results back through the serial port to the Arduino (if you need such results returning).

How you arrange those instructions to get it to do things is entirely up to you.


You have an 8-bit parallel interface TFT display. It requires 13 GPIO pins - D0-D7 plus reset, chip select, read, write and register select. You can forego the "read" signal and tie it high to save a pin. You can probably do the same with the reset signal, meaning you need a minimum of 11 pins.

I am not sure the NodeMCU has that many available, does it? (maybe it does, I don't have one to hand right now), so you may want to try getting it going with an SPI or I2C IO expander (though slowly).

And then of course you have to find the right library for the chip on the display (there's a few it could be - I have seen at least 3 different ones on the same, or similar, carrier PCB) that works with the NodeMCU.


How to build an µC controlled power regulator?

It's actually very simple, and it indeed does involve using PWM.

PWM is just a signal being on for a percentage of a predefined period.  That percentage is also, when the PWM signal is averaged out, equivalent to a percentage of the peak voltage of the PWM signal.

So if you take a PWM signal and use it to switch a higher power source (say, through a P-channel MOSFET that's being itself switched by an N-channel MOSFET), then add smoothing to that switched output, and you have a variable voltage.

If you want to know what that voltage is you can add a resistor network to the output (assuming it's higher than the voltage the MCU can handle) and read the divided voltage using an ADC.  You can then use that as a feedback loop to adjust the PWM duty cycle to get your desired voltage.

simulate this circuit – Schematic created using CircuitLab

That is precisely* how switch-mode power supplies work. Use PWM to switch a FET that controls an incoming voltage, then smooth it out, adding a feedback network for control.

*Apart from the PWM bit: they often use other methods of switching the signal to get better efficiency at different loads, such as PFM.


Arduino: The program exited the loop early and execute setup() repeatedly

This can happen when your sketch uses too much memory - the board can no longer assign addresses so it resets leading to an endless loop. Try reducing the amount of memory you are allocating.


What is the maximum frequency input signal that I can accurately track on a GPIO pin?

As Majenko wrote, when you only rely on software to measure the frequency on a IO pin, it will always be rather slow. And it also depends on the code, that you use. Functions like digitalRead() are always slower than directly working with the control registers of the pin (Reference). As you didn't show your code, we cannot say more about that.
If you need to measure higher frequencies or you want to do other things in between (like outputting the data somewhere), it is better to use the microcontrollers buildin hardware. There are multiple ways to measure the frequency. 2 immediately come to my mind:

You could assign an ExternalInterrupt or a PinChangeInterrupt to the signal pin (limited choice of pins here), which triggers each time you see a rising (or falling) edge on the signal. In the ISR (Interrupt Service Routine) you could count up a variable. That value is the number of rising (or falling) edges, thus periods of the signal. The frequency is this value divided by the duration of the measurement. Every time you calculate the frequency, you reset the counter; reading it again after a defined duration. This should be better than just polling, but its not the best. (Note that a PinChangeInterrupt triggers on every edge, so you have to divide the frequency by 2)

You could configure an unused Hardware Timer/Counter to use your signal as external clock source. Let it count up until it overflows (or up to a value defined by you) and let it trigger an interrupt. Since the Arduino framework already uses Timer0 for timekeeping, you could divide the max value of the Timer/Counter by the time passed and you will get the frequency. I think this can get you in the MHz range.(As with PinChangeInterrupt, the Counter will increment on every edge, so again a factor of 2 here)

Both ways will calculate the frequency as a mean over a specific time. If you have a changing frequency, you might wanna manipulate measurement frequency. In the first case you can change the interval, in which you read the counter variable. In the second case you can change the max value, to which the Timer/Counter will count.

what the highest frequency digital signal that I could read?

(I assume you just want to read the frequency of the signal) That depends on many factors. If we use the second case from above (configuring a Hardware Timer as Counter connected to the signal) we have a limit on the maximum frequency, that we can provide. I found the relevant part in the datasheet of Atmega328p (which is the microcontroller on the Nano):

Each half period of the external clock applied must be longer than one system clock cycle to ensure correct
sampling. The external clock must be guaranteed to have less than half the system clock frequency (f ExtClk < f clk_I/O /2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an
external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to
variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and
capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than
f clk_I/O /2.5.

So we should stay below the controllers clock frequency divided by 2.5, which would be 16MHz / 2.5 = 6.4MHz for the Nano. But before you reach that, your code might introduce further delays, which make the measurement less accurate. That depends on the implementation.


Switching time of a multiple input switch

Use External Interrupts is the short answer.
Longer version:
You probably want to make a buzzer system like what in family feud game show.
I assume you are using Arduino UNO/MEGA and or having experience with programming.
1/ Use INT0 and INT1 for button 1 and button 2.
When an interrupt is raised, the mcu jumps to a specific address to run the interrupt service routine. INT0 and INT1 vectors are pointing to two distinctive addresses to run 2 different functions. For this, mcu takes the least amount of CPU clock to capture which button press first.
2/ Use PCINT vectors which is PinChange Interrupt. But personally I prefer to call it PortChange Interrupt.
There are 3 PinChange interrupt vectors PCINT0, PCINT1, PCINT2 to run 3 distinctive service routines. But this kind of interrupt doesn't know which pin is changed.
So inside the interrupt service routine, you have to check for that specific pin. You can do this the arduino way digitalRead(button1) or capture the whole port register, ie. PORTB, PORTC or PORTD.
In a nutshell, PORTB holds values of digital pin 8 to 13 while port D hold values of digital pin 0 to 7 and PORC for A0 to A7.
You can shave off some CPU clocks (3-10 clocks probably) by put 2 buttons different PCINT vectors. So that each button still triggers distinctive function.
In 3 cpu clocks (or around 180 ns) a lot of things may change and you may not get the correct result.
3/ Polling in main loop()
This is the worst way to do it. Nevertheless, it still gives good result.
if (digitalRead(button1)==LOW) {
// do something
}

if (digitalRead(button2)==LOW) {
// do something else
}


How many 5.5v solar panel should i use to power arduino uno and 9v water pump?

I actually did this exact project a few years ago. However I ran a smaller 5v water pump, light sensor, and moisture sensor, and an LCD screen. Depending how you plan on operating your plant system, I would recommend having your uno plugged into a portable charger, then having your solar panel wired to charge the power supply during the day.
If you wanna keep it basic then you should get a single, larger panel that can supply enough power to those and its less complicated than wiring 3 separate solar panels (plus higher risk of one failing) since the Arduino takes 5v to power, plus the 9v for the pump so that's 14v needed to run your watering system. If you'd like I can send you my project files and you can edit or use them how you please.


Help with Arduino Micro Keypress Algorithm

Modifier keys are treated no different to normal keys.

The Arduino Keyboard library contains code to map different keys from the internal list of macros to specific keypresses:

If the key value is >= 138 it's a non-printing special key (subtract 138)
If the key value is >= 128 it is a modifier key (1 << (k - 128))
Otherwise look the code up in a mapping table.

That means you can use:

Keyboard.press(KEY_LEFT_SHIFT);

or

Keyboard.release(KEY_RIGHT_GUI);

The full list of modifier keys is:

#define KEY_LEFT_CTRL   0x80
#define KEY_LEFT_SHIFT    0x81
#define KEY_LEFT_ALT    0x82
#define KEY_LEFT_GUI    0x83
#define KEY_RIGHT_CTRL    0x84
#define KEY_RIGHT_SHIFT   0x85
#define KEY_RIGHT_ALT   0x86
#define KEY_RIGHT_GUI   0x87

So to do a capital A you can use:

Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('a');
Keyboard.release('a');
Keyboard.release(KEY_LEFT_SHIFT);

There is also a shortcut, and that is:

Keyboard.press('A');
Keyboard.release('A');

The character 'A' is the same in the lookup table as character 'a' except the high bit of the result is set, which triggers a "Press or release the shift key" addition in the mapping code.

A USB keyboard report consists of 8 bytes:

Up to 8 modifier keys (bitmap)
One reserved byte
6 bytes to indicate pressed keys

This means that you can have up to 6 keys pressed at once, plus modifier keys. Never any more than that. So you don't need to handle any more than that in your code.

The current list of pressed keys is maintained by the keyboard and is sent in every report. There's no concept as such of "pressed" or "released" - only the list of what is currently pressed. If a key is released it's just removed from that list of pressed keys.

So what you need is some way of transferring that data in such a way that the Arduino can interpret it properly.

Since the data is not high throughput you can afford to be quite wasteful in your protocol.  I would suggest using a fairly verbose ASCII based protocol.

All the protocol data is using ASCII characters between 32 and 127 inclusive
This frees up control characters (<32) for controlling the protocol.

The simplest thing is to use a single control character (such as \n) to act as a line ending to break your data up into packets.  Each packet can then contain a list of instructions.

For example, you might choose to have a protocol that looks like:

P,129\n
P,97\n
R,97\n
R,129\n

By treating each line as a complete entity you know that you want to Press key 129 (#define KEY_LEFT_SHIFT    0x81), press key 97 ('a'), release 97, then release 129.

There's no confusion, since commands are all a single upper-case character, and keys are all a decimal number.

For your application, though, a "raw" access interface would be of more use, since you don't really want the Arduino interpreting things for you. However, the API doesn't provide that kind of thing.  So you just have to make the best of what you have and work around it.


Combining arduino leonardo code with water alarm code

How do you want them to work ? Do you want the spacebar pressed when there is a high signal read (when the light goes on)?

If you want the space bar press when it goes high this might work:

#include <Keyboard.h>

bool eenkeergeweest = false;
int out = 12;
int in = 4;

void toggleKeyPress (const char& keypress)
{
    if (!eenkeergeweest)
    {
        eenkeergeweest = true;
        Keyboard.print(' ');
        delay(100);
    }
}

void setup()
{
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    // initialize control over the keyboard:
    Keyboard.begin();

}

void loop()
{
    const int rd = digitalRead(in);
    if (rd == HIGH)
    {
        toggleKeyPress(' ');
        digitalWrite(out, HIGH);
        // wait for new window to open:
        delay(1000);
    }
    else
    {
        digitalWrite(out, LOW);
    }
}


If I understand correctly you want to store a number of signed integers in an array.  Arrays have fixed sizes so you need to know the number of values you want to store.

// Global declarations
enum QIndex {WAxis, XAxis, YAxi, ZAxis, MaxIndex};
int16_t qData[MaxValues] = {0};

// Code inside loop
qData[WAxis] = readQuatW();
qData[XAxis] = readQuatX();
qData[YAxis] = readQuatY();
qData[ZAxis] = readQuatZ();

// Pass the array  of values to another function with the declaration
// void SomeFunction (int *ar);
// or
// void SomeFunction (int ar[]);
SomeFunction (qData);

Is that what you mean?


The latest news from Arduino that I can find is in their blog archive that the second round of beta testing is out.

The mentioned this:

  When is the Arduino TRE going to be finally on the market? The board is ready, but we don’t have a final release date yet because we are still figuring out some manufacturing matters. We’ll keep you posted!

I'd imagine that the Arduino LLC vs Arduino SLR legal issue is also delaying the production.

Other than that, speculation is all that we know.

P.S: it's still spring until Sunday, June 21! :-)


Acting as a conduit for Google: Arduino Change PWM Frequency shows me:

https://playground.arduino.cc/Code/PwmFrequency

Which has the following example function:

/**
 * Divides a given PWM pin frequency by a divisor.
 *
 * The resulting frequency is equal to the base frequency divided by
 * the given divisor:
 *   - Base frequencies:
 *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
 *      o The base frequency for pins 5 and 6 is 62500 Hz.
 *   - Divisors:
 *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
 *        256, and 1024.
 *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
 *        128, 256, and 1024.
 *
 * PWM frequencies are tied together in pairs of pins. If one in a
 * pair is changed, the other is also changed to match:
 *   - Pins 5 and 6 are paired on timer0
 *   - Pins 9 and 10 are paired on timer1
 *   - Pins 3 and 11 are paired on timer2
 *
 * Note that this function will have side effects on anything else
 * that uses timers:
 *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
 *     millis() functions to stop working. Other timing-related
 *     functions may also be affected.
 *   - Changes on pins 9 or 10 will cause the Servo library to function
 *     incorrectly.
 *
 * Thanks to macegr of the Arduino forums for his documentation of the
 * PWM frequency divisors. His post can be viewed at:
 *   http://forum.arduino.cc/index.php?topic=16612#msg121031
 */
void setPwmFrequency(int pin, int divisor) {
  byte mode;
  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 64: mode = 0x03; break;
      case 256: mode = 0x04; break;
      case 1024: mode = 0x05; break;
      default: return;
    }
    if(pin == 5 || pin == 6) {
      TCCR0B = TCCR0B & 0b11111000 | mode;
    } else {
      TCCR1B = TCCR1B & 0b11111000 | mode;
    }
  } else if(pin == 3 || pin == 11) {
    switch(divisor) {
      case 1: mode = 0x01; break;
      case 8: mode = 0x02; break;
      case 32: mode = 0x03; break;
      case 64: mode = 0x04; break;
      case 128: mode = 0x05; break;
      case 256: mode = 0x06; break;
      case 1024: mode = 0x07; break;
      default: return;
    }
    TCCR2B = TCCR2B & 0b11111000 | mode;
  }
}

And numerous results from this SE community also:

https://www.google.com/search?q=arduino+change+PWM+frequency+site:arduino.stackexchange.com

Which note methods for calculating/setting specific frequencies and pitfalls and side-effects of making such changes.


Any reason to acquire more watts than really needed?

Are you sure every led is 60 mA? Or you mean maybe each Red, green and blue led inside each led (3 x 20 mA).

You always should buy slightly more than you need (but you think about 200W instead of 135W) already which is more than enough safety overhead.

Why would you need more? If you mean to control it with an Arduino Uno, that MCU (including the LEDs etc) is high likely more than a few hundred mA. So the only reason why you need more, is if you want to control later more LED strips, or any motor or other power hungry external devices.


With my personal thoughts on Structs being the most efficient way to send many different variables I've constructed a library to help make it easier to send structs and variables over serial.  Source Code

In this library it makes sending through serial easily. I've used with with hardware and software serial. Usually this is used in conjunct with xbee's so I can wirelessly send the data to and from the robot.

When sending data it make it simple as it allows you to either send a variable or a struct (it doesn't care).

Here is an example of sending a simple char over the serial:

// Send the variable charVariable over the serial.
// To send the variable you need to pass an instance of the Serial to use,
// a reference to the variable to send, and the size of the variable being sent.
// If you would like you can specify 2 extra arguments at the end which change the
// default prefix and suffix character used when attempting to reconstruct the variable
// on the receiving end. If prefix and suffix character are specified they'll need to
// match on the receiving end otherwise data won't properly be sent across

char charVariable = 'c'; // Define the variable to be sent over the serial
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Example of sending a simple int over the serial:

int intVariable = 13496; // Define the int to be sent over the serial
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Specify a prefix and suffix character
StreamSend::sendObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Example of sending a struct over serial:

// Define the struct to be sent over the serial
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct;
simpleStruct.charVariable = 'z'; // Set the charVariable in the struct to z

// Fill the intVariable array in the struct with numbers 0 through 6
for(int i=0; i<7; i++) {
  simpleStruct.intVariable[i] = i;
}

// Send the struct to the object xbeeSerial which is a software serial that was
// defined. Instead of using xbeeSerial you can use Serial which will imply the
// hardware serial, and on a Mega you can specify Serial, Serial1, Serial2, Serial3.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Send the same as above with a different prefix and suffix from the default values
// defined in StreamSend. When specifying when prefix and suffix character to send
// you need to make sure that on the receiving end they match otherwise the data
// won't be able to be read on the other end.
StreamSend::sendObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'u');

Receiving Examples:

Receiving a char that was send via Streamsend:

char charVariable; // Define the variable on where the data will be put

// Read the data from the Serial object an save it into charVariable once
// the data has been received
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable));

// Reconstruct the char coming from the Serial into charVariable that has a custom
// suffix of a and a prefix of z
byte packetResults = StreamSend::receiveObject(Serial, &charVariable, sizeof(charVariable), 'a', 'z');

Receiving an int that was sent via StreamSend:

int intVariable; // Define the variable on where the data will be put

// Reconstruct the int from xbeeSerial into the variable intVariable
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable));

// Reconstruct the data into intVariable that was send with a custom prefix
// of j and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &intVariable, sizeof(intVariable), 'j', 'p');

Receiving a Struct that was sent via StreamSend:

// Define the struct that the data will be put
struct SIMPLE_STRUCT {
  char charVariable;
  int intVariable[7];
  boolean boolVariable;
};
SIMPLE_STRUCT simpleStruct; // Create a struct to store the data in

// Reconstruct the data from xbeeSerial into the object simpleStruct
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct));

// Reconstruct the data from xbeeSerial into the object simplestruct that has
// a prefix of 3 and a suffix of p
byte packetResults = StreamSend::receiveObject(xbeeSerial, &simpleStruct, sizeof(simpleStruct), '3', 'p');

Once you read the data using StreamSend::receiveObject() you need to know if the data was GOOD, Not Found, or BAD.

Good = Successful

Not Found = No prefix character was found in the specified ostream

Bad = Somehow there was a prefix character found, but the data isn't intact. Usually it means there was no suffix character found or the data wasn't the correct size.

Testing Validity of Data:

// Once you call StreamSend::receiveObject() it returns a byte of the status of
// how things went. If you run that though some of the testing functions it'll
// let you know how the transaction went
if(StreamSend::isPacketGood(packetResults)) {
  //The Packet was Good
} else {
  //The Packet was Bad
}

if(StreamSend::isPacketCorrupt(packetResults)) {
  //The Packet was Corrupt
} else {
  //The Packet wasn't found or it was Good
}

if(StreamSend::isPacketNotFound(packetResults)) {
  //The Packet was not found after Max # of Tries
} else {
  //The Packet was Found, but can be corrupt
}

SteamSend Class:

#include "Arduino.h"

#ifndef STREAMSEND_H
#define STREAMSEND_H

#define PACKET_NOT_FOUND 0
#define BAD_PACKET 1
#define GOOD_PACKET 2

// Set the Max size of the Serial Buffer or the amount of data you want to send+2
// You need to add 2 to allow the prefix and suffix character space to send.
#define MAX_SIZE 64

class StreamSend {
  private:
    static int getWrapperSize() { return sizeof(char)*2; }
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar);
    static char _prefixChar; // Default value is s
    static char _suffixChar; // Default value is e
    static int _maxLoopsToWait;

  public:
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize);
    static void sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize);
    static byte receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar);
    static boolean isPacketNotFound(const byte packetStatus);
    static boolean isPacketCorrupt(const byte packetStatus);
    static boolean isPacketGood(const byte packetStatus);

    static void setPrefixChar(const char value) { _prefixChar = value; }
    static void setSuffixChar(const char value) { _suffixChar = value; }
    static void setMaxLoopsToWait(const int value) { _maxLoopsToWait = value; }
    static const char getPrefixChar() { return _prefixChar; }
    static const char getSuffixChar() { return _suffixChar; }
    static const int getMaxLoopsToWait() { return _maxLoopsToWait; }

};

//Preset Some Default Variables
//Can be modified when seen fit
char StreamSend::_prefixChar = 's';   // Starting Character before sending any data across the Serial
char StreamSend::_suffixChar = 'e';   // Ending character after all the data is sent
int StreamSend::_maxLoopsToWait = -1; //Set to -1 for size of current Object and wrapper

/**
  * sendObject
  *
  * Converts the Object to bytes and sends it to the stream
  *
  * @param Stream to send data to
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize) {
  sendObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}

void StreamSend::sendObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  if(MAX_SIZE >= objSize+getWrapperSize()) { //make sure the object isn't too large
    byte * b = (byte *) ptr; // Create a ptr array of the bytes to send
    ostream.write((byte)prefixChar); // Write the suffix character to signify the start of a stream

    // Loop through all the bytes being send and write them to the stream
    for(unsigned int i = 0; i<objSize; i++) {
      ostream.write(b[i]); // Write each byte to the stream
    }
    ostream.write((byte)suffixChar); // Write the prefix character to signify the end of a stream
  }
}

/**
  * receiveObject
  *
  * Gets the data from the stream and stores to supplied object
  *
  * @param Stream to read data from
  * @param ptr to struct to fill
  * @param size of struct
  * @param character to send before the data stream (optional)
  * @param character to send after the data stream (optional)
  */
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize) {
    return receiveObject(ostream, ptr, objSize, _prefixChar, _suffixChar);
}
byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, char prefixChar, char suffixChar) {
  return receiveObject(ostream, ptr, objSize, 0, prefixChar, suffixChar);
}

byte StreamSend::receiveObject(Stream &ostream, void* ptr, unsigned int objSize, unsigned int loopSize, char prefixChar, char suffixChar) {
  int maxLoops = (_maxLoopsToWait == -1) ? (objSize+getWrapperSize()) : _maxLoopsToWait;
  if(loopSize >= maxLoops) {
      return PACKET_NOT_FOUND;
  }
  if(ostream.available() >= (objSize+getWrapperSize())) { // Packet meets minimum size requirement
    if(ostream.read() != (byte)prefixChar) {
      // Prefix character is not found
      // Loop through the code again reading the next char
      return receiveObject(ostream, ptr, objSize, loopSize+1, prefixChar, suffixChar);
    }

    char data[objSize]; //Create a tmp char array of the data from Stream
    ostream.readBytes(data, objSize); //Read the # of bytes
    memcpy(ptr, data, objSize); //Copy the bytes into the struct

    if(ostream.read() != (byte)suffixChar) {
      //Suffix character is not found
      return BAD_PACKET;
    }
      return GOOD_PACKET;
  }
  return PACKET_NOT_FOUND; //Prefix character wasn't found so no packet detected
}

boolean StreamSend::isPacketNotFound(const byte packetStatus) {
    return (packetStatus == PACKET_NOT_FOUND);
}

boolean StreamSend::isPacketCorrupt(const byte packetStatus) {
    return (packetStatus == BAD_PACKET);
}

boolean StreamSend::isPacketGood(const byte packetStatus) {
    return (packetStatus == GOOD_PACKET);
}

#endif


Try changing the resistance in your 10k potentiometer. This might be a reason for the black boxes.

P.S: I.m a beginner too.


char *res = "up_cmd0_res:";

In principle, res should be a const char *. Const because it is
pointing to a literal string, and you cannot (ar at least, you are not
supposed to) change a literal string. The compiler should warn you on
that... if you enable compiler warnings.

  strcat(res ,num);

This is very wrong. strcat() expects as its first argument an pointer
to a modifyable array large enough for the resulting concatenation
(and the terminating \0). In other words, you have to allocate enough
room for the whole string, then fill the beginning of the allocated
array with the first substring, then only call strcat():

char res[24];
strcpy(res, "up_cmd0_res:");
strcat(res, num);

What happened is that you initially had, in memory, something like this:

<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' NUL
 ^-- res

On the first call to stracat(), you overwrite the terminating NUL and
end up with

<----- memory reserved for the string literal ---->
'u' 'p' '_' 'c' 'm' 'd' '0' '_' 'r' 'e' 's' ':' '8' NUL
 ^-- res

Note that the new terminating NUL is now occupying a byte in memory that
hasn't been allocated for this purpose. You have likely overwritten some
global variable. Next time you call strcat(), you again replace the
terminating NUL and continue to overwrite whatever happens to be stored
in this part of the RAM. Expect a crash or program misbehavior.


strtok() is a destructive function. It replaces the token with an end-of-string marker (\0). Thus once used the original string is irevocably lost.

Your first use of strtok() changes the string from:

*CRB12344,Temp25,Humidity55,CC5#\0

to:

*CRB12344\0Temp25,Humidity55,CC5#\0

Thus any future references to InputString only see up to the end-of-string marker:

*CRB12344\0

Instead you should use strtok() in a while loop to slice the string into tokens and examine what the token is:

char *tok = strtok(IncomingString, ",");
while (tok) {
    if (strncmp(tok, "*CR", 3) == 0) { // tok is *CRB1234
        // ... whatever ...
    } else if (strncmp(tok, "Temp", 4) == 0) { // tok is Temp25
        // ... whatever ...
    } else if (strncmp(tok, "Humidity", 8) == 0) { // tok is Humidity55
        // ... whatever ...
    } else if (strncmp(tok, "CC", 2) == 0) { // tok is CC5#
        // ... whatever ...
    }
    tok = strtok(NULL, ","); // Note: NULL, not IncomingString
}


Why I could not read the other sms's except the first SMS?

It looks like RcvdEnd never gets reset back to zero because RcvdConf is set to zero when RcvdEnd is 2, which means it will never get to 3 and reset it (at least not when you are expecting it to). I'm not sure how many new lines you are supposed to be checking for but the way it is set up now or is looking for two on the first message, and three for every message thereafter. You might want to rework the logic and maybe move where that value gets reset.


AMIS30543 | DataSheet Understanding CIRCULAR TRANSLATOR TABLE

1. It describes the current going through the two coils of the stepper motor at each step.
2. I'm not quite sure, as I I would think the last two diagrams should actually be squares. But for example in the first image you can see that the current in the X coil will steadily increase, while the current in the Y coil will steadily decrease. This will make the stepper rotate more slowly.
In the second image you can see that only the Y coil driver at 100% in step 0. In step 1 both coils are at 100%. In step 2 coil Y is turned off. I think this is profile produces more torque, but is less smooth.
3. No. I you are, for example using full step mode, and the motor is in step 0. If you give it 3 steps forward  (while the motor is disabled) it would drive the coils (once you re-enable to motors) as describe in the lookup table for step 3. Which in practice would mean the motor would rotate backwards one step (instead of 3 steps forward).
In other cases it could result in undefined behavior. Going from step 0 to step 2 could mean if would rotate clockwise, anticlockwise, or even not rotate at all.
Though in practice I don't think this you would even be in issue, and disabling the motor, but still sending it step pulses is kind of silly.


Don't get discouraged, there are many ways to do this, but I would rate a PIR as being one of the worst options because even a bird or a squirrel could set it off. Plus, once the car has stopped you can't detect it's presence anymore with a PIR sensor, it has to be moving. I would recommend either using something like a webcam and OpenCV for this or if you're set on using an Arduino and physical sensors, multiple laser or multiple ultrasonic sensors placed 5-10 feet apart so that they both have to trip at once for positive detection of a vehicle instead of something else. You're going to have to spend some time experimenting and tuning. If you want something very reliable and you own the place, you could always do what the public street works does and cut a loop into the pavement and install a large steel cable and use inductance, but that may be overkill. ;)

Some other ideas:

Paint a pattern on the ground using high contrast paint and detect
when the pattern is completely covered.  Maybe there is something you
can do with IR reflective paint and use a camera with no IR filter,
this way you could make a pattern invisible to the eyes.
A carbon monoxide detector - Detects dinosaur powered vehicles, but
is nice to the environmentally conscious.

About a decade ago now I created my own parking detection using a Raspberry Pi and a webcam and some Perl code I wrote (non-opencv). I basically just detected the shadow contrast under the car and it worked very well. Originally I tried detecting red colors in the tail lights, but this was more troublesome due to other lighting in the environment. Especially at night. In my case, I didn't have direct access to set up physical sensors and lasers would have been too intrusive, so visual analysis made sense.


Why does my 23,032 byte Arduino sketch take 36.32 sec to upload via ISP to an Atmega328p on a breadboard w/code verification disabled?

ISP programmers typically default to low ISP clock rates.  Often something like 10khz, sometimes slower, probably to just work by default with very slowly clocked AVR chips.  The ISP clock rate must be about one eigth that of the AVR's clock.  For example, by defaulting to a low rate like 10Khz, the programmer will successfully communicate with an AVR clocked at 125KHz with some margin.   Around 4 KHz would work with a 32.768 KHz watch crystal.
Look in avrdude documentation for the -B option.  Note uppercase 'B', this is the option for changing the ISP speed, not lowercase -b which is for the PC to programmer (or bootloader) baud rate.   Not all programmers support -B, but many do.
UPDATE
Well, I dug around the USBtinyISP code and in avrdude and it looks like the default value for -B is 10.  So 10uS.  The way this value is used in the USBtinyISP code is for high or low period, rather than total clock period.  So it's about 20uS per bit, or 50kHz.  If that's your rate, then the plain clocking of the SPI data only accounts for about 3.7 seconds.  So that does cast doubt on this idea.
But, it still may be worth double checking that it is operating with the value 10 and not something larger.  Just to put this in perspective: the maximum -B value is apparently 250, which would result in 2kHz ISP clock rate and about a minute and a half to clock out your roughly 23 KByte.
More findings: Per byte SPI overhead
Each byte of the flash pages is being delivered into the ISP interface by way of 4-byte long SPI commands.  The firmware for the programmer has the following code in it for writing a page in its spi/main.c file where you can see it calling spi( cmd, res, 4 ) :
extern  void    usb_out ( byte_t* data, byte_t len )
{
    byte_t  i;
    uint_t  usec;
    byte_t  r;

    for ( i = 0; i < len; i++ )
    {
        cmd[3] = data[i];
        spi_rw();
        cmd[0] ^= 0x60; // turn write into read
        for ( usec = 0; usec < timeout; usec += 32 * sck_period )
        {   // when timeout > 0, poll until byte is written
          spi( cmd, res, 4 );
            r = res[3];
            if  ( r == cmd[3] && r != poll1 && r != poll2 )
            {
                break;
            }
        }
    }
}

This code is used to deliver data to the flash page buffer during ISP programming.
You can see a comment in avrdude's code explaining that each byte becomes a 4-byte SPI transaction as an aid to explaining their calculation for a communications timeout with the programmer.  The following is in avrdude's usbtiny.c file for the usbtiny_paged_write function.
if (usb_out(pgm,
            function,       // Flash or EEPROM
            delay,          // How much to wait between each byte
            addr,           // Address in memory
            m->buf + addr,  // Pointer to data
            chunk,          // Number of bytes to write
            32 * PDATA(pgm)->sck_period + delay  // each byte gets turned into a
                                 // 4-byte SPI cmd  usb_out() multiplies
                                 // this per byte. Then add the cmd-delay
            ) < 0) {
  return -1;
}

To be clear, these two functions have the same name but are in fact two different functions; the former running in the programmer the later is running in avrdude.
So there is in fact substantial SPI transaction overhead in just delivering data into the page buffer.  Beyond that there's a second USB and SPI transaction to commit the page buffer to flash.


Value read is not changing while rotating pot in arduino?

OK, I am unable to leave a comment (< 50) so...

Use this link to learn about the AREF pin on the Arduino, this may not be your problem but it is good to know about anyway:
what is arduino adc reference?

Your pot MAY be broken. Measure the resistance of the pot with an ohm meter, from the center pin to either of the side pins. Verify when you turn it the resistance varies from 10K to 0.

You can also measure the voltage it is providing your Arduino by measuring the voltage it presents to pin A0. Verify the voltage changes little by little from +5 to 0 when you turn it back and forth.

You list the pot as being a "bourns 3296" which the data sheets show as a "Multiturn / Cermet / Industrial / Sealed" pot.

Just so you know, when you adjust it you will have to turn it 25 turnes to fully adjust it through its entire range. The data sheet shows "Effective Travel.........25 turns nom."


Visual clock with millisecond display refresh rate

You need to define the parameters of the problem more clearly.

First, and most importantly, what is the shutterspeed you'll be using? If it's longer than 1 ms, then you can't use a 7-segment display to show the MS count, since the camera shutter would be open for multiple values.

Even if your shutterspeed is a single MS, your shutter won't be synchronized with your timer, so sometimes the shutter will be open when the display switches. That can even happen with the seconds digit of your time display.

If you're using a video camera, assume the frame rate is 60 fps, which gives a likely shutterspeed somewhere around 16.6 ms. That's way too long to display ms time values using 7-segment displays.

The ring of LED idea is good, but I would tweak it.

Here's what I would do: Build an LED clock to display whole number seconds. Don't multiplex, use latches and drive each 7-segment display constantly. (There are off-the-shelf CMOS chips that are latching 7-segment drivers.) If you only care about the 1s digit of the second value, only use 1 7-segment display. That will make things easier to wire.

Use 3 rings or columns of 10 LEDs for the MS display: tenths, hundredths, and thousandths. I would lean towards using columns since it would be visually easier to read.

The display will show your seconds as numbers, and 3 columns of 10 LEDs, showing the sub-second time range in 10ths, 100ths, and 1000ths. If the shutter opening spans multiple MS, as it will very likely do, all the LEDs that represent the sub-second time will be lit in the image, so you will get a nice clean visual image of the time SPAN that the shutter was open (All the LEDs from the start to the end of the shutter opening will be lit.)

You could drive the 3 columns of LEDs using 3 4017 divide-by-10 counters. These chips have both a 1-of-10- output, which will drive an LED, and a count/10 output, which would feed the next stage.

Write Arduino code that generates a short positive pulse every MS. Feed that into the clock input of the 4017 driving the thousandths digit. Feed the out/10 output of that chip to the clock input of the hundredths 4017, and the output of the hundredths 4017 into the clock input of the tenths 4017.

You can drive the whole ms display with 2 Arduino lines: The ms clock, and a reset line tied to all your 4017 counters' reset lines. To start timing, first pulse the reset line to zero them all out, then start your ms clock.

My CMOS cookbook doesn't say how much current the 4017 will put out to it's 1-of-10 outputs, but I bet it's enough to drive a display LED directly. You could wire all 10 LEDs in each column as common cathode, with a single current limiting resistor between each column's common cathode and ground.

You could probably set up a timer pin on the Arduino to generate a millisecond pulsed output, but that's not something I've learned how to do yet.

Occasionally you'll get a whole second 7-segment display with 2 different values captured in a frame, but that will be rare, and you will be able to figure out what happened from the frames immediately before and after it. (Previous frame shows a 5. Current frame shows a 5 and a 6 superimposed, so it's a mess. Conclusion, this frame shows the end of second 5 and the beginning of second 6.)


Sim800l gsm module cannot connect gprs data

I get it now , a stable power source is the answer. arduino with usb can give right amount of Volts but it lacks stable power(amps i guess) while making a TCP connection, that's why module keep restarting.Although it works fine with call, text etc. powering arduino with an AC adapter solves my problem ,now it can connect to mqtt too.Thanks


Hello,
You need to set a channel to both NRF:

void setup() {
   delay(500);
   Serial.begin(9600);
   radio.begin();
   radio.setChannel(0x55); //set the channel
   radio.openWritingPipe(0xF0F0F0F0AA);
   radio.setPALevel(RF24_PA_MIN);
   radio.stopListening();
   radio.powerUp(); //Power up the radio
}

Change this.

void loop() {
    if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
    }
    if (done) {
        Serial.println(response);
        done = false;
    }
    //done = false;
    delay(1000);
}


Arduino -> Processing conversion: creating mux channels

When making an array I processing you must use the code

int[] xyz = \*declare variable or new*\ {
    this is some code
}

You used

int xyz[num][num]

You must declare the values of the array only after declaring it.
Also, did you try declaring digitalWrite as a new variable?


Where in datasheet is the warning about unreliability of reading PINxn?

did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.

However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use pinMode() and digitalRead() instead of
direct port access, you too will find the internal pullup is perfectly
fine.

Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:

main:
    sbi  PORTB, PB5 ; turn on pullup on PB5
    sbi  DDRB,  PB0 ; set LED pin as output
    sbis PINB,  PB5 ; read PB5, if it is LOW then:
    sbi  PORTB, PB0 ;   turn on LED
0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for sbis, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:

cycle   instruction   pullup latch PINB5
----------------------------------------
   1   sbi PORTB, PB5   off    X     X
   2      cont.         off    X     X
   3   sbi DDRB,  PB0   on     X     X
   4      cont.         on    LOW    X
   5   sbis PINB, PB5   on     X    LOW
   6   sbi PORTB, PB0   on     X     X
   7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the next CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.

Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!

By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about three picofarads is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
before you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.

The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

  where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay.”
(emphasis mine).

Edit: In a previous version of this answer, I incorrectly stated
that sbi is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

In summary:

The stray capacitance attached to the pin, together with the pullup
resistor, for an RC circuit.
As the pin is initially floating, it's initial voltage is
unpredictable.
When the pullup is turned on, the voltage starts to rise from whatever
initial value it had to 5 V.
After some time, which can be typically of the order of the RC time
constant, the input Schmitt trigger turns HIGH.
After some extra delay introduced by the synchronizer, the PINxn
flip-flop turns HIGH.
If the CPU reads the PINx register before that happens, it gets a LOW
reading.


What device do I add in order to detect if my project is moved?

There's two basic ways of detecting vibration - one which is quantifiable and one which isn't (much).

The simplest way is a sprint (possibly weighted) inside a metal tube. Vibration causes the spring to move and touch the tube - the resultant circuit is just the same as using a button. Sensitivity can't be controlled (other than maybe "how many times in a given period does the spring touch the tube"), but it's very very simple to use. They are often used in simple movement alarms (for things like bikes, etc).

The second method is to use an accelerometer. These are harder to work with but they do give you the actual amount of vibration at any given time. They are far more sensitive than a simple spring+tube, but since they are an active component they need to be constantly queried (often through I2C or an analog input). That makes them harder to use in a low-power scenario.

Some accelerometers are more intelligent and can be programmed to trigger an interrupt when vibration above a certain level is detected, though again that increases the complexity of working with them.

So in short: the lowest power option is the simple spring+tube sensor - it uses zero quiescent current. The best option is a programmable accelerometer that can trigger an interrupt to wake the main MCU. Which you choose depends on how sensitive you need the device to be...


As said by @Mikael Patel
You need to append .c_str() to u8g2.drawStr(1,10,WiFi.macAddress()); creating the line: u8g2.drawStr(1,10,WiFi.macAddress().c_str());

The problem is that WiFi.macAddress() returns a String not the needed const char* by the drawStr function. c_str converts the String object into a const char*.

Please look at the documentation of the u8g2 library for the drawStr function.

link

And here the documentation for String

link


SoftwareSerial response is semi-gibberish using ESP8266

Try lowering your baudrate to 9600.

https://blogs.msdn.microsoft.com/abhinaba/2016/01/23/esp8266-wifi-with-arduino-uno-and-nano/


Nothing received from function returning array of strings

You can't return locally defined arrays like that. The array only exists in the function, and all you do is return a pointer to where that array was. As the array has gone when you leave the function your pointer just points to garbage.

Instead you should pass an array to the function that the function then populates.


The following code is not very "clean" but easy to understand. Use a variable to hold the day, you have already printed and check in which interval you are. If you change the 2 day interval print a message and set the actDay variable to the number of the day you have already printed; to avoid repprinting it again.
int daytwo = 25920;
int dayfour = 44400;

int actDay = -1;

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis < daytwo)
  {
    if ( actDay != 0 )
    {
      actDay = 0;
      Serial.println("dayzero");
    }
  }
  else if (currentMillis < dayfour )
  {
    if ( actDay != 2 )
    {
      actDay = 2;
      Serial.println("daytwo");
    }
  }
  else
  {
    if ( actDay != 4 )
    {
      actDay = 4;
      Serial.println("dayfour");
    }
  }
}


It is handed the addresses when the object is constrcted:

 HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

&UDR is passed as *udr. That is then assigned to _udr in the initialiser list.


Where is the inaccuracy of my arduino thermistor circuit coming from?

Why are you using the voltage divider and measuring by parts? As @nickgammon points out, you are measuring only a 1/5 of full scale at each measurement, meaning your resolution is down by 5:1 over what the A/D is capable of. Also, the divider network comes to around 500KOhms. Work out the current through that and you get a very feeble <7 microAmps. The wires are antennas that could well be contributing noise at a significant fraction of that level.

Is there a reason for the divider circuit? Could you use a single thermistor from Vcc to Gnd plus a resistor in a 2-way divider? That will have the advantages of:

Using (more of) the full range of A/D;
Taking only one reading instead of several (and the several are necessarily skewed in time since you're multiplexing the one A/D);
A larger current (ok, only 33 microAmps, but 5x better than before);
Presumably less pickup into the network than with 5 leads. Keeping the measurement lead as short as possible may help, too.

Update:

Then you probably want a 2-component divider for each temperature you need to measure, paralleled between the power rails. I just guessed, not calculated, the resistances of R1, R3, R5, & R7. You'll want to estimate the maximum and minimum temperatures of interest in each channel and pick values that will give you the best ranges without drawing excessive currents when the thermistor values are low.

simulate this circuit – Schematic created using CircuitLab


Can an arduino tell between being powered by USB or by the jack?

No, you can't do it without extra hardware.

You need to pass VIN through a voltage divider so it sits within 0-5V when powered by 12V, then feed that into an ADC input. Protect the on-board voltage regulator with a diode between 5V (anode) and VIN (cathode). Then you can measure the voltage on VIN and make a decision on if it is around 4.5V or 11.5V

A 22K/10K voltage divider will reduce 12V down to 3.75V, which gives plenty of "headroom" for over-voltage situations (where your 12V unregulated power supply actually provides, say, 15V):


Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:

period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency

frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an even number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:

const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set PERIOD to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

Edit: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the Trinket or the Digispark.

This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:

64 MHz ÷ 38 = 1.684 MHz


Extracting a substring from original string

Let's dissect your program a moment and see why it's not doing what you want:

while (Serial.available() > 0)
{

So while there are characters available to read in the serial buffer

  rfid = Serial.read();

read one character into the rfid variable.

  String cardnum(rfid);

Convert that character into a string.

  cardnum.replace("", "");

Replace nothing ("") with nothing ("")

  cardnum.replace("", "");

Do the same again,

  String id = cardnum.substring(0,2);

Take the first two characters of the string that contains the single character that you have read.

  Serial.print(id);

Print it.

So basically you have read one character, made it into a string, done nothing to it, copied it to another string, then printed it.

Instead of this method, which does nothing useful, you should read the whole ID into a string (I'd use a C string [i.e., char array] rather than an Arduino String object) then perform operations on that string once you have read the whole ID code.

There's many methods of doing that, but how you do it is heavily influenced by exactly how the data is presented to you. Does it have a terminating CR or LF to indicate the end of the string? If not you will have to use some form of timeout to determine when the string has been completer.


You are overflowing your buffer, and also allowing garbage reads.

First you need 5 bytes for your buffer not 4, and you need to ensure it is zeroed out before using it. This is because you are treating it like a C string, which means it must b zero terminated.

Secondly your use of Serial.readBytesUntil() is flawed.  From the manual:

  The function terminates (checks being done in this order) if the determined length has been read, if it times out (see Serial.setTimeout()), or if the terminator character is detected (in which case the function returns the characters up to the last character before the supplied terminator).

You are sending 5 bytes (1058\n) but telling it to read up to 4. Which leaves the \n in the buffer. The next time through you read another 4 bytes, which gives you \n which is the terminating character.

If you must use readBytesUntil then you need to specify a buffer that is bigger than the whole string including the terminator so that the terminator always occurs before the maximum number of bytes read. Including the trailing zero you would thus need at least 6 bytes in your buffer, maybe a couple more "just in case" (one can never tell with Arduino API functions...)

So to roll it all up:

  char buffer[8]; // <- Bigger buffer
  memset(buffer, 0, 8); // <- Clear it out
  int deger = 0;
  if (Serial.available() > 0) {
    int size = Serial.readBytesUntil('\n', buffer, 7); // <- Tell it to read more leaving room for the terminating NULL
    ... etc ...

if (size == 4) {


The problem here is that there are multiple flavours of linux each with their own installation and package management systems - Aptitude, Yum, EMerge, etc.

It is not easy for Arduino to keep up with creating packages for each and every system, so instead they create a single tarball that can be used on any of the systems.

At one point Arduino (or someone, anyway) used to create Debian packages for the IDE and upload them to the main Debian repository - however this has not been done for many years now and the packages in the Debian repositories are very much out of date (1.0.5 IIRC).

If you, as a system manager, choose to deploy the IDE system wide then it is your task to decide how best to do that.

One option is to just copy the contents of the archive to /usr/share/arduino and then run ./install.sh from within that directory.


I'm looking for a way to emulate addressable LED strip using LED diodes in a custom arrangement

You can buy individually addressable LEDs like the ones in LED strips. If you are fairly new to electronics I would not try to build your own serial LED controller.


Yes, it is possible, and not too difficult. Also, the native port is a lot faster than the programming  port ;)
All you need to do is to read the serialUSB data in and write it to the SerialX port, and read the data in from the SerialX port and write it to the SerialUSB port. It's best to do it on a byte by byte basis, and the due should be plenty fast enough.
This code should do the job. Let me know if it doesn't, and I'll take a look. (I have a Due and esp32)

void setup(void) {
  SerialUSB.begin(9600); //speed here doesn't matter as far as I am aware.
                         //the serial baud here should match the speed that
                         //you try to upload at to the esp32
  Serial1.begin(9600);   //change the Serial port to suit your needs
}
void loop(){
   if(SerialUSB.available()> 0){
    Serial1.write(SerialUSB.read());
   }
   if(Serial1.available()> 0){
    SerialUSB.write(Serial1.read());
   }
}


Can I read two PWM signals and output two square waves on an UNO?

Your signals are slow enough that you may not need any timer. You can
just use the Arduino micros() function to handle all your timings. Of
course, micros() itself relies on Timer 0, but you don't need to
access any timer directly.

I would use the external interrupts in CHANGE mode to measure the duty
cycle. For example:

const uint8_t INPUT_0_PIN  = 2;  // digital 2 is also INT0
const uint8_t OUTPUT_0_PIN = 4;

// Measured duration of the HIGH level of input 0.
static volatile uint32_t input_0_high_time;

// Interrupt handler invoked when input 0 toggles.
static void on_input_0_change()
{
    static uint32_t time_rise;             // last time the signal rose
    uint32_t now = micros();
    if (digitalRead(INPUT_0_PIN) == HIGH)  // detected rising edge
        time_rise = now;
    else                                   // detected falling edge
        input_0_high_time = now - time_rise;
}

void setup()
{
    pinMode(INPUT_0_PIN, INPUT);
    pinMode(OUTPUT_0_PIN, OUTPUT);
    attachInterrupt(0, on_input_0_change, CHANGE);
}

For handling two inputs, you can duplicate everything that has a 0 in
its name and name it with a 1. If your signal is no slower than
60 Hz, you can also replace all uint32_t by uint16_t to make
the code slightly faster.

For generating the outputs, do something similar to the Blink Without
Delay example:

void loop()
{
    uint32_t now = micros();

    // Determine suitable period for output 0.
    uint32_t input_0_high_time_copy;
    noInterrupts();  // avoid race condition while reading
    input_0_high_time_copy = input_0_high_time;
    interrupts();
    uint32_t output_0_half_period =
            map(input_0_high_time_copy, 0, 16666, 8333, 500e3);

    // Toggle output 0 when needed.
    static uint32_t time_output_0_toggle;
    static uint8_t output_0_state;
    if (now - time_output_0_toggle >= output_0_half_period) {
        time_output_0_toggle += output_0_half_period;
        output_0_state = !output_0_state;  // toggle state
        digitalWrite(OUTPUT_0_PIN, output_0_state);
    }
}

Again, you can handle two outputs by duplicating the code and replacing
0 with 1. Note that you cannot replace uint32_t by uint16_t,
as it would not work for the slowest frequencies.

Edit: Now we may ask the question whether it is possible to use some
timers to make all this more accurate. The answer is yes, you could
achieve maximum accuracy by using four 16-bit timers:

You could use the input capture function of a 16-bit timer, with the
prescaler set to 8, to measure the transitions of one of your
inputs with a resolution of 0.5 µs.
You could use a 16-bit timer in CTC mode, with the prescaler set
to 256, to toggle one of your outputs at the desired frequency, with a
16 µs resolution.

For reference, micros() has a resolution of 4 µs. The 16 µs
resolution of the timer-generated output seems poor in comparison, but
the timer has the advantage of having zero jitter.

Now, for doing that that, you would need an Arduino Mega 2560. The Uno
has only one 16-bit timer, so it could help with only one of your two
channels.

There is still something you can do with a single 16-bit timer. Set it
to normal counting mode, with the prescaler at 8, and use it
instead of micros() for timing your inputs: in setup()

// Configure Timer 1.
TCCR1A = 0;          // normal counting mode
TCCR1B = _BV(CS11);  // clock at F_CPU/8

and in the interrupt handler, you replace uint32_t now = micros(); by

uint16_t now = TCNT1;

And now you have input_0_high_time (which should also be uint16_t)
in units of 0.5 µs.


Creating a library for attiny85 out of working program

I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc.

Code

In the interests of answering the question though, this works:

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }

void setup()
 {
  pinMode (4, OUTPUT);  // chip pin 3

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare

  }  // end of setup

void loop()
  {
  // other code here
  }

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.

Prescaler values

From the datasheet:

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.

The delay is then:

125 ns * 256 * 124 = 3.968 ms

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

Flashing more slowly

If you put an LED on pin 3 and want to see the flashing, you need it much slower. For example:

TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13);  // prescaler: 16384

That toggles the pin every 254 ms, which is visible.

Warning

On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.

More information

Timers
Interrupts


The device sending the request has no bearing on if it is HTTP 1.0 or 1.1. Only the content has an effect.

That and what is in the path - and I suspect that may be your problem: your are going through a squid proxy - and an old version at that. It is most likely that the proxy is changing the request to be a 1.0 request instead of a 1.1 request.


Disassembling the delay code indicates it uses micros which needs interrupts on to work.

void delay(unsigned long ms)
{
 27a:   cf 92           push    r12
 27c:   df 92           push    r13
 27e:   ef 92           push    r14
 280:   ff 92           push    r15
 282:   cf 93           push    r28
 284:   df 93           push    r29
 286:   6b 01           movw    r12, r22
 288:   7c 01           movw    r14, r24
    uint16_t start = (uint16_t)micros();
 28a:   d3 df           rcall   .-90        ; 0x232 <micros>
 28c:   eb 01           movw    r28, r22

    while (ms > 0) {
 28e:   c1 14           cp  r12, r1
 290:   d1 04           cpc r13, r1
 292:   e1 04           cpc r14, r1
 294:   f1 04           cpc r15, r1
 296:   79 f0           breq    .+30        ; 0x2b6 <delay+0x3c>
        yield();
 298:   ea d0           rcall   .+468       ; 0x46e <yield>
        if (((uint16_t)micros() - start) >= 1000) {
 29a:   cb df           rcall   .-106       ; 0x232 <micros>
 29c:   6c 1b           sub r22, r28
 29e:   7d 0b           sbc r23, r29
 2a0:   68 3e           cpi r22, 0xE8   ; 232
 2a2:   73 40           sbci    r23, 0x03   ; 3
 2a4:   a0 f3           brcs    .-24        ; 0x28e <delay+0x14>
            ms--;
 2a6:   81 e0           ldi r24, 0x01   ; 1
 2a8:   c8 1a           sub r12, r24
 2aa:   d1 08           sbc r13, r1
 2ac:   e1 08           sbc r14, r1
 2ae:   f1 08           sbc r15, r1
            start += 1000;
 2b0:   c8 51           subi    r28, 0x18   ; 24
 2b2:   dc 4f           sbci    r29, 0xFC   ; 252
 2b4:   ec cf           rjmp    .-40        ; 0x28e <delay+0x14>
        }
    }
}
 2b6:   df 91           pop r29
 2b8:   cf 91           pop r28
 2ba:   ff 90           pop r15
 2bc:   ef 90           pop r14
 2be:   df 90           pop r13
 2c0:   cf 90           pop r12
 2c2:   08 95           ret

That appears to confirm that the code in wiring.c is indeed what is being used on the ATtiny85 core:

void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Turning interrupts off and then doing a delay is a Bad IdeaTM.

  So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.


Make sure you are using a software serial port for the GPRS shield.

If you aren't using the software serial port, then you are probably running into an issue with trying to read data over the only UART (serial) port while two devices are tryiing to use it.

It looks like there are two jumpers next to D0/D1 on the GPRS shield, I can't tell but I think if you remove those, the shield will use software serial over D7/D8.  If you do this, you'll have to code your program to use a software serial.  This wiki page on the GPRS shield if you need help with that.


If I am understanding correctly, you have 3 LEDs ... call them A, B and C (the fact that they are a group of 14 LEDs is a red herring).  As a function of the distance measured, you want ONE of LED A, B or C lit.

Since you are using an Arduino, you have GPIO pins.  Connect a different GPIO to each of A, B and C.   You can then write an application that senses the distance (as measured by the HC-SR04) and depending on the distance returned, have a set of  "if" statements which will choose which of the GPIOs to set HIGH and the others LOW.  The GPIO set HIGH will switch on the corresponding LED.

In fact, its going to look a lot like this Instructable:

http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/


How does one use (specically the wiring) the OV7670 camera with the Arduino Uno?

You need to connect A4 and A5 via pullup register to 3V and to I2C interface on Arduino Uno.
And you need to connect A7 to XCLK signal via 2 registers.

You can find schema and code in my blog: How to connect Arduino Uno and OV7670


RPM measurement using quadrature encoder

Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation

Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.

You are calculating revolutions per second with your code, not per min
number of pulses/400(if this is correct number)=Revolutions     which you are clearing ever 1000ms

Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.

Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection,   ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.


For the stepper motors, the easiest way to work with them is by using a very common A4988 board which is widely used with 3D printers. The controls are very easy and for them I send you this question which I answered some time ago.

Then, you say that you haven't got a lot of connections left on your UNO board, so I think that SPI would't be very useful, as it takes 3 pins for the data transmission (SCLK, MOSI, MISO) plus one pin for every device you connect.

The best way (even if it is a little slower that SPI) is to use I2C, which needs that you leave unused analog input pins A4 and A5, as they are the I2C BUS. Unfortunately I haven't any knowledge about I2C DC motor drivers.

For the steppers, I suggest to take a look at this, but it depends by your budget for what you can buy.

You could fix the pin shortage problem by adding some 74HC595 shift registers. They aren't very expensive (less than a dollar, or if you live in europe, .5€) and they can be daisy-chained. To control them, see the Arduino website tutorial.

Finally, if the pins that you use are inputs, use a 74HC165, which is the opposite of a 595. As always, see the Arduino website tutorial.


Cannot get pins on esp 8266 adafruit wifi module to read HIGH on pin 15

Pin 15 is one of the boot configuration pins (0, 2, 15) and must be LOW at boot. To ensure it, dev boards with esp8266 have external pull-down on pin 15 (and pull-up on 0 and 2). To read the pin HIGH you must overcome the pull-down.

Adafruit Feather HUZZAH has 4.7kOhm resistor for the pull-down, so it is a 'strong' pull down. NodeMcu has 12kOhm resistor on io 15.

From schematics of Adafruit Feather HUZZAH

Note: setting pin as OUTPUT and HIGH doesn't make it read HIGH in code. Only INPUT pin state can be read with digitalRead (only on some MCUs digitalRead reads the same register set by digitalWrite).


itoa is the best route:

int num = 1234;
char cstr[16];
itoa(num, cstr, 10);
-> "1234"

You can read more about using it here.

If you want more control over the format of the number (and don't mind the increased PROGMEM usage) you can use sprintf (or the more secure snprintf) to format it:

sprintf(cstr, "%05d", num);
-> "01234"

Or with PROGMEM string constant:

sprintf_P(cstr, (PGM_P)F("%05d"), num);
-> "01234"

Or with more values:

sprintf_P(cstr, (PGM_P)F("%02d:%02d:%02d"), hours, minutes, seconds);
-> "03:23:11"


The data sheet for the Siemens TC35 says "The  data  interface  is  implemented  as  a  serial  asynchronous  transmitter  and  receiver conforming  to  ITU-T  RS-232  Interchange  Circuits  DCE.  It  operates  at  CMOS  level  (2.65V).
All RS-232 signals on the ZIF connector are low active."

this is actually a low-voltage  equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).

Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.

Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

  will this be possible by stacking the modules on one arduino?

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.

If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.


use this:

attachInterrupt(wakeUpPin, wakeupFunction, HIGH);
    USBDevice.detach();
    SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
    __DSB();
    __WFI();

void wakeupFunction(){
  NVIC_SystemReset();
}


Arduino Nano and SIM800L on Battery Power

Check out

  Thin battery to power arduino micro with nRF8001?

Also, I found a 6v battery (A544) at Menards that is about the same diameter as a AA, but is considerably shorter. It has 178 mAh capacity.

I haven't taken the time to test it, but I would guess it wouldn't have as much of a temperature issue.

It's not as small as the CR2032 in the above mentioned link, nor is it flat, but it's an option.

You might consider an Arduino Beetle. They are really super incredibly tiny and still 16mHz. I can't get any more info from where I'm at, but I'd believe they would use even less power than a Nano/Micro.

I found an Instructable that shows how to use a Beetle, a rechargeable 3.7v LiPo battery, and an HC-06 Bluetooth module. Sounds like it's equivalent to what you're looking for.

http://www.instructables.com/id/Beetle-Minimize-Your-Arduino-Projects/