Can I improve this code (replacing delays with something else)? Building upon my previously solved question Ultrasonic Sensor range finder help (Solved).

Is there a better way to make the LED blink than using a delay and stopping all the rest of the code? For example, the LED is set to turn on, then shortly after turn off. Is there a better way to do this?

For example, if the LED is turned on, it then delays the code, which means it has to wait for the delay to be over, turn off, then change its pattern. For example, allow the Arduino to interrupt the blink with a new interval blink, mid blink? I'm sorry if this is confusing, it's tough to explain.

Simply put, is there a better function than delay() that can allow the Arduino to suddenly change the state of the LED while it is waiting on a delay() to finish?

The code I'm working on is this:

#include <NewPing.h>
#define TRIGGER_PIN  15
#define ECHO_PIN     2
#define MAX_DISTANCE 500
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
}

void loop() {
  delay(50);
  unsigned int uS = sonar.ping_median(10);
  int IN = sonar.convert_in(uS);
  if (IN <= 5) {
    analogWrite(LED4, 255);
    delay(100);
    analogWrite(LED4, 0);
  } else if (IN >= 5 && IN <= 12) {
    analogWrite(LED4, 1);
    delay(200);
    analogWrite(LED4, 0);
  } else if (IN >= 13) {
    analogWrite(LED4, 100);
    delay(300);
    analogWrite(LED4, 0);
  }
}

You can use millis() to get a timer:
millis() Returns the number of milliseconds since the Arduino board began running the current program.

void loop(){
    if(millis() % 100 == 0){//%(modullo) is the rest of a division. 19%10=9 because10/10 = 1 and the rest is 9
        //you have wait 100 millisecond. When millis()%100 == 0 millis() is a multiple of 100.
    }
}

For your code you can do this:

int LED1 = 3;
int LED1 = 3;
int LED2 = 16;
int LED3 = 9;
int LED4 = 6;

//Ligth on -> 1 light off -> 0
int LED1Stat = 0;
int LED2Stat = 0;
int LED3Stat = 0;
int LED4Stat = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(LED1, OUTPUT);    //every 100 ms
  pinMode(LED2, OUTPUT);    //every 250 ms
  pinMode(LED3, OUTPUT);    //every 500 ms
  pinMode(LED4, OUTPUT);    //every 1000 ms

}

void loop() {
    //for no Delay
    if(millis()%100 = 0){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
    }
    if(millis()%250 = 0){
        LED2Stat = !LLED2Stat;
        digitalWrite(LED2, LED2Stat);
    }
    if(millis()%500 = 0){
        LED3Stat = !LED3Stat;
        digitalWrite(LED3, LED3Stat);
    }
    if(millis()%1000 = 0){
        LED4Stat = !LED4Stat;
        digitalWrite(LED4, LED4Stat);
    }
}

[EDIT]

long prevMillis = 0;
void loop(){
    if(millis()-prevMillis >= 100){
        LED1Stat = !LED1Stat;
        digitalWrite(LED1, LED1Stat);
        prevMillis = millis();
    }
    //...

}


lcd.print then dataFile.print My program is a bit large and I'm worried about stability.

I need to print data to both a file and to my LCD. It's like this:

if (hour<10) {
    dataFile.print("0");
}
dataFile.print(hour, DEC);
dataFile.print(":");
if (minute<10) {
    dataFile.print("0");
}
dataFile.print(minute, DEC);
dataFile.print(":");
if (second<10) {
    dataFile.print("0");
}

Then

if (hour<10) {
    lcd.print("0");
}
lcd.print(hour, DEC);
lcd.print(":");
if (minute<10) {
    lcd.print("0");
}
lcd.print(minute, DEC);
lcd.print(":");
if (second<10) {
    lcd.print("0");
}

What is a smart way to make this shorter? Should I write a function to add the leading zero then another that does something like:

void printboth (thing) {
    dataFile.print(thing);
    lcd.print(thing);
}

good idea?

You could format the data with snprintf:

char timestamp[9];
snprintf(timestamp, 9, "%02d:%02d:%02d", hour, minute, second);
dataFile.print(timestamp);
lcd.print(timestamp);

%02d in the snprintf format means "print at least 2 digits of this value and pad with leading zeros".


When a pushbutton and sensor are in a certain state, do something for a certain period of time (15 seconds) I have a sketch that contains code for an analog input (FSR sensor), a pushbutton, and 6 blinking LEDs.

Currently, the sketch is written to allow the LEDs to blink only when the button is pressed and there is sensor input.

Can someone help me write code to make the LEDs blink for a certain period of time once there is input from the analog sensor and while the button is pressed?  I am trying to make the LED blink for 15 seconds and then turnoff.

thank you!

/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;
const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup() {
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);
  pinMode(buttonPin,INPUT);
  pinMode(SensorPin, INPUT);
}

void loop() {
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

if (SensorPinReading < 10) {
  Serial.println(" - No Pressure");
} else if (SensorPinReading < 200) {
  Serial.println(" - Light Touch");
} else if (SensorPinReading < 500) {
  Serial.println(" - Light Squeeze");
} else if (SensorPinReading < 800) {
  Serial.println(" - Medium Squeeze");
} else {
  Serial.println(" - Big Squeeze");
}

  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && SensorPinReading > 10)  {
  digitalWrite(LedPin1, HIGH);
  digitalWrite(LedPin2, HIGH);
  digitalWrite(LedPin3, HIGH);
  digitalWrite(LedPin4, HIGH);
  digitalWrite(LedPin5, HIGH);
  digitalWrite(LedPin6, HIGH);
  delay(600);
  digitalWrite(LedPin1, LOW);
  digitalWrite(LedPin2, LOW);
  digitalWrite(LedPin3, LOW);
  digitalWrite(LedPin4, LOW);
  digitalWrite(LedPin5, LOW);
  digitalWrite(LedPin6, LOW);
  delay(200);
  }
  else {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }

}

Here below is modified code based on your requirement. There are some changes in your code and I also comment it out. I hope it will help you.

/*
 6 Flashing LED Lights With A Pushbutton and FSR Sensor
*/

const int buttonPin = 8;

const int LedPin1 = 7;
const int LedPin2 = 6;
const int LedPin3 = 5;
const int LedPin4 = 4;
const int LedPin5 = 3;
const int LedPin6 = 2;

const int kDelay = 1000; // Take one varible "kDelay" and value = 1000

int buttonState = 0;
int SensorPin = A0;
int SensorPinReading;

void setup()
{
  Serial.begin(9600);
  pinMode(LedPin1, OUTPUT);
  pinMode(LedPin2, OUTPUT);
  pinMode(LedPin3, OUTPUT);
  pinMode(LedPin4, OUTPUT);
  pinMode(LedPin5, OUTPUT);
  pinMode(LedPin6, OUTPUT);

  pinMode(buttonPin,INPUT_PULLUP); // Provide PULLUP
  pinMode(SensorPin, INPUT);
}

