serial 1 was not declared in the scope #include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#include <SoftwareSerial.h>

char Mob[20]="+923319020922";
String stringGPS = "";
String stringGPS1 = "";
char c=0;
int t=0,i;
int buzzer = 9;
int buttonState = 0;

SoftwareSerial mySerial(10, 11); // RX, TX

//const int buttonPin1 =9 ;
int buttonState1 = 0;
int helmetstate=0;
const int relay=8;
char inByte=0;

void setup()
{
  lcd.begin(20, 4);
  lcd.setCursor(0, 0);
  pinMode(relay, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  digitalWrite(relay, LOW);
  delay(15000);
  lcd.print("Config modem....");

  Config();

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Smart helmet      ");
}

void loop()
{
  if(Serial2.available())
  {
    inByte = Serial2.read();
    //Serial.write(inByte);
    if(inByte=='A'||inByte=='B'||inByte=='C'){
    inByte=0;
    SMS(Mob);

    while(Serial2.available()>0)
    {
      i = Serial2.read();
    }
  }

  if(inByte=='D')
  {
    digitalWrite(relay, LOW);
    inByte=0;
  }

  if(inByte=='E')
  {
    digitalWrite(relay, HIGH);
    inByte=0;
  }
  else
  {
  }
}

 //buttonState = digitalRead(buttonPin);
 // if (buttonState == LOW) {
 //Serial.print("ok");
 //lcd.clear();
 // lcd.setCursor(0, 0);
 //lcd.print("Sending msg       ");
 // lcd.setCursor(0, 0);
 //lcd.print("Smart helmet      ");
 // checkGPS();
 // SMS(Mob);

 //helmet();
 checkGPS();
 lcd.setCursor(0, 1);
 lcd.print(stringGPS1);
 //Serial.println(stringGPS1);
}

/*
void helmet()
{
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH ON  .......    ");
    digitalWrite(relay, HIGH);
  }
  else
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH OFF .......    ");
    digitalWrite(relay, LOW);
  }
}
*/

void checkGPS()
{
  // Serial.print("check gps");
  // while (Serial.available())
  // {
  if (Serial.available()>0)
  {
   // c = Serial.read();
   // stringGPS  = c;
   //Serial.print(c);
   while (c != 'R')
   {
     c = Serial.read();
     // Serial.print(c);
   }
    // if (c== 'R')
    // {
    //   Serial.print(c );
         while(t!=41)
         {
           if (Serial.available())
           {
             c = Serial.read();
             stringGPS += c;
             t++;
             //Serial.print(stringGPS );
          }
  }
  stringGPS1= stringGPS.substring(15, 41);
  // Serial.println(stringGPS1);
  t=0;
  c=0;
  stringGPS = "";
    // }
  }
  }

void SMS(char Mob[20])
{
   digitalWrite(buzzer, HIGH);
   lcd.setCursor(0, 0);
   lcd.print("Sending msg       ");
   Serial1.print("AT+CMGS=\"");     // send the SMS number
   Serial1.print(Mob);/// Send mobile number
   Serial1.print("\"\r");
   delay(4000);
   Serial1.print(stringGPS1);// send the SMS Data
   Serial1.print("\r");
   delay(2000);
   Serial1.write(0x1A);  ///Ctrl+Z
   delay(1000);
   Serial1.write(0x0A);  ///Carrige return
   delay(1000);
   Serial1.write(0x0D);    ///line feed
   delay(1000);
   stringGPS1 = "";
   lcd.setCursor(0, 0);
   lcd.print("Smart helmet      ");
   digitalWrite(buzzer, LOW);
}

void Config()/////configuration for sim900
{
  delay(4000);
  Serial1.print("ATE0\r"); ////Disable Echo
  delay(4000);
  Serial1.print("AT\r"); ///checking echo
  delay(4000);
  Serial1.print("AT+CMGF=1\r");///msg format
  delay(4000);
}

when i run this code it give me error that serial1 was not decleared in the scope

The only SoftwareSerial you a declaring is SoftwareSerial mySerial(10, 11); // RX, TX

(And you you didn't use it afterwards).

If the hardware serials Serial1, Serial2 or Serial3 are available
(and already declared in the arduino.h header depends on the board you are using.


Can I use 5V 1A Adapter to power Arduino UNO? I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).

My question is can use any of these to power my Arduino UNO with a barrel connector?

What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.

If we look at technical specifications, it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (never go above 20V). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.


How to calibrate the MQ7 sensor module? I recently bought a MQ7 sensor module like the one in the attached picture. I have read several tutorials, and they're all different. Some of them says that i need to connect the module directly to 5v and wait 24 hours to made it work properly, others says that i need to program different periods (5v and 1.4v) and wait the same time to make correct meditions. I read this Datasheet, but i think that the information it has is not for the module.

If anyone knows how to setup this module i will aprecciate an answer (i want to read analog values).

Thanks in advance and sorry for my bad english.

first of all, you need to understand how these sensors work.

the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC


Which EEPROM has a long lifecycle? I would like to build a box counter for machine, so I'm going to use EEPROM in Arduino to save count. But the lifecycle is limited to 100,000 writes. Please suggest an external EEPROM with a long lifecycle or any other solution.

You can cycle through all the addresses in the EEPROM like a ring buffer.

You'll need to reserve a bit so you can binary search for the head of the buffer during startup.

You can also reduce how often you write in general especially when the count will increment in bursts, try and wait out those bursts instead of writing on every increment.


Separate control unit from Leds i am using one adapter (12vDC 2A) i want to be able to power led strip with it plus the control circuit the problem is that the atmega328 reboots but when i only powers up the led strip with that adapter and power the control circuit with a independent 5v adapter every thing seems to be alright but i cannot do that in real world i need to get advantage of the same adapter i attached a picture of what i am doing right now help me to fix this
i am using 7805 regulator to reduce the 12v to 5v

Why not use the barrel input connector and input 12VDC there, the filtering etc on the board will help. Also as dandavis stated you need a bigger power supply or remove about 1/2 of your LEDs.


Serial communication mac to Digispark ATtiny85 I want to use the Arduino IDE serial monitor with my Digispark ATtiny85 over USB.

I can without problems upload this code(Digispark CDC example):

#include <DigiCDC.h>
void setup() {
  SerialUSB.begin();
}
void loop() {
  SerialUSB.println(F("TEST!"));
 //SerialUSB.delay(10);
}

In a terminal, I can confirm, that it indeed creates a new devise:

ll /dev/*usb*
crw-rw-rw-  1 root  wheel   21,  89 27 Sep 10:36 /dev/cu.usbmodem1411
crw-rw-rw-  1 root  wheel   21,  88 27 Sep 10:36 /dev/tty.usbmodem1411

When trying to start the Arduino serial monitor, I get the error:

 Error opening serial port '/dev/cu.usbmodem1411'. (Port busy)

I have confirmed that there are no open files or processes using the USB port. I have the same problem trying to use cu or screen in the terminal.

I have googled the problem, and found that several people has the same problem on new mac computers, but I have not been able to find a solution. -any ideas?

Digispark Rev3 (Chinese clone - with bootloader firmware 1.6 (1.06))
Arduino IDE 1.8.7
Mac OSX High Sierra 10.13.6

SoftSerial and a real serial port on the mac will work. Or if you are careful use the DigiKeyboard and print the debug to the HID keyboard REMEMBERING to switch to a notepad equivalent window on the mac to receive and display the debugging text and not have it overwriting the arduino sketch by mistake.
DigiCDC is a kludge that does not work properly on modern operating systems sorry!


Is if statement correct? if(temperature < baselineTemp)else{
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
}else if(temperature >= baselineTemp+2 && temperature < baselineTemp+4){
  digitalWrite(2, HIGH)
  digitalWrite(3, LOW)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+4 && temperature < baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, LOW)
}else if(temperature >= baselineTemp+6){
  digitalWrite(2, HIGH)
  digitalWrite(3, HIGH)
  digitalWrite(4, HIGH)

No, the first lines should be:

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

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

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

Also, your code can be much more simplified.

Hence the following (reverse engineered) requirements:

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

So your entire code can be written as:

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


Would this substitute for an Interrupt timer? class Pseudo_Interrupt {
  //only cummulative time is important, exact interval is not
  // Class Member Variables
  // These are initialized at startup
  long OffTime = 1000; // milliseconds of off-time
  // These maintain the current state
  unsigned long previousMillis; // will store last time updated

  void Update() {
    // check to see if it's time for an Interrupt
    unsigned long currentMillis = millis();
    if ((currentMillis - previousMillis >= OffTime) {
      //Time to execute the one second code
    }
  }
}

The whole idea is sound, but I would make a few changes:

as explained by Jot in a comment, you have to update previousMillis
inside the if statement. You have two choices:

set it to currentMillis, then OffTime will be the minimum time
between the pseudo-interrupts
increment it by a constant amount, which I would call period, then
this will be the average time between pseudo-interrupts; this is
more similar to how real timer interrupts work

add a constructor for:

making the period user-selectable
making the action of the timer user-selectable via a callback
initializing previousMillis

With those changes, the class will look like:

class Pseudo_Interrupt {
    unsigned long period;
    unsigned long previousMillis;
    void (*callback)();

public:
    Pseudo_Interrupt(void (*callback)(), unsigned long period)
        : period(period), previousMillis(millis()), callback(callback)
    { }

    void update()
    {
        if (millis() - previousMillis >= period)
        {
            callback();
            previousMillis += period;
        }
    }
};


How to pause Arduino for 1 millisecond through MATLAB? I have been able to connect MATLAB to my Uno with this line of code: a = arduino('COM4'); through this package: Matlab support package for Arduino.

Right now, MATLAB is my main script that will synchronize all the components [like the Arduino].

I am able to send pulses to my stepper-motor just by using:

void loop() {
    digitalWrite(2, HIGH);
    delay(1);
    digitalWrite(2, LOW);
    delay(1);
}

This works fine, and will make the motor move about once every 2 milliseconds. My problem is that I cannot find a way to produce this same delay through MATLAB's interface. I do know that MATLAB has a pause() function, but when I set up a loop in MATLAB like this:

a = arduino('COM4');
for m = 1:400
    a.digitalWrite(2, 1);
    pause(0.001);
    a.digitalWrite(2, 0);
    pause(0.001);
end

Each step takes WAY longer - about 200 milliseconds each.

What are other options for creating the pause between digital High / Low being sent to the Arduino? It would be nice if I could control the outcome from Matlab, through Arduino.

The increased in observed delay is due to the time it takes to send the command from MATLAB to the Arduino have its code execute the requested command. In your case the a.digitalWrite. So actual time between pulses using MATLAB's delay is 0.001 pause plus the time of baud rate times the packet size and decoding then execution.

I would recommend not pursuing this solution of the MATLAB controlling the timing of Step Motors, remotely. As this latent coupling will be a frustrating limitation. Noting that for step motors the timing can not afford such latent execution. Hence all the 3D printers and many CNC with Step Motors use Arduino's which get G-Code (motor move commands with destinations) and the Real-time firmware handles the stepping, within tolerances.

I would suggest using something like grbl firmware with step motor shield and then have the MATLAB send the needed G-code. Where there are others with much more features but tailored to 3d Printing. grbl is simpler and straight to the point of moving motors.


Reading tiny voltage changes I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.

But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).

Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?

Thank you,

Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659
Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

You could try using analogReference(INTERNAL);, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.


STPM10 using Arduino SPI communication I am working with STPM10 energy metering chip (evaluation board) and I want to read the data from 8 internal registers of the chip each containing 32 bits.

The datasheet of the STPM10 chip suggested to have a simplex synchronous SPI where the MOSI of the Arduino is not connected to any pin on the energy chip. Instead they provided a timing diagram to switch from reading and writing on the energy chip.

After the t5, datasheet stated that we should apply 32 serial clocks per data record and up to 8 data records can be read this way. My problem is how to apply 32 serial clocks to the chip.  Is the Serial clock on the Arduino SPI automatically activated after SPI.begin() ? If not, how can I start the serial clock? By the way, this is the code I've written:

#include <SPI.h>

SPISettings settingA(32000000, LSBFIRST, SPI_MODE0);
const byte SYN = 8;
void setup() {
  Serial.begin(9600);
  pinMode(SYN,OUTPUT);
 /*Initializes the SPI bus by setting SCK, MOSI and SS to outputs
  Pulling SCK, and MOSI low, and SS high */
  SPI.begin();
  SPI.beginTransaction(settingA);

  }

void loop() {
  //0----->t1
  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(500);
  //t1----->t2
  digitalWrite(SYN,LOW);
  delayMicroseconds(1000);
  //t2----->t3
  digitalWrite(SYN,HIGH);
   delayMicroseconds(0.035);
  //t3----->t4
  digitalWrite(SS, LOW);
  delayMicroseconds(0.035);
  //t4----->t5
  digitalWrite(SYN, LOW);
  delayMicroseconds(0.035);
  //t5---->t6
  digitalWrite(SYN, HIGH);
  delayMicroseconds(0.035);

  byte d1 = SPI.transfer(0x00);
  byte d2 = SPI.transfer(0x00);
  byte d3 = SPI.transfer(0x00);
  byte d4 = SPI.transfer(0x00);
  byte d5 = SPI.transfer(0x00);
  byte d6 = SPI.transfer(0x00);
  byte d7 = SPI.transfer(0x00);
  byte d8 = SPI.transfer(0x00);
  byte d9 = SPI.transfer(0x00);
  byte d10 = SPI.transfer(0x00);
  byte d11 = SPI.transfer(0x00);
  byte d12 = SPI.transfer(0x00);
  byte d13 = SPI.transfer(0x00);
  byte d14 = SPI.transfer(0x00);
  byte d15 = SPI.transfer(0x00);
  byte d16 = SPI.transfer(0x00);
  byte d17 = SPI.transfer(0x00);
  byte d18 = SPI.transfer(0x00);
  byte d19 = SPI.transfer(0x00);
  byte d20 = SPI.transfer(0x00);
  byte d21 = SPI.transfer(0x00);
  byte d22 = SPI.transfer(0x00);
  byte d23 = SPI.transfer(0x00);
  byte d24 = SPI.transfer(0x00);
  byte d25 = SPI.transfer(0x00);
  byte d26 = SPI.transfer(0x00);
  byte d27 = SPI.transfer(0x00);
  byte d28 = SPI.transfer(0x00);
  byte d29 = SPI.transfer(0x00);
  byte d30 = SPI.transfer(0x00);
  byte d31 = SPI.transfer(0x00);
  byte d32 = SPI.transfer(0x00);

  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(499);

  Serial.println(String(d4,BIN) + " " + String(d3,BIN) + " " +  String(d2,BIN) + " " +  String(d1,DEC));
  Serial.println(String(d8,BIN) + " " + String(d7,BIN) + " " +  String(d6,BIN) + " " +  String(d5,BIN));
  Serial.println(String(d12,BIN) + " " + String(d11,BIN) + " " +  String(d10,BIN) + " " +  String(d9,BIN));
  Serial.println(String(d16,BIN) + " " + String(d15,BIN) + " " +  String(d14,BIN) + " " +  String(d13,BIN));
  Serial.println(String(d20,BIN) + " " + String(d19,BIN) + " " +  String(d18,BIN) + " " +  String(d17,BIN));
  Serial.println(String(d24,BIN) + " " + String(d23,BIN) + " " +  String(d22,BIN) + " " +  String(d21,BIN));
  Serial.println(String(d28,BIN) + " " + String(d27,BIN) + " " +  String(d26,BIN) + " " +  String(d25,BIN));
  Serial.println(String(d32,BIN) + " " + String(d31,BIN) + " " +  String(d30,BIN) + " " +  String(d29,BIN));
  Serial.println(" ");

The STPM10 specification describes a SPI bus unlike any I have seen.  Apparently the STPM10 "SYN" line controls the direction of the "SDA" line.  As far as I know, there is no "SYN" line in a SPI bus.  As such I do not think a normal Arduino SPI library will talk to an STPM10.

A normal single port (MOSI and MISO combined) SPI slave would automatically switch between reading and writing bits.  When interfacing with a two port master (such as an Arduino) a resistor is used between the MISO and MOSI nets.

This is the best image I could find.  Ignore the chip names.  And substitute MOSI for SDO and MISO for SDI.  Note there is no "SYN" line in this SPI bus.

I'm showing this diagram as it appears the STPM10 is using a single line for both input and output data.

Because of the missing "SYN" line I do not think you can even use the SPI hardware in the Arduino's Atmel processor.  I think your only option is to create a SPI driver from scratch only using software.

I see where STMicroelectronics offers an evaluation software package that talks to the STPM10.  Guessing, it looks like they wrote it in National Instruments Lab View.  If you could get the source code for that it may provide hints on writing your own STPM10 driver.


undefined reference to `PPMintIn::PPMintIn(int)' I am making a new library that will utilize PinChangeInt's library.
My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.)
Since i understand OOP i knew that i could go the route of make my own library.

The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is

  C:...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0':
  C:...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)'
  C:...\RCRoomba_TestPulseV2.cpp.o: In function 'setup':
  C:...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()'
  Failed linking sketch

I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.

Here is the .ino code.
for some reason UECIDE can't see the Pinchange and PPMint libraries

#include "arduino.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h"
#include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h"

PPMintIn CH1(A0);

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

void loop(){
}

Here is the .cpp code

#include "arduino.h"
#include "ppmintin.h"
#include "PinChangeInt.h"
//defined these
volatile int pwm_value = 0;
volatile int prev_time = 0;
uint8_t latest_interrupted_pin = 0;

PPMintIn::PPMintIn(int pin){
    pinMode(pin, INPUT);\
    digitalWrite(pin, HIGH);
    _pin = pin;
}

void PPMintIn::rising(){
    PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::falling(){
    PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin;
    PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);
    PPMintIn::pwm_value = micros()-PPMintIn::prev_time;
}

void PPMintIn::begin(){
    PCintPort::attachInterrupt(_pin, &rising, RISING);
}

void PPMintIn::getSignal(){
    return(PPMintIn::pwm_value);
}

Here is the .h code

#ifndef PPMINTIN_H
#define PPMINTIN_H

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
  #else
  #include "WProgram.h"
#endif
#include "PinChangeInt.h"

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

#endif // PPMINTIN_H

here is the full thing in github in case I didn't supply it here.
https://github.com/tisaconundrum2/PPMintIn

As both Majenko and I tried to explain in Pass a member function pointer to a method of a foreign class (EDB Lib) you can't pass a class member function where a static function is expected.

Your error is on:

PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

Error:

/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

PCintPort::attachInterrupt expects a PCIntvoidFuncPtr variable:

int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

That is:

typedef void (*PCIntvoidFuncPtr)(void);

That is a static function (not a class function).

However you have it as a class function:

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

Now you can make rising and falling static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).

The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

Regarding one of the comments:

Unless your class implements operator() this line doesn't make sense:

chan1(15);

Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.


AnalogWrite not working in if statement Arduino Uno with ATMega328P Processor.analogWrite is not working properly in if statement. It changes the brightness of the LED as if there wasn't any if statement at all.

There are 2 potentiometers to create an intervall in which to program increases of the LED brightness, starting at 40% of the maximum. When it's lower than the minimum value, the LED is turned off.

int ledPin = 6;
int sensorPot = 1; // it's a potentiometer for now
int maxPot = 7; // potentiometer
int minPot = 3; // potentiometer
int fortypercent = 255*0.4;
int brightness = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(sensorPot, INPUT);
  pinMode(maxPot, INPUT);
  pinMode(minPot, INPUT);
  Serial.begin(9600);
}

void loop() {
  int start = analogRead(minPot);
  int maxVal = analogRead(maxPot);
  int sensor = analogRead(sensorPot);
  Serial.println(sensor/4);
  Serial.println(start/4);
  Serial.println(maxVal);
  if(sensor/4 > start/4) {
    analogWrite(ledPin,sensor/4);
  } else if(sensor = baslangic) {
    analogWrite(ledPin,LOW);
  } else if ((start < sensor < maxVal)) {
    brightness = sensor/4 - fortypercent;
    analogWrite(ledPin,brightness);
  } else if (sensor = maxVal) {
    analogWrite(ledPin , 255);
  }
}

ORIGINAL RESPONSE, BASED ON DIFFERENT CODE

You are comparing sensorValue to see if it's ever less than minValue.

However, you have mapped sensorValue to range from 0 to 255, and minValue is set at 0. How can anything from 0-255 be less than zero?

NEW RESPONSE, BASED ON UPDATED CODE

One of your if statements: else if(sensor = baslangic) is not comparing, but assigning baslangic to sensor. To compare, use ==.

Your other if statement: else if ((start < sensor < maxval)) is wrong. C++ doesn't work this way. Maybe you want: if ((start<sensor) && (sensor<maxval))?

Instead, your statement evaluates like if ( (start<sensor) < (maxval) ), which means you are comparing the TRUE or FALSE of (start<sensor) to the int that is maxval.


Why connect arduino with Rasberry pi? I have a question about connecting a Arduino with Raspberry Pi.

What is the benefit of connecting the two?

Interfacing hardware is easier with the Arduino: more available I/O pins
capable of sourcing and sinking more current, 5 V I/O, analog
inputs, very predictable timings, etc. The Raspberry, on the other hand,
is a real computer with a real OS, has a lot more computing power
and memory, has Internet connectivity, can easily run “standard” web
servers like Apache or nginx... or mostly any Linux software for that
matter.

Some projects can benefit from using both. E.g. if you want to make a
web interface for some low-level hardware sensors.


ESP32 Arduino Bluetooth Serial does not reconnect after disconnecting The basic ESP32 Arduino Bluetooth Serial example pairs and connects as expected, BUT once I disconnect the Bluetooth terminal it stops responding to new events at all,
once I reset the esp32, it starts working again with the same problem. (it doesn't matter if it keeps being paired or not)
I have tested it with the windows Bluetooth terminal and with the Bluetooth Any terminal. (from the windows store)
I have downloaded the latest esp32-Arduino library from GitHub and I still get the same problem.
I have tested it with several esp32 modules, and they all respond with the same problem.
So it looks like a bug in the library code.
See the simple Arduino example code below:
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run make menuconfig to and enable it #endif

BluetoothSerial SerialBT;

void setup() { Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); }

void loop() { if (Serial.available()) { SerialBT.write(Serial.read()); } if (SerialBT.available()) { Serial.write(SerialBT.read()); } delay(20); }

Does anyone know of another Bluetooth serial library that does work?
Thank You!

Nothing wrong with your code, I've the exact same issue as you have. It bothers me whole week long and fortunately, we (along with my colleague) accidentally figured that was caused by Windows 10, weird right? We don't believe it at very beginning either, but after several back-N-forth testing, it just like that. When we upload exact same code from another older computer with Windows 7 OS, it just works no matter how many time we connect/disconnect or even "QUIT" the APP without make it disconnect properly, its been able to be reconnect no problem. But once we use new computer with Windows 10 OS to upload the code, it can only be connected for first time, then stop broadcasting (or advertising).
The arduino official website in IDE download page also has a notice message "IMPORTANT: This app performs with core functionality on Windows 10 S but some limited plugins do not work. We are working with Microsoft on a fix.", hope this information helps.


Global variable won't update inside void loop arduino I need to update my global variable once I get a 'overdtrue' response and light up my LED but only my LED is lighting up but my global variable is not updated.

Here is my code

int x = 0;

void loop() {
if (content.indexOf("ovrdtrue") > 0)
 {
  x++;
  digitalWrite(ledPin, HIGH);

 }
fsrReading = analogRead(fsrAnalogPin);
Serial.print("Analog reading = ");
Serial.println(fsrReading);
Serial.print("X: ");
Serial.println(x);
}

The x value should be 1 but only the LED has light up. Please help.

Here is my code

your code ran without setup()?

you are conditionally incrementing "x", and if your condition doesn't hold true, the increment doesn't take place.


too few arguments to function 'void setColor(int, int, int)' When I put "c" inside setColor(c);

it tells me:

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

I understand that I should put 3 arguments. What I don't understand is that the serial is correctly displaying the 3 arguments (255, 000, 000) so why it keeps telling me this error. What am I doing wrong ?

int rPin = 11;
int gPin = 9;
int bPin = 10;

void setup() {
    Serial.begin(9600);
    pinMode(rPin, OUTPUT);
    pinMode(gPin, OUTPUT);
    pinMode(bPin, OUTPUT);
}

void loop() {
    if (Serial.available() > 0) {
            delay(100);
            while (Serial.available() > 0) {
                char c = Serial.read(); // serial will display an rgb code, for exemple: 255, 000, 000 (red color)
                setColor(c);
            }
        }
}

void setColor(int red, int green, int blue) {
    analogWrite(rPin, red);
    analogWrite(gPin, green);
    analogWrite(bPin, blue);
}

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

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

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

String incomingData = "";

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

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

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


Arduino Micro Power Questions I have a few questions about the Arduino Micro circuit:

If I can provide a steady 5 V source (connected to +5V), then I don't need to use the voltage regulator module (including the selector) of the circuit. Correct?
If I can provide a steady 5 V source (connected to +5V), then I don't need to connect anything to VIN. Correct? If that's right, should I connect it (VIN) to GND, instead of leaving it floating?
If I'm not using +3.3V, should I connect it to GND (instead of leaving it floating)?
If I'm powering off of just USB, then I can connect +5V to VUSB. Correct?

Schematic below for reference:

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

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

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

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

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

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

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


Spikes in CO2 and TVOC measurements with CJMCU-811 sensor Firstly, I'm not sure if this is the right SE to ask this question. Please feel free to direct me somewhere else if needed.

I am observing large spikes in CO2 and TVOC measurements using the CJMCU-811 sensor. When plotted it looks like this:

Nothing particular is happening around the sensor at those moments of spikes, I'm not breathing on the sensor etc.

I use Arduino Uno with the following code:

/******************************************************************************
  Read CO2 and TVOCs from CJMCU-811 sensor

  Arduino connection:
  3.3V to 3.3V
  ACC to 3.3V
  GND to GND
  WAK to GND
  SDA to A4
  SCL to A5

******************************************************************************/
#include <Wire.h>

#include "SparkFunCCS811.h"
#define CCS811_ADDR 0x5B

CCS811 mySensor(CCS811_ADDR);

void setup()
{
  Serial.begin(9600);
  Serial.println("CCS811 Basic Example");

  Wire.begin();

  CCS811Core::status returnCode = mySensor.begin();
  if (returnCode != CCS811Core::SENSOR_SUCCESS)
  {
    Serial.println(".begin() returned with an error.");
    while (1);
  }
}

void loop()
{

  if (mySensor.dataAvailable())
  {

    mySensor.readAlgorithmResults();

    delay(1);

    Serial.print("CO2 ");
    Serial.print(mySensor.getCO2());

    Serial.print(", tVOC ");
    Serial.print(mySensor.getTVOC());

    Serial.println();
  }

  delay(2000);
}

Of course I can filter and not worry about them, but I'm nevertheless curious what is causing it. Any suggestions what could be the reason for that?

I have two of those sensors in a long term setup and I know those spikes very well. I once put lots of effort in debugging and I personally gave up on the ccs811 and use a different sensor now.
Back then I have already tried what Jaromanda suggests in his comment.
Both of my sensos showed the same behaviour while the spikes on both sensors did not correlate in any form.
Also, if I remember it right, those erronous readings appeared to be at dedicated values.
I tried several pullups, which also didn't make any difference and on the oscilloscope everything looked fine.
Printing the output of the I2C related functions revealed that communication was always stable. If it was I2C related I would expect those erronous readings to be completely random anyway (which they aren't from my experience).
My final (vague) theory was that maybe there exist race conditions between the computation and the I2C interface or maybe the adc and the approximation algorithm (that's all "inside" of the sensor). I once produced such a bug myself which resulted in a similar behaviour.
At least I'm pretty sure that there is nothing you can do in your sketch to fix this problem, because for the mentioned reasons it is very unlikely related to communication problems. You might want to work-around it or look for an updated firmware.
Or (my prefered solution) choose a sensor which does a true CO2 measurement (the ccs811 only returns a pseudo, calculated CO2-equivalent approximation).
Those higher-class sensors use NDIR technique and are only a bit more expensive (still under 50$) but you'll probably have much more reliable readings, less problems and a wider measurement range (up to 0-40000ppm vs 400-8192ppm).
Ps: did you follow the guidelines concerning the "burn-in time"? Because honestly, that was a mistake I did: I simply plugged it in of curiosity to test communication and read about this step afterwards. But I don't believe it has something to do with this problem, because there are physical reasons why one should do so, but those artifacts seem to be of digital nature.


coding standards for bigger projects I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.

I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide).
Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.

Any similar tools for C++ or more specifically arduino C++?

In my experience (15 years in industry, 30 total), this does not matter. What matters is having good developers who understand code written in ANY valid style. I currently work at a large bank, and there's 2 different bracket styles being used in our code, and nobody cares. Good developers don't care about this. We care a lot more about the code being valid, error-free, and efficient. If you do that, I don't care where your brackets are.

Yes, there are style guides for C++ but you don't need to use them. This is a good one though...

http://google-styleguide.googlecode.com/svn/trunk/cppguide.html

I am not aware of any style tools that integrate into Arduino IDE. There are some style tools that integrate into Eclipse though - and if this is important to you and your team, I strongly suggest using Eclipse for development. The Arduino IDE isn't really for large projects.

http://astyleclipse.sourceforge.net/ - but Eclipse doesn't really need this, it has a pretty good built-in formatter.


Run method Every Hour Passes I have a method. I need to trigger it every hour passes.(Cron Job)
I mean;
10.00 p.m -> Trigger
11.00 p.m -> Trigger
12.00 p.m ->Trigger
...
...
Card: Arduino Uno + Wifi Shield.
Draft Code
  void setup() {

  }

  void onTimeChanged() {
      runTask();
  }

  void loop() {

  }

  /*run this method when:
  13.00 p.m
  14.00 p.m
  15.00 p.m
  ........
  ........    */
  void runTask() {

  }

An Arduino Uno doesn't have a Real Time Clock, but you could contact a NTP time server on the internet using the WiFi shield you mention, and get the time from there, and then keep track of time using millis(). Every so often, you should adjust the time with a new call to the NTP time server, because the Arduino's clock isn't all that accurate.
The easiest way would be to get a RTC module (I think the most accurate and still affordable at the moment are DS3231-based). They have a slot for a backup battery so they keep time even when there is no power supply.
Connect the module using I2C to your Arduino, install the appropriate library, and ask it every second (or however accurate you want to be) in your loop() for the exact time.
These modules usually also have an interrupt pin and can generate an interrupt when an alarm time is reached; you could use that also.


Using an esp8266, how can I create a circuit to measure 2 different analog inputs (not simultaneously) with only one ADC pin available (A0) I'm currently using a circuit with 2 separate transistors that can be switched on or off to measure 2 separate voltage inputs.

The reason for this is because I'm using an esp8266 which has only one ADC input at pin A0 and I need to measure light intensity from an LDR as well as voltage from a solar panel.

The LDR is wired with a voltage divider. The voltage input from the solar panel is 0 - 5v, so I have that wired with a voltage divider to output a max of 3.3v (pin A0 is 0 - 3.3v). The problem is that in complete darkness, the ADC is still reading the LDR with a value of around 260 (should be close to zero) and with bright light reading around 850 (should be close to 1023). Also, the voltage measured from the solar panel (divided to 3.3v) is returning anywhere from 600 (0v) to around 840 (3.3v).

I've tried these input measurements separately with expected results. It's having the option to switch inputs is what is tripping me up.

So, is my approach correct or is there another way to do this?

Note: I would have included a circuit diagram if I knew anything about circuits and making diagrams.

There's two basic solutions, both of which require the addition of an external chip:

Use an analog multiplexer to select the different devices to connect to the ADC input
Use an external (I2C or SPI) ADC chip. These can give you higher resolutions than the internal ADC and many more inputs (depending on the chip you choose).

My recommended solution would be to get an external ADC chip.


Connecting a LSM9DS0 9DoF module to Arduino Uno I got a bit confused by Sparkfun's hookup guide for this 9DoF breakout module.

It says the VDD-in on the breakout "should [get voltage] regulated between 2.4V and 3.6V", yet in their example they do not hook it up to the Arduino's 3.3V pin, but instead they use the 5V and a bi-directional logic level converter.

Do I need to use the logic level converter, or can I just hook the module up to the 3.3V pin of my Arduino Uno without damaging the breakout module?

I might be missing the part of the hookup guide you're looking at but I can't see it being hooked up to 5V.

In the "Simple Hardware Hookup (I2C)" section they show two possiblilities a 5V Arduino hooked up via a logic level converter and a 3.3V Arduino hooked up directly. The logic level converter will need a 5V & 3.3V connection from the Arduino, but not the IMU.


Timer interrupt library for new Arduino based on MCU SAMD21 I'm looking for a timer interrupt library for the new Arduinos based on MCU SAMD21.

I want to wake up periodically the MCU form sleep state, do some task and go sleep again. Using one timer interrupt Arduino wakes up. For new Arduino MKR family.

Do you know a library to do this?

Do you know a library to do this?

it is generally very difficult to find a library that does precisely what your application wants. in fact, the purpose of a library is so that it is generic enough for you to tailor it for your specific application.

in this particular case, what you wanted to do is quite simple:

1) read through the datasheet;

2) figure out how the timer works;

3) figure out how the power management works;

4) configure timer isr to wake up the mcu periodically; an overflow isr is typically all you need;

5) run the task directly in the isr if is it short or set a flag for its execution in the loop;

6) upon completion, put the mcu to sleep.

all you need is to tackle the little steps above and you will get it done in no time, and learn a ton about your device.

device datasheet is the best friend of any embedded engineer, not the worst enemy.


Why have resistor at end of circuit cycle if GND dissipates final energy? The first challenge on the Arduino Uno manual is to make a closed circuit with a button and LED. The voltage is provided by the 5V pin (non IO), connected by wire to (+) on the bus (breadboard). The wire connects to a resistor, which makes sense since it resists current running from source. The button connects to the resistor, if pushed, the button closes the circuit and current passes through LED (making it shine) and through a wire to GND.

OK. The second challenge makes no sense. The resistors are connected not to the 5V, but the GND. WHY? Doesn't current dissipate past at ground?? As if the GND is supplying power!? It's like flipping the anode/diode! Here's the challenge: .What is the logic behind connecting the resistors to GND and WHY DOES IT SUPPLY POWER? I'm not talking about the button, which step two somewhat explains but not why, but the LEDs. Thank you thank you thank you!!

EDIT: Ok, then. I am now being told current flows negative to positive. Fine, then why resistor connected to positive? Also, I was told that GND is there to dissipate the energy flowing from positive because some of that energy was lost. Then, could you explain the circuit and whether flow is perpetual or lost at the end (wherever that is) and if it isn't perpetual in a loop, why have a resistor past the LED when the LED recieved all the volts and the electrical energy it then outputs back on the cycle is reduced by the resistor. Thanks.

Also, I'm changing my question to "Why does resistor on GND ever work on LED" to "Why have resistor at end of circuit cycle if GND dissipates final energy?".

Roman, As I understand your question you have a resistor, an LED and a switch in "series". It makes no difference in which order these are connected. It may help to think like water flowing through a hose, with a tap being a switch - it can be at either end.

"Current" flows through each in turn. As others have mentioned current conventionally is considered to flow from + to - (even though in most, but not all, cases electrons flow from - to +).

In practical circuits it is usually more convenient to select one configuration over another. An Arduino digital pin can be considered as a switch which is either connected to + or -. You could connect a LED (with a current limiting resistor) to either + or -, either is valid it just changes the logic controlling the switch.


how to use keypad button multiple integer value input I have been working on water flow sensor which measures volume then i need to restrict the amount of water which disperse from depend on the user input form the keypad so how can i store the input form the keypad into a variable.

When you use the keypad library, there is a command to read a key:

 myKeypad.getKey();

Store these keys in a (string) buffer, and after a certain key is pressed (e.g. #), parse the string buffer to retrieve the integer (with the c function atoi, see here for a description).


Program an Arduino with another Arduino Is there any way I can program an Arduino using another Arduino,without the need of any computer. I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino. Is it possible? How can it be implemented ?

It is certainly possible to do this.

  I want to store the programming code in the EEPROM of the "Programmer Arduino" and using any interface like SPI, I2C or Serial, burn this code to the Second arduino.

I should point out that the EEPROM may not be large enough for this. For example, the Uno has only 1KB of EEPROM.

A more workable solution would be to store a reasonable size program in PROGMEM, or a larger one in external memory, like an SD card.

I have a page about a stand-alone programmer - the first idea presented just uses the Serial monitor to command the programmer behaviour:

Using the Serial Monitor you select the file you want programmed. Another approach, commissioned by someone who wanted to eliminate the external computer altogether looks like this:

In this case you put one or more hex files onto the SD card, choose one using the "file select" knob, and then press the "program" button to program it. This only takes a couple of seconds.

There are also commercial products that do a similar thing.


Code test the duration press of the button I wrote code that tracks the duration of a button click. It has bounce protection and frequent clicks. (Freeze)

My code:

bool freeze_time, btn_read, debounce;
unsigned int freeze_timer, btn_timer;

#define BTN 6

void setup() {
  Serial.begin(9600);
  pinMode(BTN, INPUT);
}

void loop() {
  /* Freeze Timer Protection */
  if(freeze_time) {
    if((millis() - freeze_timer) >= 2500) {
      freeze_time = false;
      btn_read = false;
    }
  }
  /* Read Button State */
  if(digitalRead(BTN) == HIGH) {
    if(!btn_read) {
      btn_timer = millis();
      debounce = true;
      btn_read = true;
    }
  }
  /* BTN Read Process */
  if(btn_read) {
    /* Debounce Protection */
    if(debounce) {
      if((millis() - btn_timer) >= 1000) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Debounce ok.");
          btn_timer = millis();
          debounce = false;
        } else {
          Serial.println("Debounce fail.");
          freeze_time = true;
          debounce = false;
        }
      }
    }
    /* BTN Read Process */
    else if(!freeze_time) {
      if((millis() - btn_timer) >= 1500) {
        if(digitalRead(BTN) == HIGH) {
          Serial.println("Ok. Button Pressed > 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        } else {
          Serial.println("Ok. Button Pressed < 1500ms");
          freeze_timer = millis();
          freeze_time = true;
        }
      }
    }
  }
}

I checked it on real Arduino UNO and Tinkercad simulator. Initially, everything works well, but if I press the button indefinitely, the system will fail (every time you press the serial port, messages appear as if all flags were lost and the timers did not work. I filmed the behavior:

1) Initially: http://recordit.co/lVlR1z1CUq
2) System is broken: http://recordit.co/lhvzM100DI

What could be the problem and how to make it fault tolerant?

Why did the timers stop working?

The main issue seems to be that freeze_timer and btn_timer are of type unsigned int, while millis, as stated in its documentation, returns an unsigned long.

As you may know, unsigned int is normally be able to hold a much smaller range of values than unsigned long. In the case of whatever compiler Tinkercad uses for the Arduino Uno, I checked and unsigned int can hold values from 0 to 65535, while unsigned long can hold values from 0 to 4294967295. Whenever you save an unsigned long into an unsigned int, it will be reduced modulo 65536.

This means that once you pass 65.536 seconds checks such as the (millis() - freeze_timer) >= 2500 will always be true (at least until millis wraps back around after 4294967.296 seconds - around 50 days).

If you would like to learn a bit more about integer conversions, I think this Stack Overflow question covers it.

The simplest solution is, of course, to declare freeze_timer and btn_timer to be of the appropriate type, unsigned long.

Use simpler code

All of the above being said, like Gerben said, the code seems overly complex.

There also seem to be other issues. For instance, I would expect the debounce behavior should not ignore presses that last less than 1 second. Like Gerben said, 10 ms should be enough to discard any bounces.

Furthermore, I think it would be more appropriate to not even discard presses that last less than 10 ms. I would say the debouncer should trigger "press" regardless of whether the press lasted less than 10 ms. It's role should just be to ignore multiple presses within that 10 ms window (although to be fair, ignoring short presses is not a terribly big issue).

Although one could make some guesses, to really help you with this, we would need a description of your intended behavior. What is the purpose of freezing? Is it intended to allow multiple presses to be triggered when you never release the button (or maybe you should wait until release before triggering one again)?


Library, instantiation of a class object I am python experienced, an arduino noob, and absolutely no experience of C other than what has been forced upon me by arduino use.

I have just spent a day hammering google for the precise syntax of creating and using a class for user libraries, and have finally won.

However, I find that there are two forms that both seem to work for instantiating an object in the main program.

With my python experience, I find it easier to recognise the obj= style, used by Alan Zucconi in his examples, though the arduino.cc library tutorial on the Morse library uses the other form.

Is either preferrable, or are they equivalent in every way? Are there any subtle side effects of which I am unaware, that will bite me if the interfaces get more complicated, or some assumptions get corrected in future releases of the arduino IDE or compiler?

#include "Minimal_library.h"

// allocate buffer to be used
#define BUF_SIZE 40
char buff[BUF_SIZE+1];

// which of these two instantiation calls works?

// Minimal_library obj = Minimal_library(BUF_SIZE, buff);  //alanzucconi - works
Minimal_library obj(BUF_SIZE, buff);   //  Morse - that seems to work as well now
...

I presume that any private variables defined within the class become fully fledged persistent variables unique to the object created (it's been a long and frustrating day, not quite got around to testing the persistence or uniqueness yet, compiling without error, and then working, are enough for today!)

The statement

Minimal_library obj(BUF_SIZE, buff);

means “create an object named obj, initialized by calling the class
constructor with the supplied parameters”.

On the other hand,

Minimal_library obj = Minimal_library(BUF_SIZE, buff);

means “create an unnamed object initialized as before, then copy it
into an object named obj, then delete the unnamed object”.

The compiler would normally optimize the second form into the first one.
It is even allowed to do so in some weird cases where they may not be
equivalent. In the end, it's mostly a matter of style. I prefer to do
the optimization myself and write the first form. But if you find the
second form more readable, go ahead: you can normally trust the compiler
to optimize out the unneeded copy.


AnalogRead from voltage divider ladder I'm building a MIDI guitar, using an Arduino, sound synthesising and wood.

To properly know which note I'm pressing, I built a voltage divider with 12 equal resistors (10K). One side is connected at +5V and the other end at GND, so each of the 6 strings connects the right tap to the ADC.
I had just calculated the expected value w/ a bit of math considering I also needed a pullDown resistor(1M) and capacitor for every analog channel to keep the readings stable when no key is pressed.

When measuring with my multimeter the readings are stable, and there are variations of less than 0.02V, and since the difference from tap to tap is about 0.4V that's quite good.

The problem is when reading the 6 channels together: channels supposed to be pulled down to gnd read voltages caused by nearby channels, readings are shaky and similar errors.
This mess disappears on one channel when I connect the multimeter to that one.
Instead of buying 6 multimeters, I figured I could ask you if someone has an idea on why this happens, my guess is on the pulldown resistor, but I'm not sure about Arduino's ADC; I'm also worried about having 6 wires half of a meter each so close, so any other idea on finding the keys is welcome.

EDIT
@EdgarBonet was right, I used 12x220ohm resistors, and at first the results were absolute garbage, then I made it so the code would read each channel about 10 times, discard the readings, wait a millisecond and finally read and store the value. Now it is perfect.
Thanks again.

The datasheet of the ATmega328P (the main chip of the Uno) states:

  The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less.

The Thevenin equivalent output impedance of most taps of
your voltage ladder is higher than 10 kΩ. You 1 MΩ pulldown is
way beyond that limit. Cross talk from previously read channels is
exactly the symptom you expect from excess output impedance.

Taking each reading multiple times, until the value stabilizes, should
help. A buffer (e.g. an OP-amp set as a unit gain amplifier) is the
usual solution to this kind of impedance problems.

  Actually, the whole works perfectly with R as 220 and pull downs as
  10K. The problem comes when connecting more than 3 strings at the same
  time, on any tap, as the pull down resistors become part of the
  ladder (i belive).

The pull down resistors will indeed have an effect on the potentials of
the voltage ladder, especially if you connect several strings. This
could be minimized by having the pull-downs be a lot more resistive
than the resistors along the ladder, but then you would need very low
resistances along the ladder, which is not desirable because of current
consumption and heating.

Here is an idea for an alternative solution: If you can spare 6 digital
pins, you could build for each analog input a pull-down circuit that is
switchable between a “strong pull” mode and a “weak pull” mode. Assuming
D0 is the “pull strength control” pin for A0, it would look like this:

A0 ---+--- 1 kΩ --- D0
      |
     1 MΩ
      |
     GND

Whenever you want to read A0, you:

set D0 to OUTPUT LOW, which creates a strong pull-down to ground
take a couple of analogRead()s
set D0 as INPUT, which leaves only the weak 1 MΩ pull down
take a couple of analogRead()s, keep the last one.

If A0 is not connected to the ladder, then the first reads will
discharge the internal sampling capacitor of the ADC. The final read is
done with only a weak pull-down, but this should be OK since the
capacitor has already been discharged.

The potentials along the voltage ladder will be disturbed by any string
connecting a tap to its strong pull-down, but this disturbance will
disappear when you switch to weak pull-down, so it will not affect the
readings.


Can I access individual pixels on my 16x2 LCD display I have a generic 16x2 LCD display connected to my Arduino.  I can use the standard LCD library to display characters, but are there way to turn on and of individual pixels?

It's possible to define custom characters for “generic 16x2 LCD displays” [ie, displays based on HD44780 or equivalent controllers], but only up to eight such characters at the same time.  See LiquidCrystal.CreateChar for details.  See page 2 and part of page 1 of the Print degree symbol ° on LCD arduino.cc thread for create-character examples that don't use the library.  Page 1 of that thread also shows a table of all the characters built into typical HD44780 controllers, some of which may perhaps meet your needs.

For pixel-by-pixel LCD control, look at graphics LCDs, eg the KS0108 or LCD12864 and similar.


How can i make my MLX90614ESF scan temperature after the MFRC522 scans the RFID tag? //THIS IS THE RFID CODE

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
    //shows in serial that it is ready to read
}
//*****************************************************************************************//
void loop() {
  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;
  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;
  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

// AND THIS IS THE MLX90614 CODE
#include <Wire.h>
#include <Adafruit_MLX90614.h>

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

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

  mlx.begin();
}

void loop() {

  Serial.print("*\Body Temperature = "); Serial.print(mlx.readObjectTempC()); Serial.println("*C");

  Serial.println();
  delay(500);
}

It appears that you have simply concatenated the code from the RFID tag Sketch and the code from Temperature Sketch together.  This will not work as both programs contain identically named functions. Specifically "setup()" and "loop()".  What you need to do is integrate the code for each "setup()" function into one "setup()" function.  Similarly, you need to do the same with the "loop()" functions.
Assuming you only want to scan the temperature after you have successfully recovered data from the RFID tag, place the Temperature Sketch loop code immediately before the delay in the RFID tag code.


Help! My motors are not working! I have made a project using Arduino, 3 LDRs and a L293D motor driver shield. My project was that when I block light from the first LDR, the motor will spin. When I block light from the second LDR, the motor will spin in opposite direction, and when I will block light from the third one, it will stop. The code had no errors and I expected it to work... But no luck. When I blocked light from the first or second LDR, the motor only made a faint "zing-zing" type of sound. Why is this happening? Is this a power problem? But I have connected 2 9v batteries to the shield and the Arduino. Please help! Here is the code I used-

#include (AFMotor.h)

const int LDR1 = A0;
const int LDR2 = A1;
const int LDR3 = A2;
const int LightIntensity = 150;
int SensorReading1 = 0;
int SensorReading2 = 0;
int SensorReading3 = 0;
AF_DCMotor motor(1);

void setup(void)
{
  pinMode(LDR1, INPUT);
  pinMode(LDR2, INPUT);
  pinMode(LDR3, INPUT);
  motor.setSpeed(255);
}

void loop()
{
  SensorReading1 = analogRead(LDR1);
  SensorReading2 = analogRead(LDR2);
  SensorReading3 = analogRead(LDR3);

  if (SensorReading1 < LightIntensity)
  {
    motor.run(FORWARD);
  }

  if (SensorReading2 < LightIntensity)
  {
    motor.run(BACKWARD);
  }

   if (SensorReading3 < LightIntensity)
  {
    motor.run(RELEASE);
  }
}

You have not said what you motor is and that normally has a big bearing on the answer, but I think your problem is you need more power.

A 9V battery doesn't actually give you much current, you would be better off with a 'wall wart' aka a mobile phone charger.  The higher the amps the better normally, particularly with motors.  Try and find one that can put out 5Volts at 1Amp (assuming you have a 5V motor).

Also make more use of Serial.println() to show you what your program is doing.  If you had debug statements in the LDR if statements then you would know the switches are working.


Optocouplers for Arduino DCC decoder - Explain? I am trying to make an Arduino circuit as outlined here.

This is for connecting an Arduino input to a DCC system. DCC is a command control system for model railways that uses the same two wires for power and data (there's a wikipedia article that explains it better than I can)

I'm wondering what the optocoupler has more than 4 pins for? I'm new to this and I understand the purpose of the optocoupler but I am confused as to how this particular one works. It is a 6N136 optocoupler. I don't understand why it has the extra pins compared to 4 pin optocouplers, and I don't understand how it would read the polarity of the signal. DCC sends commands using polarity as I understand it, so I know I need to read the polarity, but how does the optocoupler do it here?

I have a very limited knowledge of electronics right now so pardon anything stupid I said :P

That specific chip (the 6N137) uses a more efficient IC detector rather than a simple transistor junction.  It also has an "enable" pin that allows it to be turned on or off.  Consequently it needs a power supply to run it. That all means extra pins.

This design allows for higher speed communication (it's a 10Mbaud chip) with less leakage when compared to a traditional design.

The pin VE (pin 7) needs to be pulled up to make the chip work (the job of R2) and the output is pulled high (it's open drain) by R3.

The optocoupler will be on with one polarity and off with the other. It's as simple as that. The diode D1 protects the LED in the optocoupler from the reverse voltages.


nodemcu doesnt response in at command mode I want to sent AT command into node mcu esp8266 module with arduino IDE  through serial monitor.
I connect the node mcu to arduino uno board in following sequence:
RX to pin 2 of arduino
TX to pin 3 of arduino
Vin of node mcu to 3.3V of arduino
GND to GND
EN of node mcu to 3.3V of arduino
I send at commands in serial monitor but dont get any response.
I also checked different baud rates.
what is the problem? what thing I'm doing wrong?

    #include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //2 -->rx  ,3 -->tx

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

void loop() {
  if (esp8266.available()>0)
  {
      char c = esp8266.read();
      Serial.write(c);
  }
  if (Serial.available()>0)
  {
    delay(1000);
    String cmd = "";
    while (Serial.available())
    {
      cmd += (char)Serial.read();
    }
    esp8266.println(cmd);
  }
}

Some points to note:

VIN should connect to 5V (it goes through the on-board 5V -> 3.3V regulator). If you connect VIN to 3.3V you will be starving the device of power.
The NodeMCU doesn't come with AT firmware installed. You will have to install it first before it will respond.
If you have a NodeMCU why are you bothering with an Arduino? The NodeMCU can do everything (and more) that the Arduino can do (except it lacks IO).


Teensy to Teensy serial communication via USB connector I have 2 Arduino Teensy 3.2 boards that I'm trying to implement serial communication between the 2 boards.  I have successfully done this by connecting RX1 of the 1st Teensy with TX1 of 2nd Teensy and TX1 of 1st to RX1 2nd.

However I was wondering if I could send serial messages between the Teensys i.e. do the same thing, by connect the 2 Teensys via the USB port?  Or is this USB port reserved to connecting the Teensy to a computer?

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

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

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


Serial Monitor "button" implementation I have a small project and I have some problems while working on that. The idea of the project is as below:
I have an LED which is operated by two "buttons". The buttons takes two values (1 or0) which I have to send from serial monitor.
One button is for LDR sensor, which lights up the LED when its value is below 300 (in my code). The other button turns it off (Value 0). The buttons are working together, so I have to consider both of them in my statements. The problem is that I cannot play with the serial monitor it's just looping continuously and I cant type anything as input.

Can anyone help me with this to find a solution to be able to input values for both buttons?

Here is the code:

const int analogInPin = A0; //LDR PIN
const int digitalOutPin = 13; // LED PIN
int outputValue;

int sensorValue = 0; //

char Buton1; //LDR button
char Buton2; //Blutooth button

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

void loop()
{
  while (Serial.available())
  {
    Serial.println("Button1 value: ");
    Buton1 = Serial.read();
    if (Buton1 == '1')
    {
      Buton2 = Serial.read();
      Serial.println("Button2 value: ");
      if (Buton1 == '1' and Buton2 == '0')
      {
        sensorValue = analogRead(analogInPin);
        outputValue = map(sensorValue, 0, 1023, 0, 255);
        Serial.print ("Sensor: ");
        Serial.println(sensorValue);
        if (sensorValue < 300);
        {
          digitalWrite(digitalOutPin, 255);
        }
      }
      else if (Buton1 == '1' and Buton2 == '1')
      {
        digitalWrite(digitalOutPin, 255);
        Serial.print("Both buttons are ON ! !");
      }
    }
    else if (Buton1 == '0')
    {
      Serial.println("Button2 value: ");
      Buton2 = Serial.read();
    }
    if (Buton1 == '0' and Buton2 == '1')
    {
      digitalWrite(digitalOutPin, 255);
    }
    else if (Buton1 == '0' and Buton2 == '0')
    {
      Serial.println("Both buttons are inactive ! Please reset");
      break;
    }
  }
}

A simple approach would be to use bit 0 of serial data to control "button 1", and bit 1 of serial data to control "button 2".  As follows:

char sd = Serial.read();
byte button1 = sd & 1;
byte button2 = sd & 2; // Or (sd & 2)>>1 if you prefer

With the above code, button 1 is true for odd-digit inputs, and button 2 is true when (sd & 2)>>1 is odd.  For example, input 0 to turn off both buttons, 1 to turn on only button 1, 2 for only button 2, and 3 to turn on both.

You might also wish to button1 or button2 only when the input character represents a digit.  For this, you can say:

char sd = Serial.read();
byte button1, button2;
... ;
if ('0' <= sd && sd <= '9') {
    button1 = sd & 1;
    button2 = (sd & 2)>>1;
}


Can't you easily use "quadrature" incremental rotary encoders at 2X or 4X their number of "stops"? I bought a 12-step "quadrature" incremental rotary encoder as an input device for a project I'm working on.

When I wrote the code to track "ticks" of rotation, I made it respond to any change in the "A" pin. As a result, I got 24 steps, not 12. They appear to be evenly spaced, and still correctly indicate clockwise or counter-clockwise rotation.

It occurs to me that if I track changes of state in both the "A" and "B" pins, as long as I reverse the logic for identifying clockwize vs. counterclockwise rotation, I could get a 48 step count from the same encoder.

Thus isn't it straightforward to get 2X or 4X the steps from a quadrature  rotary encoder simply by interpreting the signals differently?

Maybe the encoder you got is being incorrectly described?  I have a handful of the little thru-hole rotary encoders popular in Arduino module kits and they have 12 detents for one rotation, but they are actually 48-position-per-rotation encoders. When I use them, I have to divide the tick count by 4 to have one physical "click" count as one tick in my code.

For some of these, it's fairly straightforward to open them up and remove the detent, and thus get a higher-resolution, smooth spinning encoder. Unfortunately, others, such as the ones I have, are difficult to open without destroying them, and since they physically snap to the detents, aren't usable at the proper resolution.

The method you note, where you track the high/low change in either direction of both outputs is the normal way to read quadrature encoders.


Powering an Arduino Mini Pro using a CR2032 battery as a remote control I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.

Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.

I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.

What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.

If we assume this, while looking at this sheet:

NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 0.19 mA @ 2V = 2100+ hours

Even if we just say 600 hours and it takes 2 seconds to turn something on, I should be able to run it  600H*60M*60S = 2.160.000 seconds = 1.080.000 times. If my calculation isn't completely wrong, it means I could literally turn it on a million times in the worst case scenario.

I hope that calculation is wrong, because that seems crazy.

EDIT: I could desolder the LED and regular as well, if that won't damage it too much. Just to consume power. I've read I can basically run it for free then.

You should take a look at ATmega328P datasheet

  On page 2, it says: Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby

These are the modes which can be used to put Arduino Pro Mini in stand-by. You can search for them at datasheet and choose the only that better applies to you. To learn more about sleep mode and other methods to save battery, you can take a look at this source: Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery

On the datasheet of battery, you should pay attention at its charge:

  Typical Capacity: 240 mAh (to 2.0 volts)

This means that from 3 to 2 Volts, it relases 240 mAh. This is the charge you can expect to use. Using the consumptions rates you posted above

NRF24L01: 10 mA per second (low-ball)
ATmega328P: 5 mA per second (low-ball)
CR2032: 240 mAh
Time: 240mAh/(10mA + 5mA) = 16 hours

Which is not so much. To increase this autonomy, the link I posted above is quite useful because it will show you alternatives like removing the voltage regulator that will reduce drastically your consumption. Now, if you feel really adventurous, you may take a look at how to underclock your board: Arduino pro mini @ 1MHz - 1.8V. This is a very efficient way to save power where clock frequency is not a must.

EDIT after comments:

The 16 hours were computed using 5mA for the Arduino (which is a value for power consumption that can be expected on active mode) and 10mA for the NRF24L01. You have to estimate a sleep mode consumption for both and a percentage of time in sleep mode if you want to estimate an autonomy. At the link I sent you about sleep mode there are some tables with power consumption in different configurations.

ATmega328P can run with a minumum of 1.8 Volts, while nRF24L01+ can while with a minimum of 1.9V - see datasheet. So probably you are going to have a little bit more than 240mAh to work with. Your battery won't have 3v all the time. It is going to start with 3V (maybe a litte bit more) and gradually reduces it voltage as the charge is provided to the circuit. Once the voltage goes bellow 1.9V, nRF24L01+ won't be guaranteed to work properly.

Definitely, to sleep the Pro Mini, just waking it up when using, is the right way to design this circuit. According to this reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of nRF24L01+ datasheet, it is described that it consumes 0.32mA at standby mode II. If you sleep the Pro Mini for, let's say, 90% of the time, without removing leds or voltage regulators, you can estimate that

t = 240mAh * (0.1/(5mA+10mA) + (0.9/(0.9mA+0.32mA)) = 178.65 hours

If you use strategies to reduce Arduino power consumption, like the ones I send you above, you can increase this time. You will also save power if you change nRF24L01+ from standby mode 2 to standby mode 1. Check the database to see which one fit your needs.


Ideas for setting I2C device IDs I am using I2C to communicate between a collection of ATtiny85s that are acting as controllers for various parts of a system and the "Main Brain" -- a RaspberryPi. Most of the ATtiny85s only have a couple of free pins left (usually Pins 1 and 2 -- the reset and the pin that can't be used for PWM) so I can't use something like a DIP switch to directly set device IDs. I'd rather not hardcode the device IDs when I push code to the tinys but I can't think of a good, simple, and reliable way to do it otherwise. Anyone here have a suggestion?

Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.


Button that gives an Input, Has a small delay --- then gives another I'm pretty new to the Arduino scene, and my question will likely be solved simply by some more experienced fellows. I'm trying to create a code for a switch/ button that when you press it, it generates an output--- then waits (delays?) and produces another (after that set amount of time) before ending that transfer of information.  Can any insight be shed on this? What would that look like? For example, the code that I am imagining is something like this :

if(buttonisPressed){

  Function1 = 1;   // Original output is issued

  delay(1000);  // Set time delay for the next output

  Function2 = 1; // The second output follows suit after the set amount of delay time (only after one press, without a secondary)

}

This is a snippet of the code I am using, but I haven't been able to get it to work.

Thanks so much for your help! Any advice at all would be greatly appreciated.

A standard way to do this is to connect a digital i/o pin via a (normally open) push button to ground. Internally in the Arduino a pullup resistor can be activated to keep the pin on a high level when de button is open. For example when pin #8 is used: pinMode(8, INPUT_PULLUP). The program watches the state of the pin to detect whether the button has been pushed. An extensive tutorial about using switches for input to microcomputers you can find here: http://www.gammon.com.au/forum/?id=11955

Be sure to familiarize yourself with a phenomenon called "contact bouncing": when the button is pressed or released the contacts don't open or close immediately but go through a series of rapid open/close/open/etc. states. The best information I know about how to handle this you can find here: http://www.ganssle.com/debouncing.htm


Simultaneous Serial reading and writing I am trying to read long strings from the Serial, using arduino.
In order to spare some RAM I don’t use Serial.readString().
I use Serial.read() instead.

During the reading, I also print some debug info to the same Serial port.

Let's say I send 90 characters to the Serial from the PC. I read them with Serial.read(). If I call a few times Serial.println() between two calls of Serial.read(), I get only 67 character of 90 (Serial.available()>0 is false).

I read all the 90 character when I don’t call Serial.println() at all.

Why? I was sure that it is possible to write to the serial and read from it simultaneously, that these are independent processes.

Am I wrong?

You can indeed simultaneously read and write through the serial port. At
the hardware level, the serial port (the UART) is a transmitter and a
receiver, which are almost independent. At the software level, they are
both handled through interrupts that read from / write to a software
buffer.

There is, however, a limitation you should be aware of: the software
buffers are not large, typically 64 bytes on AVR-based boards. If
you try to write too much too often, the output buffer will fill out,
and then all subsequent writes become blocking, and run as slow as the
serial port itself. If you receive lots of data and do not read it soon
enough, the input buffer will overflow, and you loose some data.

From your description of your issue, it would seem you are hitting the
limits of both buffers. You Serial.println() too much, too often. Then
these write operations take too long and, in the meanwhile, you do not
Serial.read(). Since your PC is not waiting for you to
Serial.read(), your input buffer eventually overflows, and you only
get slightly more than a buffer worth of characters.


How to send a message to my phone that my Arduino system is on when turning on my Arduino i have installed a GSM shield on the Arduino to create security alarm system using PIR SENSOR when ever there motion I will receive a call to my phone.
but i want to add also a line of code which can make my system send me a txt message stating that my system is turned on so i can make sure that when ever i turn my system on i can doule check by getting a message that says that system is turned on successfully
i dont know how to start doing that.
this is the code i did:
int PIR = 6;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(96000);
 pinMode (PIR , INPUT );
}

void loop() {
  // put your main code here, to run repeatedly:
if (digitalRead (PIR == HIGH)){
  Serial.println("thief detected");
  delay (200);
  Serial.println ("ATD+0197263315;");
  delay(1000);
  Serial.println("ATH");
  delay(1000);

  }
  else digitalWrite (PIR, LOW );

}

You can send an SMS using the Arduino GSM library. Here is a bare bones sketch that sends one pre-set SMS when it starts up, based on this tutorial:
#include <GSM.h>

#define PINNUMBER "1234"
#define REMOTENUMBER "07123456789"
#define TXTMESSAGE "System started!"

GSM gsmAccess;
GSM_SMS sms;

void setup() {
  boolean notConnected = true;

  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      delay(1000);
    }
  }

  sms.beginSMS(REMOTENUM);
  sms.print(TXTMESSAGE);
  sms.endSMS();
}

void loop() {
}

If you can't or don't want to use the GSM library, it should also be possible to send an SMS by using the SoftwareSerial library to control your GSM shield using AT codes. Here's a tutorial on this approach, which is lighter weight but might be more fiddly to get working, especially if you need a PIN for your SIM card.


Arduino leave PWM on I am doing an aquarium light sunrise/sunset. Till now programming wise I only did the sunrise. After running the code the light starts to rise up fine, than  at full brightness, it turns off. I want to keep it on after it reaches the 100% pwm and than starts decreasing when it's time to get off. Any help on how to leave the pwm at 100% and than starts to dim when it's time to turn off? I am still new to coding arduino, so explanation need to be for a beginner :P Thanks before hand.

#include <DS3231.h>

//Set Variables
int fadeTime = 15; //Fade Time
int onHour = 12; //Light On Hour
int onMin = 00; //Light On Minute
int offHour = 19; //Light On Hour
int offMin = 00; //Light On Minute
int led = 9; //Set pinout with with PWM

DS3231  rtc(SDA, SCL);
Time t;
void start();

void setup()
{
  pinMode(led, OUTPUT);
  rtc.begin();
}

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

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == onHour && t.min == onMin) //Check Time
  {
    start();
  }

}

void start()
{
  // Fade script
  for (int i = 0 ; i <= 255; i++)
  {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
  }

}

Why not create a global brightness variable (e.g. cBrightness) so that you can adjust the brightness accordingly when the time comes? With a global variable, you can still maintain the brightness of the LED even after it exits the start() function.

For the start() function, you can include one argument (int/bool type variable) in the function to determine when to perform the brightening or dimming of the light depending on the RTC timing.

void start(int st)
{
  if(st==0)
  {
     //Brightness decrement function here
  }else if(st==1)
  {
     //Brightness increment function here
  }
}

For the brightness decrement function, it is the opposite of the increment function:

for (int i = 255 ; i >= 0; i--)
{
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
}

To summarize, the code could look something like this:

#include <DS3231.h>

//Set Variables
int fadeTime = 15; //Fade Time
int onHour = 12; //Light On Hour
int onMin = 00; //Light On Minute
int offHour = 19; //Light On Hour
int offMin = 00; //Light On Minute
int led = 9; //Set pinout with with PWM
int cBrightness = 0;  //Current brightness

DS3231  rtc(SDA, SCL);
Time t;
void start(int st);

void setup()
{
  pinMode(led, OUTPUT);
  rtc.begin();
}

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

  // Send Day-of-Week
  Serial.print(rtc.getDOWStr());
  Serial.print(" ");

  // Send date
  Serial.print(rtc.getDateStr());
  Serial.print(" -- ");

  // Send time
  Serial.println(rtc.getTimeStr());

  if (t.hour == onHour && t.min == onMin) //Check Time
  {
    start(1);
  }else if (t.hour == offHour && t.min == offMin)
  {
    start(0);
  }
  //Maintains brightness
  analogWrite(led, cBrightness);

}

void start(int st)
{
  if(st==0)     //Will decrement in brightness
  {
   for (int i = 255 ; i >= 0; i--)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
   cBrightness = 0;

  }else if(st==1)   //Will increment in brightness
  {
   for (int i = 0 ; i <= 255; i++)
   {
    analogWrite(led, i);
    delay(((fadeTime * 60000)/306));
   }
  cBrightness = 255;
  }
}


Why does Arduino IDE recommend storing 0-255 numbers in "byte" instead of "char"? I bumped into byte datatype recently. My knowledge of C/C++ is shallow, but I know char and I couldn't find much on byte in C++ docs. I looked it up in the Arduino docs:

  It’s recommended to only use char for storing characters. For an
  unsigned, one-byte (8 bit) data type, use the byte data type.

Is byte datatype a solely Arduino construct? If so, why is it recommended over char? Both are 8-bit so why would it make any difference?

Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, since it originated from Processing, which is Java. So we have data types the "look like" Java ones, including "byte" for "unsigned char" and "boolean" for "bool".

  If so, why is it recommended over char?

Personally I don't ever recommend using it, since it's non-standard. Instead you should use uint8_t which is essentially the same thing, but portable.

It is recommended to use "hard signedness" data types for portability.  The problem with char is that whether it is signed or not is entirely down to the compiler implementation. Some systems have it as signed, some as unsigned. By using byte (or better, uint8_t) you are always going to get an unsigned 8-bit value.

For just storing of binary data it doesn't really make any difference, but when it comes to doing mathematics with the stored data you may find you suddenly have negative values when you don't want negative values (a char might be storing your number as -128 to +127, not 0 to 255).


Sending more than BUFFER_LENGTH(32) bytes in slave answer I2C I need to send 259 bytes as answer to I2C master read request. AFAIK there is a buffer limit of 32 bytes in Wire.h and in HW (Arduino Nano). Is there a way sending 259 byte answer, or I have to choose another HW?

The code is:

void serveInitCommunication() {
  Serial.println("serveInitCommunication()");
  static unsigned int counter = 0;
  auto answer = findInitAnswer(counter);

  uint8_t buffer[260]; //maximum size from dataLengths[] in comm_init_data.h
  memcpy_P(buffer, answer.dataPtrProgmem, answer.dataSize);

  Serial.print(" dataSize:");
  Serial.print(answer.dataSize);
  Serial.print(" data:");
  Serial.println(int(buffer[answer.dataSize - 1]));

  auto bytesToWrite = answer.dataSize;
  uint16_t bytesWritten{0};

  while (bytesToWrite > BUFFER_LENGTH) {
    Serial.println("Write part");
    Wire.write(buffer + bytesWritten, BUFFER_LENGTH);
    bytesToWrite -= BUFFER_LENGTH;
    bytesWritten += BUFFER_LENGTH;
  }
  Serial.print("Bytes written:");
  Serial.print(bytesWritten);
  Serial.print(" Bytes yet to write:");
  Serial.println(bytesToWrite);
  Wire.write(buffer + bytesWritten, bytesToWrite);

  counter++;
}

And called is it:

void requestHandler() {
  char buff[100];
  sprintf(buff, "requestHandler addr:0x%x counter:%d", readAddress, msgReadCounter);
  Serial.println(buff);

  if (readAddress == INIT_MSG_ADDRESS) {
    serveInitCommunication();
  }
}

I've tried moving the serveInitCommunication() into void loop() and setting a just a flag in requestHandler() but without success. Sending up to 32 bytes works fine. Tnx

update: uint8_t twi_transmit(const uint8_t*, uint8_t); so twi library self limit data to 255 bytes

update2: there is a hacker way doing it, by replacing the twi.c twi_txBuffer and twi_txBufferLength with buffer from the sketch

The limitation is purely in software. The I2C hardware has a limit of one byte at a time, and the software creates a 32 byte buffer and feeds each byte from that in turn.

While it would be perfectly possible to increase that buffer size, you may find you have other problems when you get above 255 bytes, since lots of parameters and internal variables for the library are limited to 8 bit values.

It would also be considered very "hacky" since you can't easily upgrade the Wire library in future.

A better strategy would be to split your data into chunks and make multiple requests, each one saying "Give me chunk number ..." and then recombine them upon reception.


Is there any way to prevent Arduino CLI from closing each time? I prefer writing code in Vim, so I'd like to get a workflow going with the Arduino CLI. I used to use ino, but I didn't like the restructuring of the project, which meant anyone who downloaded the code having to use ino.

I can build and verify using /Applications/Arduino.app/Contents/MacOS/Arduino --verify MyProject.ino, which pops up a new instance of the Java IDE, then exits after verifying.

While this works, and works well, it's incredibly slow. Is there any way to keep the IDE open to save the few seconds lost from the IDE starting again?

Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

Start the Arduino IDE and set external editor in the Preferences (once).
Open the sketch file(s) in the Arduino IDE and VIM.
Edit the sketch file(s) in VIM.
Move to the Arduino IDE and Verify, Upload, Monitor, etc.
Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the Cosa build system for Linux.

Cheers!

PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.


Change Servo Speed With RedBearLabs BLE Shield I recently got the RedBearLabs BLE shield to use it to control two high spped continuous rotation servos. I have the BLE example sketch loaded and the ios controller app works. The problem is that the servos are too fast to control and I want to slow them down. I cannot use the app to slow them down. I was wondering how I could modify the example sketch or servo library to change the ax speed or something. Thanks in advance.

BLE Shield Homepage: http://redbearlab.com/bleshield/

BLE Libraries and Example Sketch: https://github.com/RedBearLab/nRF8001

The bi-directional Parallax High Speed Continuous Rotation Servo responds to “simple pulse-width modulation”, according to its web page.  That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.

The code in the BLEControllerSketch uses the following bits of code, among others, to initialize servo-control data structures and to control them:

#include <Servo.h>
...
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
...
      case 'O': // set Servo
        {
          byte pin = ble_read();
          byte value = ble_read();

          if (IS_PIN_SERVO(pin))
            servos[PIN_TO_SERVO(pin)].write(value);
          pin_servo[pin] = value;
          reportPinServoData(pin);
        }
        break;

Thus, you will need to send an O message from your iOS app, together with servo pin number and control value, to set a servo's speed.

As noted on the ServoWrite page at arduino.cc, the parameter to Servo's .write() method is a number:

  On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's .write() method in Servo.cpp:

void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

SERVO_MIN() and SERVO_MAX() are macros that access min and max fields in a Servo object and convert them to microsecond values.  Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).

Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees.  The .write() method will interpret such numbers as microseconds instead of as degrees.  Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.

In short, it appears that you should do some experimenting with O messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.