void loop()
{
  SensorPinReading = analogRead(SensorPin);
  Serial.print("Analog reading = ");
  Serial.print(SensorPinReading);

  if(SensorPinReading < 10)
  {
    Serial.println(" - No Pressure");
  }
  else if (SensorPinReading < 200)
  {
    Serial.println(" - Light Touch");
  }
  else if (SensorPinReading < 500)
  {
    Serial.println(" - Light Squeeze");
  }
  else if (SensorPinReading < 800)
  {
    Serial.println(" - Medium Squeeze");
  }
  else
  {
    Serial.println(" - Big Squeeze");
  }

  buttonState = digitalRead(buttonPin);

  if(buttonState == HIGH && SensorPinReading > 10)
  {
    digitalWrite(LedPin1, HIGH);
    digitalWrite(LedPin2, HIGH);
    digitalWrite(LedPin3, HIGH);
    digitalWrite(LedPin4, HIGH);
    digitalWrite(LedPin5, HIGH);
    digitalWrite(LedPin6, HIGH);
    delay(15 * kDelay);            // You need 15 Sec, multiply kDelay with 15
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
  else
  {
    digitalWrite(LedPin1, LOW);
    digitalWrite(LedPin2, LOW);
    digitalWrite(LedPin3, LOW);
    digitalWrite(LedPin4, LOW);
    digitalWrite(LedPin5, LOW);
    digitalWrite(LedPin6, LOW);
  }
}


Any way to include the text of a file inside a sketch, to make it shorter and neater? I'm wondering if there is any way to include the text of a file into a sketch by using a single placeholder command, similar to the "#Include" command when using Server Side Includes on .shtml files.

I'm sorry if I'm not wording this correctly. It was hard for me to phrase it and also hard for me to search about it, since the nouns seem so generic.

I understand that some parts of code can be separated out into their own functions, and that those functions could be saved in a different .ino file. But I'm wondering about for the cases that can't be separated out into functions (like for declarations at the beginning of a sketch, or an area in loop() that would require too many variables to be passed to the function).

EDIT: I think I should've been more specific:
In one example, I have lots of html code being served from the loop() function. The Arduino webserver is serving a complex page that shows about 100 buttons on the webpage. I would like to separate the page-serving code to a separate .ino file and have it opened as a separate tab in the Arduino IDE. That way it's easy for me to open that tab whenever I want to modify the webpage, but also the code for serving the page won't take up so much space in my main file. The code isn't completely html (it has lots of functions and conditionals), so that's why I can't just save it as an external .html file and have it served from that file.

As another example: At the top of my sketch I have lots of defines for wireless signals that need to be sent. They look like this:

const unsigned long a1o = 4216115, a1c = 4216124, a2o = 4216259, a2c = 4216268, a3o = 4216579, a3c = 4216588, a4o = 4218115, a4c = 4218124, a5o = 4224259, a5c = 4224268; //remote control 1

There are 10 lines of code that look like that, and I never have to modify them because they're all constants. When I'm searching for bugs in my code, I never have to refer to those lines, and they're usually just in my way.

As suggested in comments, you can use #include statements to include texts of files into a sketch.  For example, suppose files c1.h,  c2.h,  c3.h,  c4.h, and  c5.h are in directory ~/sketchbook/tincludes, along with the file tincludes.ino, which is as follows:

#include <Streaming.h>
void setup() {
  const long int
#include "c1.h"
#include "c2.h"
#include "c3.h"
#include "c4.h"
#include "c5.h"
 etc=5   ;
  Serial.begin(115200);
  Serial << z1o <<  z1c <<  z2o <<  z2c <<  z3o <<  z3c <<  z4o <<  z4c <<  z5o <<  z5c;
}

Further, suppose c1.h ... c5.h each contain one line of code, as follows:

==> c1.h <==
  z1o=25829, z1c=9774,

==> c2.h <==
  z2o=7850, z2c=25585,

==> c3.h <==
  z3o=7103, z3c=17981,

==> c4.h <==
  z4o=30827, z4c=24511,

==> c5.h <==
  z5o=4167, z5c=10036,

Then the sketch will compile ok, and the sketch-lines with const long int through etc=5   ; will compile the same as if they were replaced by

const long int z1o=25829, z1c=9774, z2o=7850, z2c=25585, z3o=7103,
     z3c=17981, z4o=30827, z4c=24511, z5o=4167, z5c=10036, etc=5;


Const Array still using dynamic RAM during compile, causing failure Using win7 and arduino 1.6.7 IDE
I have a rather large CONST array of chars and upon compile using atmega2560, it fails and says:

Sketch uses 11,216 bytes (4%) of program storage space. Maximum is 253,952 bytes.
Global variables use 8,414 bytes (102%) of dynamic memory, leaving -222 bytes for local variables. Maximum is 8,192 bytes.
processing.app.debug.RunnerException: Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
    at cc.arduino.Compiler.size(Compiler.java:319)
    at cc.arduino.Compiler.build(Compiler.java:156)
    at processing.app.Sketch.build(Sketch.java:1108)
    at processing.app.Sketch.build(Sketch.java:1083)
    at processing.app.Editor$BuildHandler.run(Editor.java:2011)
    at java.lang.Thread.run(Thread.java:745)
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.

When I delete the CONST array the program compiles successfully, but when I put it back in, the compiler tells me that I'm using too much dynamic RAM.  If I am to understand correctly, consts should store in ROM not RAM.

Here's the even weirder part I put the program in Arduino IDE for Linux and it compiles, but it makes my robot act all crazy.

Any help would be much appreciated.

In a Princeton architecture const arrays are stored purely within the text (i.e., flash / read only / ROM) area.

In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.

Because of that it has to copy the const array from Flash into RAM so it can be accessed as normal variables.

To combat this you can use PROGMEM to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.

You can read more here: https://www.arduino.cc/en/Reference/PROGMEM


Understanding Nikon modified version of SPI I am trying to use this library to connect a Nikon lens to an Arduino.
https://lainy.github.io/NikonLens/classlain_1_1t_nikon_lens.html

I'm finding it very hard to understand the correct wiring.

  Connections are as follows (with Arduino Uno pin numbers):

  SS (10) is unused.

  SCK (13) is connected directly to lens SCLK.

  MISO (12) is connected to the lens Data line, which must be pulled
  high.

  MOSI (11) drives the lens Data line through a transistor,
  open-collector. So: MOSI -> Base, Data -> Collector, GND -> Emitter

  handshakePin_In is connected directly to lens H/S

  handshakePin_Out drives lens H/S through a transistor, open-collector.

I would like help to understand this.

  drives the lens Data line through a transistor, open-collector. So:
  MOSI -> Base, Data -> Collector, GND -> Emitter

It uses a variant of SPI interface. I'm just finding it hard to wrap my mind around it.

It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

simulate this circuit – Schematic created using CircuitLab

Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).

The Arduino reads that data in through the data in pin.

When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.

This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.


Statistical Mode calculation in Arduino programme How can I calculate the statistical mode from a set of values obtained from a distance sensor in an Arduino programme?

First, two caveats: (a) The question is fairly general and might be better asked on stackoverflow, except that asking here will tend to focus answers on algorithms with low memory requirements or online methods (methods that continually compute an answer as data streams through).  (b) In many cases – eg, with noisy sensors, noisy inputs, changing inputs – the statistical mode is less likely to be relevant than the statistical mean or median.

What computation method is best depends on which model of Arduino you use (because available RAM depends on model), what range of data your distance sensor returns, how many readings are taken, what you want to do with the data, whether an approximate (or nearly-correct) answer is acceptable vs an exact answer, and so forth.

Assuming you take 30 readings and store the data in an array d (that is, in d[0] ... d[29]), you could act as follows:

  Set high-value and high-count variables, say hiv and hic, both to 0.  For i from 0 to 29, count the number of occurrences ni of the value d[i] in the d array.  Whenever ni exceeds hic, set hic to ni and hiv to d[i].

You could make this more elaborate by detecting whether hiv is already equal to d[i] and testing ni ≥ hic rather than ni > hic.  This would allow detecting cases where two values are modal.

The method suggested in a comment – counting number of readings in various intervals – may compute an incorrect answer because the interval with the highest total count need not be the interval the mode is in.


AC meter By ADC timer interrupt from Nick Gammon I want to read ADC from the pin A0 and A1. I have written in this code, however.

I took this code came from Nick Gammon

Thank You
//////////////////////////////////////////////////////////////////////////////

this is code

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

// ADC complete ISR
ISR (ADC_vect)
  {
  if (resultNumber >= MAX_RESULTS)
    ADCSRA = 0;  // turn off ADC
  else
    results [resultNumber++] = ADC;
  }  // end of ADC_vect

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

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

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);  // WTF?
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

  // wait for buffer to fill
  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
    Serial.println (results [i]);

  }  // end of setup

void loop () { }

You can read two analog channels like this:

int first_reading = analogRead(A0);
int second_reading = analogRead(A1);

If this does not fit your purpose, then your question was not asked
properly: rewrite it and clearly state your requirements. Explain why
the simple solution does not work for you.

If this does work for you, then stop (for now) reading advanced
tutorials, like the one where you found your code, and focus on the very
basics: the Arduino examples in the 01.Basics section, then the
03.Analog section.


Reading 4 to 20ma pressure sensor using uno I have a OsiSense™ XMLP pressure sensor that I want to read from my Arduino uno. This is the circuit I am looking at building for measure 4 to 20 milliamp.

I've read online to find out how to build the circuit.  Can you tell me if it is correct?

Also I dont understand why it works and I'm hoping you can correct my thinking.  Following ohms law we want to leave 5v when 20 milliamps goes through the circuit.  We know the voltage on the circuit is a constant 24 volts (short cable runs) and we know the maximum current is 20 milliamps so my maths says :

Resistance = Voltage  / I (current)

We need to leave 5 volts for the Arduino to read when the sensor is at maximum pressure so we subtract 5 from 24.

Resistance = 19  / 20 milliamp

So the resistor to select to give us a maximum of 5 volts is a 0.95 Kilohms resistor.  I dont see where the 250 ohm resistor comes in? please help.

To read a current with the Arduino you first have to convert that current to a voltage - and you do that by passing it through a resistance. The voltage dropped across that resistance as the current changes is what interests you.

simulate this circuit – Schematic created using CircuitLab

For a 4-20mA current you need to choose a resistance that gives voltages that are within the 5V range that an Arduino can read.

The biggest voltage drop across the resistor will occur when the current is at maximum (20mA) so you can use that to calculate a good resistor value to use:

R = V/I = 5 / 0.02 = 250

And for the same resistance at minimum current:

V=IR = 0.004 × 250 = 1

So across the resistor you would get between 1V (4mA) and 5V (20mA).

250Ω resistors aren't that common, so a more common value would be used instead - such as the commonly available 220Ω.  Substituting the 250Ω for a 220Ω would give voltages:

@20mA: V=IR = 0.02 × 220 = 4.4V
@4mA:  V=IR = 0.004 × 220 = 0.88V

Both comfortably within the Arduino's range and also gives a bit of wriggle room in case of any small over-current conditions.

It can also be good to protect the analog input of the Arduino with a resistor + zener diode to prevent damage in the case that the resistor fails / becomes disconnected and you get the full output voltage applied direct to the Arduino:

simulate this circuit


Switch Control Between Two Different Techniques I have implemented PID control of a generator governor to maintain a constant RPM using an Arduino Uno. It works pretty well, but there is a tradeoff between stabilty and response time. Using PID values that allow it to respond without oscillation is also about half as fast as the old mechanical governor.

I came up with a plan to use a CT to sense the AC amps and have the Uno rapid the throttle servo to a known value determined manually. Either using a lookup table or an interpolation algorithm, I haven't yet checked the linearity of the amps vs. throttle angle. The idea is to use a table (or interpolation) to get the governor close, and then let the PID fine tune it.

My hangup is that I'm not sure how to switch between lookup control and PID control as needed.

Pseudo-code:

analogRead(AMPS);
myservo.write(table_Val);
somehow_switch_to_PID;
myservo.write(PID_value);

the PID is looking at the RPMs and giving an output but that output is
  being ignored because another operation has servo control.

PID is not something, that happens somewhere in the background without you having any control. On the Arduino it is done in software, so you can totally control it. Why should you run a PID calculation, if you don't use the value? The solution is to simply only do the appropriate calculation depending on the RPM at any given time. No need to do 2 calculations at the same time. I will form that into a code with explanations:

You have 2 ways of calculating the needed servo values:

Your "getting close" method
The PID method

To switch between those methods you need to make a decision based on the RPM. If the RPM is outside of your interval, the first method is used. If it is inside, the second will be used. Decision/conditionals are often wrote with an if else statement. Look at this (not tested) code snippet:

int target_rpm = 700;
int half_interval = 20;
int current_servo_pos = 0;

void loop(){
    current_rpm = analogRead(AMPS);

    if(current_rpm > target_rpm - half_interval && current_rpm < target_rpm + half_interval){
        // Do the PID calculation here and save the result in current_servo_pos
    } else {
        // Do the "getting close" calculation here and save the result in current_servo_pos
    }

    myservo.write(current_servo_pos);
}

I didn't go into detail about the actual calculation, since that is not important here. You may use any calculation, that you like there. For PID you can find libraries, that do the calculation for you, for example here at github.

The code will simply decide based on the RPM, what calculation should be used. If the RPM goes out of the interval for some reason (maybe is was disturbed and lost some speed), it will automatically use the "getting close" method until it is again inside of the interval.

Note: The numbers, that I used here, are arbitrary. You should change them to what ever you need.


Problem with serial driver for CH340G board I bought a USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1

The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded http://www.wch.cn/download/CH341SER_MAC_ZIP.html

Most of the instructions were in Chinese, but the driver CH341SER_MAC.ZIP 资料类型：应用资料 资料大小：250KB 资料版本：1.1 更新时间：2013-12-25 seemed to install, but I cannot seem to find any /dev/tty and Arduino can't see any serial ports.

Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)

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

This indicated a newer driver for OSX 10.9 and above at:-
http://kiguino.moos.io/downloads/CH34x_Install.zip

It is now working OK.

PS This was probably a Mac question, but I will answer as it is mainly of interest to Arduino users.

PPS The board worked on my Raspberry Pi which had the driver installed.

WARNING

The driver worked on OS X 10.11 but after upgrading to OS X 10.11.2 when I plug the USB cable into the Mac it causes a crash. This may or may not be related to the upgrade but after this happened twice I gave up.


Sending NEC IR signals makes LED strip blink I'm trying to make my ESP8266 (running NodeMCU meaning Arduino code gets compiled on it). I followed a guide and now I can read the IR codes from my remote using my Arduino UNO, and then send them to the LED strip. So far sending it actually works, but it blinks REALLY fast.

Some part of me tells me it's trying to send it twice or the radio frequency is wrong. For TVs and so on, it doesn't really matter, as you can't turn on and off a TV instantly. You can with this LED strip though. This is how I send my NEC signal to the strip:

irsend.sendNEC(0xFF02FD, 433);

433 is the frequency (433 kHz), as I read that's the most common frequency these LED strips work at. The entire code I used can be found here. Do you think I have a frequency issue? I have tried a lot of different frequencies and they all seem to do the same thing.

Also, when I try to send the exact same NEC signal to my receiver, I get two different results. It is only being sent one time as well. Here is what I receive:

Using the actual receiver:

Decoded NEC(1): Value:FF02FD (32 bits)
Raw samples(68): Gap:51848
  Head: m8750  s4550
0:m450 s650 1:m450 s650      2:m450 s650    3:m450 s650
4:m500 s650 5:m450 s650      6:m450 s650    7:m450 s650
8:m450 s1750    9:m500 s1750         10:m450 s1750  11:m450 s1750
12:m500 s1750   13:m450 s1750        14:m450 s1750  15:m500 s1750

16:m450 s650    17:m450 s650         18:m450 s650   19:m450 s650
20:m500 s600    21:m500 s650         22:m450 s1750  23:m450 s650
24:m450 s1750   25:m500 s1700        26:m500 s1750  27:m450 s1750
28:m500 s1700   29:m500 s1750        30:m450 s650   31:m450 s1750

32:m450
Extent=66900
Mark  min:450    max:500
Space min:600    max:1750

Using irsend.sendNEC(0xFF02FD, 433)

Decoded Unknown(0): Value:0 (0 bits)
Raw samples(38): Gap:18088
  Head: m8850  s4550
0:m500 s1750    1:m500 s650      2:m450 s650    3:m500 s650
4:m500 s650 5:m450 s650      6:m500 s650    7:m450 s1800
8:m450 s700 9:m450 s1800         10:m450 s1800  11:m450 s1800
12:m450 s1800   13:m450 s1800        14:m450 s1800  15:m450 s650

16:m500 s1750   17:m500
Extent=43200
Mark  min:450    max:500
Space min:650    max:1800

EDIT: I forgot to mention: 0xFF02FD is the signal power/on/off button. If I change the 0xFF02FD to anything else (like 0xFF18E7 to make it yellow), the LED strip will just blink.

32 kHz seems to be the winner. Now all my codes work! Damn, if I only had read that ONE SITE that showed it haha.


Arduino Micro blue light dimms and turns off when I plug in my circuit I have a PING Ultrasonic Sensor, Adafruit Absolute Orientation Sensor, and a Continuous rotation servo. All pins are connected to an Arduino Micro. However because the micro only has one 5V output, I used a rail from a breadboard. I connected the + & - leads from all the devices to the rail and then plugged in two leads connecting 5V and GND from the Micro to the rail. My goal was two send power from the Arduino Micro down the rail to all three devices.

I plugged in the Micro, and instead of seeing green lights on the sensor (powered on), the blue light on the Micro turned off and the servo twitched. I have no idea why. Do I need external power for the 5V?

This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.


Problem with HC-06 receiving data I have paired 2 BT modules HC-05 and HC-06. When I write something through Serial Monitor and send it from HC-05 to HC-06, everything works well. But when I send continuous data through loop, HC-06 receives only specific amount and then just stops! Is it because of BT module, or there is something else?
My code for HC-05:

#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTserial.begin(38400);
}

void loop()
{
        BTserial.write('1');
}

Code for HC-06:

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTSerial.begin(9600);
}
void loop()
{
if (BTSerial.available())
    Serial.write(BTSerial.read());
}

Baud rates are good.
Thanks!

I think you have 2 problems:

First about the shown sketch: I don't think, that the Baud rates are good. In your HC-05 code (the sender) you are using BTserial.write('1'); without any delay or other code, thus this will run very fast, so the SoftwareSerial interface is almost completely busy. You sending almost at the maximum speed, that you can get with 38400 baud. On the receiving site you are using 9600 baud, which is significantly slower than 38400 baud. How should the HC-06 transmit all data, that it get's, to the Arduino, when you only use 9600 baud, but the data is coming with 38400 baud? That cannot work. You should configure the HC-05 and HC-06 to use the same baudrate, so that this cannot happen. Or - if you really don't want to - you can restrict the overall speed, that you are sending with, by just sending less data per time unit (sending the data slower, but on the same baudrate as before). This will prevent the HC-06 to get flooded by data. (Also there might be a limit on how fast you can send data over the HC-05, but I haven't tested this). All in all it mostly isn't a good idea, to do communication totally without any speed brake. That can get you into troubles, that you mostly don't want to think of.
Secondly: In your comment you wrote, that you tried to change the baudrate, but that gave you garbled data. Since you didn't describe more, we cannot say much about this. But garbled data is a normal symptom for wrong baudrate. So it seems, that you haven't changed the baudrate successfully. I would suggest, that you again look into this and that you try to change the baudrate successfully. It is possible and there are many tutorials and codes on the web, that show how it is done. (When you again have problems with this, you can ask a question about this specific problem, including all the relevant information)


Pass a member function pointer to a method of a foreign class (EDB Lib) I'm currently working on my own arduino library and I'm becoming exasperated with the following problem: I want to store data with the extended database library (https://code.google.com/p/arduino-edb/) on a sd card. I tried to follow and adapt the instructions on this page and I gave my custom library a property "File dbFile" as well as a property "EDB db". Additionally I have to pass two function pointers to the constructor of the EDB library. So my custom library got two more properties: a writer and a reader function. My class looks roughly like that:

class myLib
{
   public:
      myLib();
      ~myLib();
      void configWriter( unsigned long address, byte data );
      byte configReader( unsigned long address );
      File dbFile;
      EDB configDB;
}

...so far so good. But here comes the pain in the ... When I'm trying to instantiate a new EDB object in the constructor of my class by passing two pointers to the member functions I'm constantly getting an error. Here is how I call the constructor of the EDB library:

configDB = new EDB( &myLib::configWriter, &myLib::configReader );

I get the following error:

  no matching function for call to 'EDB::EDB()'

  [...] note: candidates are:

  note: EDB::EDB(void ()(long unsigned int, uint8_t), uint8_t ()(long
  unsigned int))
       EDB(EDB_Write_Handler *, EDB_Read_Handler *);

The prototype of the EDB constructor looks like this:

  EDB(EDB_Write_Handler *, EDB_Read_Handler *);

EDB_Write_Handler and EDB_Read_Handler are defined like so:

  typedef void EDB_Write_Handler(unsigned long, const uint8_t);
  typedef uint8_t EDB_Read_Handler(unsigned long);

So I assume that my constructor call doesn't work because the functions that I'm passing are from a foreign class: (myLib::) and not just ()

I have no idea how to solve that problem. Does someone of you have any idea?

Thanks,
Andy

EDIT:
Here is a Minimal, Complete, and Verifiable example:

myLib.h:

#ifndef myLib_h
#define myLib_h

#include "Arduino.h"
#include <SPI.h>
#include <SD.h>
#include <EDB.h>

#define SD_CS 4
#define SD_SS 10

class myLib
{
  public:
    myLib();
    ~myLib();
    void begin();
    void configWriter( unsigned long address, byte data );
    byte configReader( unsigned long address );
    File dbFile;
    EDB * configDB;

};

#endif

myLib.cpp:

#include "myLib.h"

myLib::myLib( void )
{}

myLib::~myLib()
{}

void myLib::begin()
{
  // Init SD
  pinMode(SS, OUTPUT);
  SD.begin(SD_CS);

  // Load Config
  configDB = new EDB( &myLib::configWriter, &myLib::configReader );
  dbFile = SD.open("config.db", FILE_WRITE);
}

void myLib::configWriter( unsigned long address, byte data )
{
  dbFile.seek(address);
  dbFile.write(data);
  dbFile.flush();
}

byte myLib::configReader( unsigned long address )
{
  dbFile.seek(address);
  return dbFile.read();
}

Arduino sketch:

#include <SPI.h>
#include <SD.h>
#include <EDB.h>
#include "myLib.h"

myLib* a;

void setup()
{
  a = new myLib();
  a->begin();
}

void loop()
{
}

The problem here is a common one with C++.  It basically boils down to how C++ handles member functions.

You define a member function as, say,

class myLib {
    void myFunc(int val);
};

When you call the function it's actually not defined as that - it's instead had its definition change to:

void myFunc(myLib *this, int val);

The addition of the myLib *this is an implicit parameter, and it's how C++ keeps track of its object instances when calling different functions.

So a function which expects a parameter of void (*func)(int) won't accept your method because it's actually void (*func)(myLib *, int).  Hence the error you are seeing.

There is no easy, clean, way around it that I have found as yet, I am afraid.  The closest you can do is to move the reader and writer functions outside of your class and store a global pointer to the actual class, something like:

static myLib *globalLib;
void globalConfigWriter( unsigned long address, byte data ) {
    globalLib->congigWriter(address, data);
}
byte globalConfigReader( unsigned long address ) {
    return globalLib->configReader(address);
}

Then in the constructor for your lib you can do:

myLib::myLib() {
    globalLib = this;
}

You then register the global reader and writer functions with the EDB constructor instead of the class member functions.

It does have the rather major down-side that there can only be one instance of your class since there is only one global pointer and only one pair of reader / writer functions.  There are ways of supporting a finite number of instances, but it basically involves having a reader/writer pair for each instance and allocating one to an instance when it's constructed and de-allocating it when its destructed.  Keeping track of them and knowing which object is associated with which function pair is tricky at best...


Two function Reset button - long/short press I am trying to make a circuit using an ATmega328, that has a reset button that behaves like many consumer devices:

A short press just restarts the micro-controller
A long press (5 seconds?) causes the settings to be restored to default

What is the best way to achieve this behaviour? I imagine it is going to require two pins? Can it be done just using passive components?

Thanks!

It can be done with one button, one resistor, one capacitor and one GPIO pin (in addition to the RESET pin):

simulate this circuit – Schematic created using CircuitLab

Pressing the button causes a LOW pulse on the RESET pin (in the exact same way as the USB interface does).

During your startup procedure you read the GPIO pin you have chosen. If it's LOW the button is still being pressed in. If it's HIGH it has been released.

If you are using an Arduino with the normal bootloader the bootloader itself imposes a 2 second delay (which may be enough for you). Alternatively you will need to have your own delay in your program before reading the button to ensure that you have plenty of time to release the button so you don't accidentally reset your settings.


Arduino stops working when servo makes a few rotations The sketch rotates servo back and forth with buttons.
When I rotate servo MG 995/996R 2-4 times Arduino stops working. Its voltage step-down transformer switches from ~9V to ~3.7V which is not enough for Arduino. To make it work again, I must turn off-on the device.

There is no such a glitch with smaller servos such as SG90.

Ground loops can be bad.  Do follow up as suggested in the comments regarding ensuring the power supply grounds are the same. To be specific, connecting the power supply grounds through the Arduino is a bad idea! The trace size should not be assumed adequate for the unknown amount of current passing between the ground outputs of the power supplies.  And a voltage potential can develop causing the processor to behave unexpectedly or worse burn out components.
Also, consider that some Arduino platforms regulate power to 5 volts on the board and that many servos run fine at 5 volts. If this is true here, you could greatly simplify and possibly solve the describe problem by using a single 5 volt power supply.
Lastly, ensure there is a pull up on the 2 inputs connected to the (assumed) normally-open-momentary-contact switches.  There are none in the diagram.  So it is assumed pull ups have been activated in the code such as explained here.


How can I set a calculated value when my sketch is uploaded? I have an Arduino based countdown timer that counts down the number of minutes remaining to an event and displays them on an LCD. Since the event's start time is fixed, I have to re-calculate my countdown duration and update a constant in the sketch every time I upload it.

Is it possible to calculate the duration on the PC and set the starting value for the timer automatically? Perhaps using some kind of pre-compile script? Or perhaps through some kind of debugging features?

I'm not interested in adding RTC or other hardware to this project b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project.

I'm currently using the Arduino IDE but I would be open to solutions that use other IDEs, or external components.

The C compilers provide two macros that resolve to string literals:  __DATE__ gives the time the file was compiled, and __TIME__ gives the current time of day. They output e.g. "May 31 2017" and "21:19:49"

You'd have to parse these string to get the time and do the calculations to get the remaining time.


Question about number of sensors for Arduino Mega What is a good max number of sensors for an Arduino Mega? Since it has like -- 2? -- ground connections, is it better to keep the number of sensors to a minimum amount?

It depends on what you want the Arduino to do with them. There is no (not much) penalty for having many sensors connected. Where it begins to matter is when you need to read at rates which, collectively, tax the speed of the processor to meet the total demand. Your project specs will really determine how many sensors make sense. The other place that sensor count might matter is if your project is to be battery powered, and the sensors draw some amount of current even when they're not being used. In a battery powered project, you'll want to be able to power-down everything that isn't being used at a given time, to maximize the system's overall run-time on battery.

The Mega, and I'm assuming you mean Mega 2560, has 50-some odd I/O pins available, so you have a lot of potential connectivity, and I think it's safe to say, the designers intended for them to be used.


Can't create an array of type const char* I have something being returned as a const char* and would like to save it to an array.

I've tried this:

const char* book[amtBooks] = "";

and get this error:

error: array must be initialized with a brace-enclosed initializer

const char* book[amtBooks] is an array of pointers.
"" is an array of chars (with only a NUL character).

You can initialize an array of chars with an array of chars:

const char foo[] = "hello";

You can also initialize a pointer to char with an array of chars:

const char *bar = "good bye";

this works because of the “decay to pointer” feature of C and C++.

But initializing an array of pointers with an array of chars simply does
not make sense. An array of pointers to char could be initialized as

const char *book[] = {"hello", "good bye"};


Hand position sensor What is the simplest way to get an alarm sound when a human raise hands up.
Assuming he is wearing a sensor or whatever as a watch or ring.

A tilt sensor, can be used as what you are trying to say, whenever someone (who wore it) raise his hand or move it, will trigger an alarm.
If you want to carry your alarm with you then...
You can use arduino nano or micro with a sensor and buzzer connected to it to just place it in gloves or watches etc.


Making pushbutton behave as a toggle switch with ezButton - do I have to use ledstate with =! operator I'm using ezbutton to make a pushbutton act like a toggle switch, first press doing permanent on, second press doing permanent off. I'm just trying to understand the basic coding. This project is just a testbed for what I'm planning to do later - wiring vehicle toggle switches to Arduino and feeding the output signal to mosfet that will control the load state. So I'm trying to get the code as nice and tidy as I possible can. In the code below, I would like to know if ledState will be applicable when this sketch will control a mosfet instead of a test led, and I've seen comments saying "ledState = !ledState;" is not optimal - but being a beginner I'm not sure what this means, and is there a better more sound way to address it. Thanks!
#include <ezButton.h>

// ---
// Declaration
// ---

const int button1  = 9;
const int led1     = 4;
int ledState = LOW;

ezButton button(button1);

// ---
// Setup
// ---

void setup()
{

  pinMode(led1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  button.setDebounceTime(50);

}

// ***
// Main Loop
// ***
void loop()
{

  button.loop();

  if (button.isPressed()) {
    ledState = !ledState;
    digitalWrite(led1, ledState);
  }

}

I've been looking through the source code for ezButton.c
The function isPressed() is something of a misnomer and is only meaningful for a push-to-make button on the low side of a pull-up resistor. It actually detects falling edges of the signal, so it should be called isFallingEdge(), but the code itself is good.
Similarly for isReleased() which detects rising edges of the signal, so should be called isRisingEdge().
The constructor defaults to INPUT_PULLUP which may (or may not) be what you want for your buttons and toggle switches, so it's something to bear in mind especially for low-side push-to-break buttons or high-side push-to-make buttons which will generate rising edges when pressed and falling edges when released thus reversing the meanings of isPressed() and isReleased(), hence why they really should be called isFallingEdge() and isRisingEdge().
The algorithm in ezButton::loop() could be optimised a bit by getting rid of previousSteadyState and nesting the final if statement within the second if statement.
Other than that, it's quite a good algorithm that makes use of hysteresis to reset the debounce timer.
For comparison you could take a look at my algorithm in this simple debouncer for Arduino that simply detects rising edges, falling edges or both edges without regard to whether a button was pressed or released, and can be used in a polling loop or with interrupts. Here's the essence of the algorithm:
    bool input_state = digitalRead(INPUT_PIN);
    unsigned long current_ms = millis();

    edge = rise = fall = false;

    // Hysteresis:
    //   If there is no change, reset the debounce timer.
    //   Else, compare the time difference with the debounce delay.
    if (input_state == output_state)
    {
      last_ms = current_ms;
    }
    else if ((current_ms - last_ms) >= DEBOUNCE_DELAY_ms)
    {
      // Successfully debounced, so update the outputs.
      rise = input_state && !output_state;
      fall = !input_state && output_state;
      edge = rise || fall;
      output_state = input_state;
    }

And ledState = !ledState; simple toggles the value of ledState which is what you write to your LED with digitalWrite(led1, ledState); each time a falling edge is detected in the input signal.


How to switch on and off an HD44780 LCD Display? I have an LCD Display HD44780 model and I was reading his datasheets

I saw the it has the functionality to be switched on/off as stated:

  Display on/off control: D = 0; Display off // C = 0; Cursor off // B = 0;
  Blinking off

and by continue reading it states:

Then he states again:

Display On/Off Control

  D:  The display is on when D is 1 and off when D is 0. When off, the
  display data remains in DDRAM.

But I can't reaaly understand what I fisically need to do, can anyone help me out to better understand?

EDIT:
For better clarify myfinal goal is to completely (power OFF) the LCD screen, I have some NPN transistors and if this would be the best solution, how about the wiring? do I have only to stop suppying VDO?

Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

set RS to LOW first (meaning it is command, not data)
set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)


Current Arduino STL Libraries I was going to update this question but I thought that this was different.

I have been trying to get std::vector to work with the latest Arduino. I have tried downloading several libraries found online but I can not get one of them to compile correctly. So here is my question, does anyone CURRENTLY know of a Arduino STL Library that is working?

StandardCplusplus: As stated above I tried to use this library but run into problems with the new/delete functions.

Andy Brown's AVR-STL Library doesn't even seem to come close to compiling.

If anyone has a working copy of these two I would love to have a copy or if you can tell me how to get them to compile. Otherwise I really need to find a way to get Vectors working, does anyone have any ideas?

Edit

I didn't want to answer this question so it is still active as I am sure there will be additions to this. Anyways I FINALLY got a library to work (for now, so far). I downloaded the StandardCplusplus library and found that in order to get any of the stl functions to work you have to add an include to the "StandardCplusplus.h" file before EVERY use, not just in the first file as stated in the Wiki on the Project page.

So I was able to get vectors to work using the following:

#include "StandardCplusplus.h"
#include <iterator>
#include <vector>

vector<int> test;

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

   test.push_back(1);
   test.push_back(2);
   test.push_back(3);
   test.push_back(4);
}

void loop(){
   for (int i = 0; i < test.size(); i++){
      Serial.println(test[i]);
   }
}

I would still like to know of other working STL Libraries as it seems that there are tons of outdated and old libraries out there.

I maintain an Arduino plugin that's a port of uClibc++ (just like the defunct StandardCplusplus library). It's available in the Arduino library manager for Arduino versions 1.6.10 and higher. It's called ArduinoSTL.


Can't display the two float values correctly from pyserial on Arduino's LCD I transported two float values with pyserial to COM3 and Arduino accepted the values.

But it displayed the first value correctly on LCD, the second value can't be read and showed "nan" on LCD.

Python code:

import serial
import struct
ser =serial.Serial("COM3", 115200, timeout=2)

##======Get  Ready================
print("Connecting to Arduino.....")
for i in range (1,10):
    rv=ser.readline()
    print("Loading...")
    #Debug print (rv) # Read the newest output from the Arduino
    print (rv.decode("utf-8"))
    ser.flushInput()
    sleep(1) # Delay for one tenth of a secon
    Str=rv.decode("utf-8")
    #Debug print(Str[0:5])
    if Str[0:5]=="Ready":
          print("Get Arduino Ready !")
          break
##------------------------------------------------------
d = 77.25
a = 111.32
ser.write(struct.pack('>2f',d,a))

Arduino code:

#include <LiquidCrystal.h>
float x;
byte *xdata = (byte *) & x;
float y;
byte *ydata = (byte *) & y;
int num = 0;
char coor[2];

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(115200); // set the baud rate
  Serial.println("Ready"); // print "Ready" once
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
}

void loop(){
  while(Serial.available() > 0){
    for(int i = 0; i < 2; i++){
      coor[i] = Serial.read();
      }
    if(coor[0] == 'B' ){
      xdata[3] = coor[0];
      ydata[3] = coor[1];
      num = 1;
    } else if(num == 1){
      xdata[2] = coor[0];
      ydata[2] = coor[1];
      num++;
    } else if(num == 2){
      xdata[1] = coor[0];
      ydata[1] = coor[1];
      num++;
    } else if(num == 3){
      xdata[0] = coor[0];
      ydata[0] = coor[1];
      num = 0;
    // use the values
    Serial.write(xdata,4);
    Serial.write(ydata,4);
    lcd.print(x);
    lcd.setCursor(8,0);
    lcd.print(y);
      }
    }

The LCD monitor will show 77.25 and nan. It can't show 111.32 correctly.

I don't understand why you read the bytes this way. Your original version was reading only the bytes of the first float into xdata and -1 into ydata. (read returns -1 if no data is available, it doesn't wait.) Now when two bytes are read with readBytes, first two bytes of the first float are written one into xdata[0] and second into ydata[0].

read first float with readBytes(xdata, 4) and the the second with readBytes(ydata, 4)


Simple compiler design help: Variable length arrays in Arduino? I'm trying to write a simple compiler in the Arduino language that I am making up for my lab.  The compiler will have to be able to turn a string like this:

"do command_one 3 times"

into a data structure that represents this:

<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:

"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:

<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.

These examples show all of the functionality that I would want from the compiler.

I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in Arduino need to be initialized with a length, this could be a problem.

I am not fluent in Arduino so I am hoping that an Arduino whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.

You will also notice that I posted the same question in the C++ stackexchange.  I am trying to write the same code for an Arduino and in C++.  I know that Arduino code is based on C++, if the answer is the same in Arduino as it is in C++ that would be very helpful.

The Arduino IDE features nearly full C++ language support (at least for C++03 features).
library support is limited, but any standard component you need, you should be able to get an open source implementation that compiles.
That said, you have 2K of RAM to work with on an Arduino, so the kind of C++ code you would write for a general purpose computer just won’t get you very far.
I could be wrong, but I very much doubt there are full Python implementations for Arduino.

Edit: Thanks to Mr. Penguin for pointing out that we’re dealing with an Arduino Due, not an Uno (I had overlooked the OP’s tag). 96K of memory is actually a decent amount to play with, so grab a library implementation like this one and use the C++ techniques you wish to use.


Constructing my own serial command syntax to control arduino I know this is a basic question, but as a hardware electronics guy and not a programmer I cannot seem to fathom how to do this - so any examples of code would be greatly appreciated:

I want the arduino to spit out some initialization chatter on startup - (ok, done easy).

Then I want it to listen for serial commands, they can all be same length if that helps but I want them to be strings. i.e. identifier followed by value

Command --- Result

PWR_TRUE --- Power on device

PWR_FLSE --- Power off device

REP_FREQ --- Print frequency over serial

SP000752 --- Set power value to 752

SP016675 --- Set power value to 16675

Obviously the commands are two types, the first two being booleans and then integers, but I cant seem to find any examples not working off a single ascii character value, which is useless to me. I need more information and then from the message be able to break it down into something the arduino does.

An example of how to import whole commands and either do something, and / or chop the command up to get the value out, would be most useful.

Many thanks in advance :)

EDIT/UPDATE:
I now seem to have found a solution thanks to Edgar as given in the comments. However I now have another question relating to updating the variables so as to effect the loop, as well as performing actions upon receipt of commands (which itself now works)
LINK HERE

Expanding on my comment... I wrote a simple command line interpreter
that you can use as a base, or an inspiration, for your own interpreter.
In order to not make a link-only answer, I will put here an annotated
and simplified version.

The incoming characters are handled by loop(). They are stored into a
static buffer until a carriage return (CR = '\r') is received. When
the CR is received:

the buffer is NUL-terminated in order to make it a proper C string
it is handed to the exec() function for interpretation
the variable storing the command length is reset to zero for the next
command

Here is the code:

while (Serial.available()) {
    static char buffer[BUF_LENGTH];
    static int length = 0;  // length of line received so far
    int data = Serial.read();
    if (data == '\r') {
        buffer[length] = '\0';     // properly terminate the string
        if (length) exec(buffer);  // give to interpreter
        length = 0;                // reset for next command
    } else if (length < BUF_LENGTH - 1) {
        buffer[length++] = data;   // buffer the incoming byte
    }
}

The exec() interpreter function uses strsep() to split the
command line into a command verb and subsequent parameters. It then
compares the command verb with all supported commands in a long if...
else if sequence, like this:

static void exec(char *cmdline)
{
    char *command = strsep(&cmdline, " ");

    if (strcmp(command, "mode") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int mode = atoi(cmdline);
        pinMode(pin, mode);
    } else if (strcmp(command, "read") == 0) {
        int pin = atoi(cmdline);
        Serial.println(digitalRead(pin));
    } else if (strcmp(command, "write") == 0) {
        int pin = atoi(strsep(&cmdline, " "));
        int value = atoi(cmdline);
        digitalWrite(pin, value);
    } else {
        Serial.print(F("Error: Unknown command: "));
        Serial.println(command);
    }
}

This one supports the three commands:

mode <pin> <mode>, meaning pinMode()
read <pin>, meaning digitalRead()
write <pin> <value>, meaning digitalWrite()

The full version is here: Simple Arduino command line
interpreter. Compared to the version in this answer, the
main differences are:

it echoes the characters it reads, and does so in a way which is
friendly to terminal emulators:

it echoes CR as CRLF
it handles BS (backspace) and echoes it as BS + space + BS

it uses strcmp_P() instead of strcmp(), with the PSTR() macro,
in order to keep the constant strings in Flash only
it supports more commands, including "help".


Using several Arduinos simultaneously I'm working on a project where I need to control the light of 5 buttons as well as listen when each button is switched on/off by the user. I would furthermore like to provide feedback on an OLED display. It looks like I'm running out of pins. This https://arduino.stackexchange.com/a/22689/69029 provides several options for that. I would specifically like to explore the option to have several arduinos connected to each other in a master/slave configuration. Where can I learn more about my option to build stuff using several Arduinos connected to each other? I can also forsee scenarios where I could use 3.3V devices as well as 5V devices.

Among all the options mentioned, using a master/slave should be the last resort, especially when you are new to embedded programming or Arduino, it is not only more complicate but also more expensive to implement.
One potential solution that could free up the precious digital i/o pins that were used by the 5 buttons is using analog input to detect the status of the buttons.

simulate this circuit – Schematic created using CircuitLab
When sw1 is pressed, the voltage at the A0 will be around 0.83v, and when sw5 is pressed, the voltage at the A0 will be 2.5v. You can write a simple switch...case to determine which switch has been pressed.
The only problem of this circuit is that it can't handle more than one button been pressed simultaneously, but that could be solved by double the value of each resistor like 10k, 20k, 30k...
This will free-up 5 digital pins that can be used for control (such as servo, relay, etc.).


Wireless Sensor (IMU) to Arduino I was doing some research about this subject and I only have more questions than answers.

I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.

The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.

What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.

My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.

As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.

You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.

Radio: Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.

You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.

IMU: Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.

You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.


can I create an on/off switch for my Arduino using the reset pin? If i connect a switch to the reset pin, can I create an effective way of turning off the Arduino (overnight) without removing its power supply?

Tests show that connecting Reset to Ground on a Uno reduces the power consumption from 47 mA to 41 mA. So it is hardly "off".

All that would do is stop the currently-loaded sketch running, and save a few milliamps.


Is there any working analogue to the pair std::function and std::bind in Arduino? Both ArduinoSTL and StandardCplusplus don't support them. They implement the version that is compatible with c++03 (not c++11).

This functionality is handy when you design libraries that work with callbacks. And you do need them, if your Arduino does more than one thing simultaneously.

I tried also several other options, but none was enough. Most complete thing I found, Passing capturing lambda as function pointer, does not support plain function pointers and does not allow me to hold the function object as a member of the structure, because the type of the object depends on the lambda (not only its signature, like in std::function).

In particular, I need a functor that

can store both capturing lambdas and plain function wrappers
has a type that depends only on the signature of the function, so I can store it as a class member.

We have written a solution, that we published as a Platformio library: https://github.com/fopeczek/function_objects.
Please note, that each functional object does one allocation, and those are not particularly friendly in an embedded environment. I am not even sure, that the Arduino C++ does heap deallocation, so you may be leaking resources if you create and destroy the functional objects in a loop.


ctc mode on atmega 328 I'm trying to use CTC mode on Arduino 1 but I have the following problem.
I need to generate an interrupt on threshold B and A and I have set the prescaler to 1 since I want to generate interrupt A at 15999 (correspond to 1ms) and interupt B at 15( ie a number small enough from the start of counting).
I'have write a println function in ISR(A and B) to proof the calling of the latter but the program does not print all the characters in the println function and furthermore the counter does not reset at treshold A but stop his work.
How I can resolve the problem?

Here is the program I wrote:

void setup() {
    TCCR1A = 0x00;                // No outputs on compare math, no PWM mode
    TCCR1B = 1 | (1 << WGM12);    // Enable CTC mode up to OCR1A and prescaler /1 -> Start
    //TCCR1B = 0b00001001;
    TCCR1C = 0x00;                // Nothing to set into C register

    OCR1A = 15999;                // Set Threshold A
    OCR1B = 15;                // Set Threshold B
    TCNT1 = 0;                    // Clear Counter

    TIFR1 = (1 << OCIE1A) | (1 << OCIE1B);    // Clear Interrupt flag Match A and B

    TIMSK1 = (1 << OCIE1A) | (1 << OCIE1B);   // Enable Interrapt flag Match A and B

    analogRead(A0);            // Dummy Read to make Arduino setting the AD
    ADCSRA |= (1 << ADIE);     // Enable AD Interrupt on conversion completed
    ADCSRB = 5;                // Select Timer 1 Match B as trigger
    ADCSRA |= 1 << ADATE;      // Enable Auto trigger

    Serial.begin(115200);      // Initialize the USART
    Serial.println("Start");   // Write the welcome message

}

void loop() {
    // Nothing to do
}

ISR(ADC_vect)
{
    Serial.print(TCNT1);
    Serial.print(" - ADC Conversion Completed (");
    Serial.print(ADC);
    Serial.println(")");
}

ISR(TIMER1_COMPA_vect)
{
    TCNT1=0;
    Serial.print(TCNT1);
    Serial.println(" - Interrupt A");
}

ISR(TIMER1_COMPB_vect)
{
    Serial.print(TCNT1);
    Serial.println(" - Interrupt B");
}

I don't know about configuring the timers on an AVR off hand, but one thing I will point out:

Never ever use Serial in an ISR.

Serial is interrupt driven - when there are characters in the outgoing serial buffer an interrupt routine sends them out through the serial port.  That can't happen when you're in an interrupt routine yourself, so when the buffer fills up the next Serial.write() (print, etc) blocks until there is room in the buffer for the next character.  As the ISR can't run, that space never appears, so the print(), write(), etc never finish and the program locks up.

Instead you should store any incoming values in your ISRs into volatile variables, and set flags to indicate to your main program what has happened in the ISR - then your main loop() reads (and resets) those flags and prints out the statuses you want.


use of spec sensor in arduino uno i have been trying to use NO2 spec senor in arduino UNO. how to write the code for it to get the output in terms of 'ppm' and how to give connection.with the helo of cross-sensitivity given in datasheet how to detect the interference gases from this sensor itself..the datasheet URL:

https://www.spec-sensors.com/wp-content/uploads/2016/10/3SP_NO2_5F-C-Package-110-508.pdf

In the specification sheet linked to in the post we find this:

  -30+/-10nA/ppm

This is a very small amount of current.  The Arduino ADC is a voltage sensing device and (unless modified) has a range of 0 to the operating voltage of the Arduino.  Usually 3.3V or 5V.

Converting nano Amps to that range of voltage will require additional hardware.  A stock Arduino and code are unlikely to make use of such a sensor.

The conversion of such small amounts of current to voltages measurable by a stock Arduino is not trivial. And most answers do not fit into the short format of stack exchange.  Here is an Engineering Design News article on the subject.


Is there a thermal sensor with a distance of 10 meters for Arduino I am looking for a thermal sensor with a distance of 10 meters . In my plan , I would like to recognize objects based on the heat. for example car.

How about this one at £20?

The range depends on what lens you put in front of it - this has to be plastic as IR doesn't penetrate glass, but you can set your own range, like a focus adjustment. Commercial IR remote thermometers generally have aiming dots (laser) so you can see the optimum range - there's a fixed lens.

The actual sensor won't have a defined range, because of this.


Arduino ultrasonic sensor to trigger LED when path is blocked I'm working on a project which has falling objects non stop, I only want to detect when objects block the sensors set trigger area. Any suggestions would be great!

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin1 9 // LED 1

int maximumRange = 300; // Maximum range needed
int minimumRange = 10; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
    Serial.begin(9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(LEDPin1, OUTPUT);
}

void loop() {
    /* The following trigPin/echoPin cycle is used to determine the
    distance of the nearest object by bouncing soundwaves off of it. */
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

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

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

    //Calculate the distance (in cm) based on the speed of sound.
    distance = duration/58.2;

    //If the distance is beyond the limits - then nothing happens ie,
    //more than 3 meters or less than 10 cm
    if (distance >= maximumRange || distance <= minimumRange) {
        Serial.println("Nothing Happens");
        digitalWrite(LEDPin1, LOW);
    } else {
        Serial.println("Trigger");
        digitalWrite(LEDPin1, HIGH);
        delay(200);
        delay(50);
    }
}

Arduino uno
4 pin ultrasonic sensor

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

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

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

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

    distance = duration/58.2;

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

delay(10);
}


Arduino Micro serial communication is not working after wake from power down I'm trying to use the power down state for a battery application, but I'm having issues with the serial communication.

I'm using the lowpower.h library to put the Arduino Micro into power down mode.

When it wakes I flash an LED, which is working, so I know it's is waking up. And I also re-establish serial communication and send a message. This is not working. I receive nothing on the serial monitor, however the TX LED does flash.

I think the Arduino may be working correctly, but for some reason the serial monitor can't handle it. Perhaps there is a better serial monitor application?

#include "LowPower.h"

void setup()
{
    //20sec delay added to make uploading easier (cant upload in power down state)
    Serial.begin(115200);
    Serial.println("20");
    delay(5000);
    Serial.println("15");
    delay(5000);
    Serial.println("10");
    delay(5000);
    Serial.println("5");
    delay(5000);
    Serial.println("START");
    pinMode(LED_BUILTIN, OUTPUT);
    delay(1000);
    Serial.end();
}

void loop()
{
    // Enter power down state for 8 s with ADC and BOD module disabled
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

    Serial.begin(115200);
    delay(100);
    Serial.println("BLINK");
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(5000);                       // wait for a second
    Serial.println("BLINK_stop");
    digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
    delay(5000);                       // wait for a second

    Serial.end();

}

Serial monitor output:

20
15
10
5
START

and then nothing...

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);


Library to set internal analog gain of the Arduino? My original question was if there is a library that covers the internal comparator and differential and gain modes for the Arduino Uno, Mega 2560, Leonardo, Due, Zero, M0.
The answer is obvious: "No". To my surprise there is not even a start to make it and neither a collaboration to gather usefull code.

If you know pieces of code (Arduino compatible and documentation for which pins) for the analog comparator and gain, then please tell me about it, and I put them in this list.

analogComp, a library to manage the analog comparator.
To use the analog comparator for the ATmega8, Arduino Uno, Leonardo, Mega 2560, ATtiny85, and others. A routine is called with an interrupt every time a particolar condition happens.
Arduino Differential ADC and Gain ADC
A file "wiring_differential.c" should be added to the Arduino files. Functions "analogReadDiff" and "analogReadGain" will be added. For the Arduino Leonardo and the Arduino Mega 2560.
Nick Gammon: Using the Arduino Analog Comparator
A simple example of a comparator mode for the ATmega328.
Application Note AT11480: Analog Comparator Application Examples
Using the Analog Comparator for SAM D (that includes the ATSAMD21 of the Arduino Zero and M0) processors.

I would recommend you to check Nick Gammon's example on using the analog comparator by means of configuring the relevant flag bits of registers in the ATmega328. Sample code from the link, by Nick:

volatile boolean triggered;

ISR (ANALOG_COMP_vect)
  {
  triggered = true;
  }

void setup ()
  {
  Serial.begin (115200);
  Serial.println ("Started.");
  ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
  ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
        | bit (ACIE)    // Analog Comparator Interrupt Enable
        | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)
   }  // end of setup

void loop ()
  {
  if (triggered)
    {
    Serial.println ("Triggered!");
    triggered = false;
    }

  }  // end of loop


DIY Arduino technical difficulties I followed this ArduinoToBreadboard and I just added a 5V regulator just to be on the safe side.

So my questions are:

When I connect a Nokia LCD 5110 to the DIY arduino, nothing really happens but when I take out the AtMega328P-PU chip and place it to the official arduino board the screen works normally, why does this happen? (The pins are connected on the same way, it is not this kind of problem)
How can I make this DIY arduino to work with a 3.7V Li-op battery? Because the DIY board works only when I power it up with 5 or more Voltage it works perfect, so any ideas?

So. You say you have build an Arduino on a breadboard, is that right?

Have you checked all the pins, so they are all connected up properly? Can you post some pictures of the protoboard? Maybe you missed something, didn't connect all GND pins to each other if there are more on the arduino or something.
You can power the Arduino using a 3.7 Lion or Lipol battery using a boost-converter, here is a great video explaining how you can build your own (https://www.youtube.com/watch?v=QnUhjnbZ0T8), or you can just order one from Ebay.

Great Scott (the author of the video) also made a video on how to create a standalone Arduino: https://www.youtube.com/watch?v=J3DYgzRvLT8 . Check the videos out! Hope I helped you.


mySerial.available() is returning 0 I am using bluetooth hc-05, arduino uno and ap app created by mit app inventor.The problem is myserial.available is returning 0 and hence its loop is not getting executed. I had connected four pins of the hc-05 module. Rx to pin 10, Tx to pin 11, VCC to 5V, GND to GND. On the app it is showing that the mobile is connected to HC-05 however the condition is not met.

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

String name="";
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  Serial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.println("Bluetooth is connected");
    name=mySerial.read();
    Serial.println(name);
  }
  else
 {
   Serial.println("Bluetooth is not connected");
  }
}

I found out my solution. Actually I was connecting Rx to Rx and Tx to Tx.


How do I use a 5v/120v relay that is not mounted on a board I bought an arduino kit, and it came with, amongst other things, a 5v relay to control 120-220v.

The relay is only that, there is only the 5 pin relay, and it's not on a board on which one can screw in the leads

I was wondering how I can use it..  i.e. how do I mount it somehow (especially since the leads are metric and most perf board is standard (or vice-versa)).

I don't mind soldering the 5v control leads from the arduino, but I'm not so sure about soldering or connecting 110v straight on the relay.  i'm worried about long term longevity.

I have soldered longer leads just to be able to fit it on a board for tests, but those are tiny, and aren't safe for higher voltage/current.

Any suggestions?
Thanks, Seb.

What I did with a similar looking 'module' (An AC/DC converter), was to use a protoboard/perfboard. Some holes fitted in the existing holes, others I drilled with a small drill.

On the back you can solder the wires you need, so for the 110V wires you might use thicker wires than for the controls.

Than if you want to make it fancy, you add some terminal blocks to connect the external wires too. Terminal blocks looks like this:


Arduino Zero RTC alarm not running loop Using an ATSAMD21 with the Arduino core, I'm running into an issue where the RTCZero alarm callback won't continue running the loop() function. If I schedule another alarm inside the callback, the second alarm will execute the loop() function after the callback is done. Every second time it works, every other time it doesn't.

Minimal example in which I expect the LED to change state every 2 seconds, which does not happen:

#include <RTCZero.h>
#include <time.h>

RTCZero rtc;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  rtc.begin();
  rtc.attachInterrupt(alarmMatch);
  schedule_wake_up();
  rtc.enableAlarm(rtc.MATCH_HHMMSS);
}

void loop()
{
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  schedule_wake_up();
  rtc.standbyMode();    // Sleep until next alarm match
}

void schedule_wake_up() {
  time_t wakeupTimestamp = rtc.getEpoch();
  wakeupTimestamp += 2;
  struct tm *wakeupTimeStruct = gmtime(&wakeupTimestamp);

  rtc.setAlarmSeconds( wakeupTimeStruct->tm_sec );
  rtc.setAlarmMinutes( wakeupTimeStruct->tm_min );
  rtc.setAlarmHours( wakeupTimeStruct->tm_hour );
}

void alarmMatch()
{
  // Do nothing, just wake up
}

Arduino IDE 1.8.9
RTCZero ver 1.6.0
SAMD core ver 1.8.4 and 1.6.20 tried

I ended up deleting my copy of RTCZero and installing a new one via the Arduino IDE library manager. This solved the issue.

The difference between my local copy and the upstream one is in the standbyMode() function. I had the following PR merged into my local copy of this function:
https://github.com/arduino-libraries/RTCZero/pull/46/files

After I installed the clean copy I went and replaced the standbyMode() function's content with the following:
https://github.com/arduino-libraries/ArduinoLowPower/blob/892594adbccf45b198fc067ea994048c76523936/src/samd/ArduinoLowPower.cpp#L18


Need a sensor to make ball roll away from pet but which sensor? Having recently entered the world of Arduino I am seeking to make, as my first project, a ball that will sense my dogs approach and roll away.

I can handle the rolling part but I have been unable to find a sensor that will work when fully embedded in the ball (so the dog cannot bite or swallow it). This means no ultrasound or infra red or normal proximity sensor will do.

My best bet - an inductive proximity sensor (with a metal object attached to dog's collar) is only effective at a maximum distance of 8 cm and that is far too little. I need something that activates at say 1 foot.

Any ideas anyone?

Perhaps an RFID tag on your dogs collar and a reader inside the ball will work.
You will just have to find a reader and tag combination that can work from the range you need, I think some RFID can work from over 1ft.
EDIT: You will need active tags (battery powered) to get over a foot range.

PIR sensors detect heat given off by humans and animals, so they make work through the ball. (not totally sure though).

Edit: i think PIR that is capable of detecting small animals may be your best bet you would just have to calibrate the range of detection some how


LCD displays an "A" instead of 0 I am trying to make a timer that has a accuracy up to 1 tenth of a second. However when it is suppose to print "0", it will print an "A". For example, when printing "10", it will print "1A".
This program only lasts up to seconds. Any suggestion is highly appreciated, thank you!

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
unsigned long time2 = 0;
int x = 0;
int a = 0;
int b = 0;
void setup() {
  lcd.begin(16,2);
  lcd.backlight();
  lcd.setCursor(0,0);
  lcd.print("00:00:00:0      ");
  Serial.begin(9600);
}

void loop() {
  unsigned long time1;
  time1 = millis();
  if (time1 - time2 > 100){
    time2 = time1;
    lcd.setCursor (9,0);
    x=x+1;
    lcd.print(x," ");
  }
  if (x>=10){
    x=0;
    a=a+1;
    lcd.setCursor(7,0);
    lcd.print(a,":");
  }
  if (a>=10){
    a=0;
    b=b+1;
    lcd.setCursor(6,0);
    lcd.print(b+a);
  }
}

Here is my Suggestion: In cases a clear answer could not be seen, you have to remove any weaknesses step by step to further encircle the problem. Since there is now answer for more than a month, I assume this as an appropriate proceeding.

One weakness I see in your coding is, that you are counting your values x, a, b, up to ten and you are printing them bevor reseting them to Zero, so your are printing 'x' even if it is ten. If for any reason in the further handling your display shows HEX values, you will end up displaying an 'A'. Change your Code so that values > 9 are not printed out, than this weakness will be removed.


incompatible types in assignment of 'int*' to 'int [0]' I was coding a class for "a kind of gun". I have this code for the classes:
Gun.h:

#ifndef Gun_h
#define Gun_h

#include "Arduino.h"

class Gun
{
  public:
    Gun(String identifier, String name, int teamIRCodes[]);
    String getIdentifier();
    String getName();
    int getIRCode();
  private:
    String _identifier;
    String _name;
    int _teamIRCodes[];
};

#endif

Gun.cpp:

#include "Arduino.h"
#include "Gun.h"

Gun::Gun(String identifier, String name, int teamIRCodes[])
{
  _identifier = identifier;
  _name = name;
  _teamIRCodes = teamIRCodes;
}

String Gun::getIdentifier(){
  return _identifier;
}
String Gun::getName(){
  return _name;
}
int Gun::getIRCode(){
  return _teamIRCodes[1];
}

It returns me this error while compiling:

sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

   _teamIRCodes = teamIRCodes;

                ^

exit status 1
incompatible types in assignment of 'int*' to 'int [0]'

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don't recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:

// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:

for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it's much simpler to use a pointer:

int* _teamIRCodes;

Then you can make your ctor:

Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don' forget to add a dtor:

~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:

 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).


IDE to program Arduino Uno especially internal interrupt vectors I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?

What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.

Suggestions?

You can do all you need to do in the Arduino IDE.  It doesn't "block" you from doing any low-level operations.  Any other IDE will also allow you to do what you want.

All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.

http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf


Expected } at the end of input I am getting the error in my title when I try to compile the following code:

#define char incomingByte; //Defines incomingByte
#define char sendBack = K;
#define char ?;
#define pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}

void loop() {
for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.
pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.
incomingByte  = Serial.read();
if(incomingByte = ?) {
Serial.print(sendBack);
  }
 }
}

Your code is completely wrong in almost every respect.

#define char incomingByte; //Defines incomingByte

That line means that the compiler will substitute incomingByte; whenever it sees char.

#define char sendBack = K;

Now it will substitute sendBack = K; when it sees char.

#define char ?;

Now it will substitute ?; when it sees char.

#define pollTime;

I don't know what you are thinking here. If you are trying to declare a variable you have to give a type, like this:

int pollTime;

bool running = true;

void setup() {
Serial.begin(9600); //Set data rate.
}
void loop() {

Those lines are OK.

for(Serial.available() > 0;)  { //Gets you the number of bytes that are available to be read from the serial port.

You don't want the semicolon there. A for loop is not written like that. You possibly mean while, ie.

while(Serial.available() > 0)

pollTime = delayMicroseconds(200); // Sets a poll time of 200 microseconds.

That is doing nothing of the sort. It is delaying 200 µs, it isn't setting anything.

incomingByte  = Serial.read();

That line is OK, assuming you declared incomingByte like this, and not the way you did:

char incomingByte;

if(incomingByte = ?) {

That needs to be in single quotes, as you are comparing a character. Also you compare with == not = ie.

if(incomingByte == '?') {

Serial.print(sendBack);

It looks from your earlier code you mean:

Serial.print('K');

  }
 }
}

These lines look OK.

I suggest you read a beginners page about C programming. This is just pure guesswork what you are doing here. For one thing, read up on how #define works. Here is one page: https://www.techonthenet.com/c_language/constants/create_define.php. And another: http://www.cprogramming.com/reference/preprocessor/define.html


Response from ESP8266 is returning unknown characters I'm working on a project with Arduino UNO that needs connection with a cloud server, that is why I'm using ESP8266 module.

I'm already connecting to wi-fi and making GET and POST request but my problem is get the response from these requests.

Here is my code:

/* Doing all these steps to make the request
AT+RST
AT+CWMODE=1
AT+CWJAP="MyNetwork","MyPassword"
AT+CIPMUX=1
AT+CIPSTART=0,"TCP","myserver.com.br",80
AT+CIPSEND=0,270
*/

String data = "data=example";

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
comando += "User-Agent: Arduino/1.0\r\n";
comando += "Connection: Close\r\n";
comando += "Content-Type: application/x-www-form-urlencoded;\r\n";
comando += "Content-Length: " + String(data.length()) + "\r\n\r\n";
comando += data;

esp8266.println(command);

delay(2000);

String response;

while(esp8266.available()) {
  response += esp8266.readStringUntil('\r');
}

Serial.print("Request response: ");
Serial.println(response);

When I run this code the only response I can get is something like:

Recv 270 bxt⸮⸮C⸮
SEND OK

+IPD,0.569:HTTP/1.0 200 OK

But I was expecting a JSON.

Can someone tell me what I am doing wrong and how can I resolve it?

Edit.

Ok, after Code Gorilla helps me (Thank you so much) and a lot of research what I did was program Arduino UNO to send some commands that I invented to serial and program ESP8266 to read the serial and, depending of the command that it reads, do requests and stuff.

ESP8266 is a lot easyer to make requests and have a lot of others possibilities, like HTTPS requests, that you can't do using AT Commands.

When I create this ask I didn't know that I could program directly in ESP8266, but when Code Gorilla told me about it and helps me with some articles I could finally continue with my project.

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
...
esp8266.println(command);

I suspect this is just a typo because it shouldn't compile.  But you are adding all the HTTP headers to commando not command.

Usually the ? means that the character is unprintable.  So to help diagnose the issue display the integer value for each character that is returned.  Something LIKE this (I've never used a String before so length() might not be right)

Serial.print("Request response: ");
Serial.println(response);
for (int index = 0; index < response.length(); ++index)
{
   Serial.print (response[index]);
   Serial.print (" ");
}

If you want to program the ESP directly then have a look at these guides, they should give you the general idea.  Its usually as easy as programming an UNO once you are setup.

http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
https://www.hackster.io/harshmangukiya/how-to-program-esp8266-with-arduino-uno-efb05f


I am building an robotic arm by using flex sensor, servo and 2 xbees Rx Code:

#include <Servo.h>
Servo myServo;

void setup() {
Serial.begin(9600);
myServo.attach(9);
delay(5000);
myServo.write(0);
}

void loop() {
  while(Serial.available()==0);

    int d = Serial.read() - '0';
    if(d>0)
    {
      int pos = map(d,0,9,0,180);
      pos = constrain(pos,0,180);
      myServo.write(pos);
      Serial.println(d);

      delay(50);
      }
      else
      {};

}

Tx code:

int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
int SensorMid = 0;
const int POWER_OF_TWO_TO_AVERAGE = 6;

void setup() {
pinMode(13,OUTPUT);
  Serial.begin(9600);

  while (millis() < 10000) {
    digitalWrite(13,HIGH);
    sensorValue = analogRead(A1);
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
  SensorMid = (sensorMin + sensorMax )/2;
  digitalWrite(13,LOW);
  }

void loop() {
int val = map(analogRead(A1),SensorMid,sensorMax,0,9);
Serial.println(val);
delay(100);
}

I am building a robotic arm and I am facing some problems regrading to the servos stability with the flex, I am using the flex as the transmitter and the servo as the receiver, and when I press my finger my servo doesn't move properly.

Any suggestions?

Without knowing more about the actual problem of "doesn't move properly", what I initially see is that you are transmitting values 0-9 by using Serial.println(), which sends the byte data, and also a newline (ASCII value 10), so your RX code is probably getting alternating input of the intended value, and the value 10, which is getting subtracted from 48 (the ASCII value of '0'), mapped and constrained to 0.

Try changing your TX script to call Serial.print() instead. Your receiver doesn't care about each value showing up on a new line -- it doesn't know about lines.


Why doesn't OTA work with the Ai-Thinker ESP32-CAM board? I have working code on an Ai-Thinker ESP32-CAM board, programming over serial.

I would like to reprogram using OTA, but adding in the functionality from the BasicOTA sketch (which I have done on various other boards successfully) fails when OTA programming is attempted, the board reboots following an abort() and a stack trace is generated.

The invaluable ESP32 exception decoder shows the fault occurs from checking if memory location is safe to write.

Normally, I would choose a partition option which includes OTA, but the Ai-Thinker board doesn't have this option in the IDE

The boards.txt file configures what can be configured in the Arduino IDE for each board.

On my installation, this is found at
C:\Users\MyUser\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.4\boards.txt

I found the section esp32cam.name=AI Thinker ESP32-CAM and changed the lines:

esp32cam.upload.maximum_size=3145728
esp32cam.build.partitions=huge_app

to

esp32cam.upload.maximum_size=1966080
esp32cam.build.partitions=min_spiffs

The various options are detailed in the same file with keys named esp32.menu.PartitionScheme., and for some boards these options are configurable be the user. To add this, remove (or comment out with a # character) the two lines found above so they look like:

# esp32cam.upload.maximum_size=3145728
# esp32cam.build.partitions=huge_app

and add the required menu selections for your application- e.g.

esp32cam.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32cam.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32cam.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32cam.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (Large APPS with OTA)
esp32cam.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32cam.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080

After making any changes to boards.txt, restart the Arduino IDE for the change to take effect. Note that these changes (and any changes to the installation) may be overwritten by any future upgrades or library updates, so note your changes so they can be easily reapplied.

Alternatively, add the menu lines to boards.local.txt, introduced in Arduino 1.6.6 so they should persist during updates. In this case, no change needs to be made to boards.txt, as the boards.local.txt entries override those in boards.txt. I haven't tested this, hopefully it works across library updates and IDE upgrades.


What is the best Arduino board for a Quadcopter with camera and Wifi? I need to design a Quadcopter that contains a camera , ultrasonic sensors and Wifi connection to broadcast images in order to do image processing on a computer

Given the current (lack of) detail of the question, the best advice I can give you is to have a look at instructables.

You will find many options with varying cost, complexity and range of applications.

It should help you form a better vision, in case you still do not have one good enough to make the choice of components obvious.