Arduino Due unable to access library I am unable to run code on Arduino Due that I earlier ran on an Arduino Uno. The error indicates it is unable to recognize the library. Could this library access problem be due to difference of the micro-controllers of the 2 boards?

Quite possibly. The modern library format contains a list of board types it runs on (in library.properties). If the Due (SAM) isn't listed then it won't be included in the list of libraries.

For instance the SD library has:

name=SD
version=1.1.1
author=Arduino, SparkFun
maintainer=Arduino <info@arduino.cc>
sentence=Enables reading and writing on SD cards.
paragraph=Once an SD memory card is connected to the SPI interface of the Arduino or Genuino board you can create files and read/write on them. You can also move through directories on the SD card.
category=Data Storage
url=http://www.arduino.cc/en/Reference/SD
architectures=*

However the AVR specific SPI library has:

name=SPI
version=1.0
author=Arduino
maintainer=Arduino <info@arduino.cc>
sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus.
paragraph=SPI is a synchronous serial data protocol used by microcontrollers for communicating with one or more peripheral devices quickly over short distances. It uses three lines common to all devices (MISO, MOSI and SCK) and one specific for each device.
category=Communication
url=http://www.arduino.cc/en/Reference/SPI
architectures=avr

Note the last line of each - architectures=... - that defines what the library can work with. If your (unspecified) library doesn't have * or include sam in that parameter then there is no way that library will work with the Due.


Alternative distance-meter, HC-SR04 doesn't work very well On door to my room there is HC-SR04 that triggers led-wave. The shorter the distance, the faster the led-wave (8 leds).

The circuit works fine in synthetic tests – moving hand or flat object towards the sensor generates gradually accelerating wave.

However, when placed on door to detect approaching persons it generates short correct (<=170 cm) impulses and the wave starts and immediately stops, again starts, etc. I guess HC-SR04 isn't good enough to detect people.

Are there any alternatives to this sensor that will correctly detect human approaching?

In general the HC-SR04 is controlled using pulseIn().

When there is nothing within range for the sensor to detect it usually has to wait for pulseIn() to time out. That can take up to a second by default.  While that is happening the rest of the sketch cannot do anything.

You can reduce the timeout in the pulseIn() function, but it's still not going to be perfect - you'll still get a delay which will interrupt your LED sequences.

The ideal way will be to create a "free running" distance sensor system - use a timer to periodically start a ping, and use the Input Capture module of the ATMega to measure the time between the start and end edges of the returning pulse. Everything will happen asynchronously to the rest of your sketch then.

I am not aware of any libraries for Arduino boards, but I have one for the PIC32 based chipKIT boards that I use. It can't ever work on AVR based boards, but you can use it to see the general concepts and how things fit together.


Adafruit Motor Shield and Bridge Library for Yun Shield I am using the Leonardo board with the Adafruit Motor Shield v2, 2 steppers and the Yun Shield. The yun shield and steppers all run harmoniously, however, as soon as I do Bridge.begin() and anything that accesses the Yun shield Bridge library to access the console, the steppers stop running. Is this to be expected and are there any solutions?

Thanks

Looking at Bridge.begin() description here
 you can see this is blocking function.

  begin() is a blocking function. Once you call Bridge.begin(), nothing else will happen in your sketch until it has completed. This process takes approximately three seconds.


powering Nodemcu using Vin Forgive me for this really dumb question. I am an amateur in electronics, and im trying to wrap up my head around this question and im not able to do so. Need your help.

Im trying to power up a nodemcu using a 5v 1A power supply- I connected +ve to Vin and ground to ground. But i see that 5v is not enough to power up the nodemcu. So i removed the 5V and connected to a 9V battery, and again I find the same issue- the power is not enough. Knowing that i did something wrong - i measured the voltage across Vin and ground and find it to be around 2.5V when using the 5v source and around 2.5V when using the 9 V battery too.

Confused and thinking that my nodemcu is corrupted, i ordered a new one, and did the same. But i find that when i try to supply power using Vin, the voltage across the device- Vin and ground is around 2.5V for the newer device also. Obviously Im missing something.

Can anyone tell me what is it that Im doing wrong. Please tell me how to power a nodemcu without using a usb and only using a 5v source.

I have a NodeMCU Esp8266 v3 (Lolin) and it works fine conecting Vin and G to my cell phone power supply rated 5.1V, 1000mA. This develop board has a aprotective diode (the closest to Vin), if you have a Multimeter o multitester you can check it measurement continuity. If your diode is damaged the power applied to Vin never be enough to power up the nodemcu.


Updating SPI transfer16 to create Transfer24 It might be a bit out there, but for a project that I am working on, my word size default is 24bits (3x8-bit), of which the first 8-bits are data and the next 16-bits are data. I would like to transfer it out of the system as fast as possible with minimal calls to the sub-routines. For this I am trying to reduce the number of calls, I have managed to reduce it from 3 to 2, Can I possibly make it 1 call.

My first attempt was to use 3x SPI.transfer() Second was to use 1x

SPI.transfer() and 1x SPI.transfer16()

I would like to know what would be the ideal way to write a SPI.transfer24 function.

You can't.  The teensy 4.0 has hardware support for 8-bit, 16-bit and 32-bit transfers. Not 24-bit transfers.
But at 600MHz the overhead of making a function call is negligible anyway - certainly compared to the speed of SPI which is at best about 30x slower than the CPU operates at.
If you want high throughput you won't be wanting to use the SPI library anyway, instead you'd be using DMA to transfer your data with minimal CPU intervention.


CAN Bus without Transceivers I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)

Here is the detail of my effort:

I have used this(1) library, and I want to run the CAN_EchoTest example(2).
As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.

I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:

CANTX1 in the schematics, refers to PIN with the label '53' on the board.
CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.

what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.

Thank you in advance

(1) github.com/collin80/due_can

(2) github.com/collin80/due_can/tree/master/examples/CAN_EchoTest

(3) www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf

(4) electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus

(5) www.keil.com/download/files/canprimer_v2.pdf

(6) www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.

You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil


HC-05 master and slave I have a silly question that came to my mind
when communicating between HC-05 and A smartphone, the smartphone is considered as the master,
and the HC-05 is considered a slave.
master will send data to the slave and then the slave will send these data to the MCU.
my question here is that, what is the MCU considered if it is not a master or slave?
if I got something wrong, I'll be glad if you correct it for me.
thank you

You have a misconception about the interfaces involved. Actually we have 2 different interfaces here: Bluetooth and Serial (UART). The HC-05 is a Bluetooth Serial bridge.

The Bluetooth interface has a fixed concept of master and slave. Every connection needs to have only 1 single master. This concept applies only to the communication between HC-05 and the smartphone. It has nothing to do with the MCU itself, because the MCU does not do any Bluetooth communication.

The second interface is the Serial (UART) interface between the HC-05 and the MCU. For this interface there is no concept of master/slave, because it is not needed. Either of them can send independently on their corresponding TX pin and can receive on their RX pin.

These are two totally independent and different communication interfaces. The HC-05 just forwards data between the interfaces.


Implementing AT commands with Arduino and ESP8266 Being a newbie to Arduino, I'm trying to implement AT commands in the serial monitor, though in vain. After connecting the ESP8266 (01) module to an Arduino Uno, I tried to scan for the nearest network present [code link: https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/scan-examples.md#simple-scan] and it worked perfectly.

But the moment I am trying to connect to send AT commands (even manually), it shows nothing. In addition, if(Serial.available()) and if(esp8266.available())< both are giving false value.

What am I doing wrong?

You don't give a circuit diagram or very much detail about what you've done, but if I guess correctly...

You have flashed the code in your link to the ESP-01 (perhaps using the Arduino as a serial port adapter). That code is now running on the ESP itself - it's not running on the Arduino and controlling the ESP.

Flashing the ESP erases the stock firmware, so the ESP can no longer respond to AT commands.

I don't know of a way to reprogram the 'AT' firmware into the ESP but perhaps Google will help.

If I've guessed incorrectly, please explain exactly what you have done - with circuit diagram, setup steps and code.


WDT and RadioHead with delay() The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
RadioHead ASK library (slimmed down)

What I want to do is:

deep sleep
wake up every minute
turn on sensor
take measurement
transmit data
back to sleep

This works when I test it seperatly, where it goes awry is when I combine RadioHead with WDT and then try to use a delay. This always hangs.

Probably a timer issue, I am looking for a work around.
I need the delay because I need to start the sensor, wait .5 sec and then take a measurement. Maybe I should give the ATtiny85 just some job to keep it busy for 0.5 sec?

This is working code, when I uncomment //  driver.init(); it will fail.

// RadioHead ASK
#include <RH_ASK.h>

// Sleep
#include <avr/sleep.h>
#include <avr/wdt.h>

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

// Absolute reference PB to overcome inter-IDE issues
#define T_PIN 1 // transmission
#define L_PIN 3 // optional LED pin
#define S1 A2
#define S2 A1
#define BAUD 2000

// Baud rate, receiver, transmitter
RH_ASK driver(BAUD, 9, T_PIN); // pin 9 is non existent

// Watchdog
volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

// Sleep
void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

// Setup for Watchdog
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
//  driver.init();
  setup_watchdog(8);
}

void loop()
{
  if (f_wdt==1) {
    pinMode(0, OUTPUT);
    digitalWrite(0, HIGH);
    delay(500);
    digitalWrite(0, LOW);
    delay(500);
    system_sleep();
  }
}

The RH_ASK library uses timer0, which is also used for millis and delay.

Quick workaround is to use the standard AVR delay instead.

#include <util/delay.h>

...

_delay_ms(500)


Button press with Arduino repeated many times I have 5V -> button -> 10K resistor -> PIN2 setup with Arduino UNO.

My code is very simple:

int count = 0;

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

void loop() {
  int state = digitalRead(2);
  Serial.println(state);
  if (state == HIGH) {
    count++;
    Serial.print("Hi");
    Serial.println(count);
  }
  delay(1000);
}

If the button is pressed print "HiX", but what I get is very strange. When I press the button only once I get this:

0
0
0
0
0
1
Hi1
1
Hi2
1
Hi3
1
Hi4
1
Hi5
1
Hi6
1
Hi7
1
Hi8
1
Hi9
1
Hi10
0

The button press is registered 10 times.

What am I doing wrong ?

I can't comment that's why I'm writing this as an answer but,

Are you doing exactly this this to wire the button?

I'd like to see your schematic but from what you describe there's a pull-down connection missing


how to combine two code of arduino uno int mamank=13;
void setup() {
  pinMode (mamank,OUTPUT);
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  if(sensorValue>550)digitalWrite(mamank,HIGH);
  else if(sensorValue<500)digitalWrite(mamank,LOW);
  delay(100);
}

-----------------------------------------------AND this code----------------------

int red=2;
int green=3;
int blue=4;

void setup () {
  pinMode (red,OUTPUT);
  pinMode (green,OUTPUT);
  pinMode (blue,OUTPUT);
  Serial.begin (9600);}

void loop() {
  // read the input on analog pin 0:
  int value = analogRead(A1);

  if (value > 500) {
    Serial.println("Very heavy Rain");
    digitalWrite (red,HIGH);
    digitalWrite(green,LOW);
    digitalWrite(blue,LOW);}
  else if ((value > 300) && (value <= 500)) {
    Serial.println("AVERAGE Rain");
    digitalWrite (green,HIGH);
    digitalWrite (red,LOW);
    }
  else{
    Serial.println("Dry Weather");
    digitalWrite (blue,HIGH);
    digitalWrite (red,LOW);
    digitalWrite (green,LOW);
  delay(100);
  }
  }

Put the stuff before setup() together, fix any duplicates:

int mamank=13; <<< pin assignment? If yes, this can be byte
int red=2; <<< pin assignment? If yes, this can be byte
int green=3; <<< pin assignment? If yes, this can be byte
int blue=4; <<< pin assignment? If yes, this can be byte

Put the stuff in setup() together, fix any duplicates

void setup() {
pinMode (mamank,OUTPUT);
Serial.begin(9600);
pinMode (red,OUTPUT);
pinMode (green,OUTPUT);
pinMode (blue,OUTPUT);
Serial.begin(9600);  <<< duplicate, so delete this line
}

Put the stuff in loop() together, then check the desired functionality:

void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
if (sensorValue>550) {
digitalWrite(mamank,HIGH);
}
else if (sensorValue<500) {
digitalWrite(mamank,LOW);
}
delay(100);
// read the input on analog pin 0:
int value = analogRead(A1);
if (value > 500) {
Serial.println("Very heavy Rain");
digitalWrite (red,HIGH);
digitalWrite(green,LOW);
digitalWrite(blue,LOW);
}
else if ((value > 300) && (value <= 500)) {
digitalWrite (green,HIGH);
digitalWrite (red,LOW);
}
else {
Serial.println("Dry Weather");
digitalWrite (blue,HIGH);
digitalWrite (red,LOW);
digitalWrite (green,LOW);
delay(100);
}

}


Passing struct from main.cpp to a class Sorry if this question been posted but I couldn't find the one that matches my issue. I couldn't pass my struct values from the main file to a class. Any ideas? I got this:

error: no matching function for call to 'ODriveArduino::SetParam(R_motor_params&)'

Main.cpp:

#include ODriveArduino.h
ODriveArduino odrive(Serial1);

struct L_motor_params{
 int axis=1;
 float vel_Gain= 2.5f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};
struct R_motor_params{
 int axis=0;
 float vel_Gain= 2.75f/10000.0f ;
 float pos_Gain= 40.0f;
 float vel_Int_Gain= 0.0f/10000.0f;
};

void setup() {
  struct R_motor_params M;
  odrive.SetParam(M);
}

ODriveArduino.h:

class ODriveArduino {

private:

    struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
    };

public:
    ODriveArduino(Stream& serial);

    // Commands
    void SetParam(struct motor_Params M);

 }

ODriveArduino.cpp:

#include "ODriveArduino.h"
template<class T> inline Print& operator <<(Print &obj,     T arg) { obj.print(arg);    return obj; }
template<>        inline Print& operator <<(Print &obj, float arg) { obj.print(arg, 4); return obj; }

ODriveArduino::ODriveArduino(Stream& serial)
    : serial_(serial) {}

void ODriveArduino::SetParam(struct motor_Params M){
  Serial1 << "w axis" << M.axis << ".motor.config.pos_gain " << M.pos_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_gain " << M.vel_Gain << '\n';
  Serial1 << "w axis" << M.axis << ".motor.config.vel_integrator_gain " << M.vel_Int_Gain << '\n';
}

It looks like you're trying to implement polymorphism without implementing polymorphism.

What you have done is create three completely independent structures and assumed that they will all work together just because they are the same size, with similar names, and fields named the same. That's not the case. They are all completely separate.

Instead you want just one structure but to use it multiple times to create different variables:

// from ODriveArduino.h, but move *outside* the class
struct motor_Params{
      int axis;
      float vel_Gain;
      float pos_Gain;
      float vel_Int_Gain;
};

// in your code
struct motor_Params left_params = {
    1, 2.5f/10000.0f, 40.0f, 0.0f/10000.0f
};

struct motor_Params right_params = {
    0, 2.75f/10000.0f, 40.0f, 0.0f/10000.0f
};

// later
  odrive.SetParam(left_params);


Which Arduino for many analogue sensors (and WiFi)? For context, I come from a very software-heavy background so I know very little about hardware.
I'm looking to build a system that requires at least 6 sensors (pH, electrical conductivity, humidity, temperature, light intensity, flow rate), and I want to send all of this input over WiFi at ~10 minute intervals. Most of these sensors will be analogue.
I noticed that for example the Arduino Uno only has 6 analogue inputs. Plus from research, I would need to connect a WiFi module to the Uno which seems too much of a hassle and added cost.
I'm looking at the ARDUINO NANO 33 IOT right now. It seems perfect for what I want to do since it's cheap, has 8 analogue pins, and has WiFi out-of-the-box. Is my reasoning correct in choosing this Arduino? I'm wondering why something with WiFi capability and more pins is cheaper than the Uno.
Thanks in advance!

For short answer: Just use NodeMCU ESP32 or any ESP32 dev board.
TLDR;

ESP32 is actually a wifi module but has very powerful processor (240MHz max), way more faster than Arduino Uno (atmega328 @16MHz). Because of this, wifi comes as natural for ESP32.
You can even buy ESP32 dev board around US$10 (include shipping) while the esp32 module itself costs only $5
Arduino UNO 33 IOT is simply SAMD21 (@48MHz) with external wifi module. This wifi module alone costs about US$10. This configuration is similar to Arduino UNO + wifi shield but of course cheaper because you don't need an extra costly shield for wifi.
The expensive wifi shield is actually HDG204 wifi SIP (system in package) + 32-bit AVR AT32UC3C1512C (66MHz max). Pretty much the wifi shield piggy back on Arduino UNO is 4 times faster than 8-bit micro atmega328 of Arduino UNO. So... it's pricey.
Edit:
ESP32 has 2x 12-bit ADC with 16 channels exposed out to IO pin on most of ESP32 dev board.
If you just read some temperature sensors, range finder sensors, humidity sensors... You are good with most of ADC inside microcontrollers these days. Unless you are building instrumentational device, well, this is a whole different story.


ESP32-CAM interfacing with CCS811+HDC1080+BMP280 I want to measure Temprature, Pressure, Humidity and CO2 in a room with ESP32-CAM & CCS811+HDC1080+BMP280

Since this module is combination of 3 sensors. Can I integrate it with ESP32-CAM over Software SPI ?

No. Those three devices are I2C devices, not SPI devices.

Using that is no different to using three individual sensors all wired to the same I2C bus.


How to return Char Array Value in Arduino IDE Function? Function

char* getConnectDetail(int starting){
  String data;
  for(int i=0;i< 1024 ;i++) {
    if(EEPROM.read(i+starting) != 0){
    data += char(EEPROM.read(i+starting));
    }
   }

   int str_len = data.length() + 1;
  char char_array[str_len];
  data.toCharArray(char_array, str_len);
  return char_array;
}

When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it.
I just want to know whats wrong with my returning method.

char char_array[str_len]; is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.

If the caller creates data and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make data a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.


Temperature on two 7-segments displays I'm new to the arduino board and my teacher gave us a project with little to no teaching about the language the board uses, or how to effectively program with it.
I'm trying to read temperature from a DHT11 and display it on two separate 7-segments displays. I've been trying to do this by editing a code he provided us that makes one display count from 0 to 9. I've been to hook up and read the DHT11 and split the temperature into two variables. But I have no idea how to make the variables display on the seven segment displays. My code is.

//DHT11 set up
#include <dht11.h>
dht11 DHT11;
void setup()
{
   DHT11.attach(4);
   for (int i = 0; i < 4; ++i)
    pinMode(i, OUTPUT);
   for (int i = 8; i < 11; ++i)
    pinMode(i, OUTPUT);
}
static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;
// Output pins.
static int output[] = {0,1,2,3};
// 8421 code lookup table.
static int segs_encoding[][4] =
  {{0,0,0,0},   //=0
    {0,0,0,1},  //=1
    {0,0,1,0},  //=2
    {0,0,1,1},  //=3
    {0,1,0,0},  //=4
    {0,1,0,1},  //=5
    {0,1,1,0},  //=6
    {0,1,1,1},  //=7
    {1,0,0,0},  //=8
    {1,0,0,1}}; //=9
// Outputs an 8421 decimal digit on the output pins from
// base to base + 3 in big endian order.
void show(int base, int num) {
 for (int i = 0; i < 4; ++i) {
   if(segs_encoding[num][i] == 1) {
     digitalWrite(base + 3 - i , HIGH);
   } else {
     digitalWrite(base + 3 - i , LOW);
   }
  }
}
// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
// force value to displayable range because show() doesn't do any sanity
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10);
}
void loop() {
  static int i = 0;
  show_decimal(i);
  delay(1000);
// Increases the counter.
  ++i;
  if (i == 10)
    i = 0;
}

Let me know if you guys need pictures of my breadboard set up, thanks for any help you guys can provide.

The show() function already has support for specifying the first pin of the display. So if the second digit is starting at pin 8 and connected in the same order then it should be as simple as:

// Output a 2 digit decimal value.
void show_2digit_decimal(int num) {
  // force value to displayable range because show() doesn't do any sanity checks
  if (num < 0)
    num = 0;
  if (num > 99)
    num = 99;
  // display it.
  show(0, num%10);
  show(8, num/10); // int/int always rounds down to the nearest int
}

You will also have to add the appropriate pinMode(<pin>, OUTPUT); commands to the setup() function to make the pins outputs.

----- update

To get the temperature to display first get rid of these lines, they aren't doing anything useful

static int temp = DHT11.fahrenheit();
static int digit_0 = temp % 10;
static int digit_1 = temp - digit_0;
static int digit_2 = digit_1 / 10;

And then change the loop function to being

void loop() {
  show_2digit_decimal(DHT11.fahrenheit());
  delay(500);
}

Although unless the teacher is completely incompetent you should have been able to work that out yourself, it's not exactly rocket science. If unsure take a guess and try it first before asking. The logic is simple enough that you should be able to work it out. For syntax errors the compiler error messages will normally tell you exactly what's wrong.


Digital Pin State - Some 1, Some 0 I'm running a sketch that looks for inputs to digital pins 3, 4, 5, 6, and 7.  The gist of the sketch is that it's a digitalRead() from 3-7 with a Serial.println() to the monitor. The odd thing is that without any pins connected I'm seeing "0" on some and "1" on others.  I there a reason some will be "0" while other are "1" without anything connected?  I imagine that all pins should read "0" until voltage is detected.

Based on my limited experience I draw the conclusion that a pull-up resistor will likely resolve my problem.  Thoughts?

Yep, in fact I would configure them as INPUT_PULLUP (which uses a built-in resistor), unless you are actually wiring pull up resistors of your own to them.

Also the Digital pins Tutorial has a bit more info on the modes possible.


Where can I find magnetic declination lookup table? Is there a way to get approximate value of magnetic declination from GPS coordinates?

My Arduino-based device has a Magnetometer and a GPS, and uses magnetic declination in calculations. I would like to avoid having to configure it by hand.

I have found references to https://www.ngdc.noaa.gov/geomag/WMM/soft.shtml online, but the site seems to be down (Google has a cache of the site but not of the code).

Is there another way of getting magnetic declination from GPS coordinates? Doesn't have to be precise, +/- 10% would work just fine.

No, the North pointed by GPS coordinates are extracted using the velocity heading which would represent the true North. If you get the ECEF (earth centered earth fixed) coordinates from the GPS you can convert it to a local ENU (east north up frame) and calculate the heading from the velocity vectors (take a look here if you need the formulas for that).

However, this site http://www.magnetic-declination.com/ can provide you a estimate for magnetic declination at your location.

EDIT
From the comment I came across this topic which lead to this

you can play with the code provided and take it as a template for your needs to create a lookup table. The software used for creation of the files is the one present in the site you pointed. Just downloaded the linux zip file and tested it with the sample txt coordinates provided and all seems ok.

For the record the command used was (yes for some reason the extension exe is present but this is linux binary):

./wmm_file.exe f sample_coords.txt out.txt

which created a out.txt equal to sample output file provided. Now this file can be used by the function void build_lookup_table() (present on grab60_char.c) to build the lookup table you need.


How to load Image in Arduino? In my recent project, I want to load Image in my Arduino. Is there any library available that can be used for loading Image in Arduino. Give some suggestion. Thank you!

Yes there is a library to load the image to Arduino called as "TFTLibrary".

Loads an image file from the SD card into a named instance of PImage. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. Images can be smaller or larger than the screen resolution (160x128), but there is no method on the Arduino for image manipulation. The images should be sized before you put them on the SD card. The TFT library has the ability to read .bmp files off the root of a SD card and display them on the screen. It is possible to load 24 bit bmp image only.

Syntax:

screen.loadImage(name);

Details available on Arduino website:
https://www.arduino.cc/en/Reference/TFTLoadImage


Changes to user included library I've been putting a small helper library together which I'm just including manually via the libraries sub-directory. I've just made some changes to the library in the filesystem however when trying to compile a previous sketch referencing it (after making the appropriate changes), the compiler is complaining and it appears to still be using the old version of the library. What's going on here and what is the correct way to update such a library?

I have tried completely reloading the Arduino IDE to flush out any caches etc. but that didn't help

Whatever compiler you are using (Arduino IDE?) should have a 'verbose' setting that you can activate.  This will give you a HUGE amount of output, but will also show you exactly what file is being accessed for the library in question.
When I do this, I copy/paste the entire output into Notepad++ and use its search capabilities to sort through all the chaff.
Frank


UNO Power supply to USB If UNO is supplied with 9VDC to Power Jack.
Will it supply power to USB connector?

No

As you can see in the schematic, the USBVCC is only connected (via a MOSFET) to the 5V line, when the voltage on VIN (barrel jack) is LOW.

If you connect 9V to the power jack, the mosfet will turn of, and disconnect the USB power from the 5V on the UNO.


Is it possible to print a custom object by passing it to Serial.print()? I googled about it, but can't find the answer. As I would guess I would have to inherit from the Print class and somehow pass to its print methods the part of my object I would like to be printed. But I am not sure how to go about it or if it is even possible.

There is a class called Printable. If you inherit from that, and implement the size_t printTo(Print& p) function, your object can then be passed to the print functions:

class myClass : public Printable {
    private:
        int _val1;
        int _val2;

    public:
        myClass(int v1, v2) : _val1(v1), _val2(v2) {}
        size_t printTo(Print& p) const {
             size_t r = 0;

             r += p.print("One: ");
             r += p.print(_val1);
             r += p.print(" Two: ");
             r += p.print(_val2);
             return r;
       }
};

Then:

myClass ob(4, 5);

Serial.println(ob);
=> One: 4 Two: 5


Wireless Shield Not being detected w/ Arduino Uno R3 Wireless Shield is not being detected by arduino, not MAC address is displaying.
 Not sure what to try next, there is nothing noticeably wrong with the shield at first glance.

Green LED under status is on.

Shield Type: CC3000 WiFi Shield
Board Model: UNO R3

No Mac Address is being detected (my output in Serial Monitor)

Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0

My Script:

#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi...");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

Your problem:

You have a CC3000 WiFi shield
You are using the WiFi library for the Arduino WiFi Shield
The Arduino WiFi Shield is a HDG204 based shield, not CC3000

Get the right library for your shield, install it, and try the examples and tutorials that come with it.


Is Arduino IDE enough to program with C or C++? I am using Arduino IDE to program my ATmegas with bootloaders. I can directly manipulate ports, use timers, interrupts, PWM pins and timers, etc. Everything is working.

But this question arises: Does the Arduino IDE differ from AVR Studio in terms of using C or C++ on an ATmega chip?

I know AVR Studio has some features or something. My question is not about that. My question is that I am coding everything, not using extra libraries, features etc.

In terms of the core language features, there's virtually no difference. In the background, the Arduino IDE and Atmel/AVR Studio both use GCC to compile the code.

GCC is an excellent toolset which supports all the core language features of C++. Admittedly, the version which currently comes with the Arduino IDE is a little old, so it doesn't support C++11 onwards. However, a lot of C++11 features are not very relevant or useful for microcontroller programming anyway (e.g. threading).

You're also likely to use the same standard library for both, which is AVR Libc. It provides pretty much all the standard C functionality that you're likely to use in an AVR project. It doesn't include the C++ stuff though, such as streams, containers, and algorithms. These tend to be very resource-hungry though, so are best avoided anyway.

The major difference is basically flexibility. Atmel/AVR Studio is designed to let you work on a wide range of projects and customize the build to suit very specific needs. You can also use alternative libraries with it more easily. In theory, the Arduino IDE can be modified in similar ways, but it's a major hassle because it provides no GUI to do it.

It's also important to note that the Arduino IDE does a number of non-standard things, such as re-organising declarations and including libraries in strange ways. It's designed to be more user-friendly, but often ends up just getting in the way. There are usually ways to work around those issues though.


EMG control of solenoid valve I need some help with programming Arduino with EMG signals to control the solenoid pressure valve.
I wrote some program which is setting high and low state on the output pin, but it's not working properly.
First I create a plot to observe the signal level. And the plot looks like in the picture which I attached.

The basics concept of program is setting the high signal on the output when I flex muscles and when I relax the muscle it's should write low state on the output. My idea was based on triggering the on-off signals at the moment when the muscle is flexed, the value of signal is above 600 (now the diode should be ON and stay in ON state) and it drops and when I relax muscles the value rises once again to value around 600 more or less (now the diode should be OFF) and drops under 100.

const int ledPin=13;

const int sensorPin= 0;

int level;

const int threshold1=400;

const int threshold2 =500;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
    }

void loop(){

    level= analogRead(sensorPin);

    if (level > threshold1){

    digitalWrite(ledPin, HIGH);

    if (level > threshold2)

    digitalWrite(ledPin, LOW);

    }

I wrote new code, but I still have problems with proper sending of an ON and OFF     signal to the output.

When I flex the muscle I have high state on the output causing by first peak (LED is ON) but when I relax the muscle the second peak won't set the low state on the output. But when I flex the muscle once again the output change state to low and the diode is OFF. Do you have any suggestions what part of the code do I need to improve?

Here's the code:

const int ledPin=13;

const int sensorPin= 0;

int level;

int flex= 0;

int PreviousState = 501;

const int threshold1=600;

void setup() {

    pinMode (ledPin, OUTPUT);

    pinMode (sensorPin, INPUT);

    Serial.begin(9600);
}

void loop() {

    level= analogRead(sensorPin);

          if (level > threshold1 && PreviousState < threshold1){

          {

            flex =!flex;

          }

          if (flex == 1)
          {

            digitalWrite(ledPin, HIGH);

          }

          else

          {
            digitalWrite(ledPin, LOW);

          }

          PreviousState = level;

        }

    }

}

I see this problem more profound than just some if and else. As you may observe, there may be two peaks in flex and always there is one in relax.

What makes difference is the width of the pulse: flex is wide and relax is narrow.

You should detect the width. It can be measured by amount of times, when you detect a value in input that is over the treshold.

When the amount is less than some value when signal is very low again, you detected a LOW for output and if it is more than some value it means HIGH.

in setup

unsigned int times = 0;
unsigned int threshold = xxx;
unsigned int low = xx;
unsigned int high = yyy;

...

in loop

...
if (level > high) {
      times = times + 1;
} else if (level < low) {
     if (times > threshold) {
          digitalWrite(ledPin, HIGH);
     } else {
          digitalWrite(ledPin, LOW);
     }
     times = 0;
}


upcoming voltage from a button i use this simple code for arduino :

const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println ( buttonState ) ;
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println ( buttonState ) ;
  }
}

it's so basic program, I've seen some people work with Resistors when they use buttons, so i wanted to know why, i plugged in one side of the button to the pin 2 , no matter if i plugged in the other side of the button or no to the 5 volte source, the arduino started giving me some ones and zeroes therefore the blinking of the led, so basically that means there's a certain voltage comming from the button to the pin 2, I wonder why and what's the reason for this ?

I see you are new to Arduino, so let's start:
1) if you say it works you might be using an circuit like this:

which is not all bad but you might find trouble. I explain:

1. When you set pinMode(pin,INPUT); you tell arduino to enable a high-impedance state on that pin: it's equivalent to 100Mohm resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings.
That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).

2. So you end up with something like this:

I would personally put the resistor and the GND wire between the button and the digital pin wire.
I hope I was useful! If you need/want more documentation check those two links out:

https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section

https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.


Concern myself with current draw from digital pins used as INPUT with internal pullups? My project is using a genuine Arduino Mega 2560, probably 3-4 yrs old since purchased (I don't see any revision numbers on the PCB).  It's being used to read a lot of switches, buttons and drive some LED's and displays.

When using a digital pin as INPUT with the internal 10k pullup enabled, do I need to consider the draw with respect to the 200mA total through all pins?  Is it simply the 10k ohm resistor with 5V so 0.5mA?  Can I just ignore it? (there's only so many pins I suspect I can ignore it)

I've seen several posts/pages about driving LED's using transistor arrays powered by an external source and those spec sheets describe the transistor input currents so I can estimate the draws for those elements, but not sure if I need to concern myself with the Arduino pins used as INPUT.

You are right. The current through digital inputs is so low, that you can normally ignore it.

And the 0.5mA, that you calculated don't flow all the time, just, when the corresponding button is pressed and thus shorted to ground, because only then a current will flow through the pullup resistor. The current into the actual input hardware is even smaller. So, as long as not all buttons are pressed at once, the current will be even lower as calculated.

Buttons are somewhat voltage devices. They don't need a specific amount of current, just of voltage. So the actual value of pullup/pulldown resistors are not critical. LEDs in contrast are current devices. They need a specific current to light up, which is often higher, than the maximum output current of a digital pin. Thus they are often driven with an additional transistor.


Can an IC be programmed by an Arduino and then be removed, to be used in an external breadboard? I wanted to find out if is possible to write programs into a micro controller using the Arduino and use the micro controller independent of the Arduino board?

Yes. The compiles code will is burned in the Arduino ROM. You can then take the Atmel chip (the Arduino microprocessor) and use it. You only need a few extra component for a chip like the 328p (Arduino Uno).


ESP8266 HTTPS post body request with WifiClientSecure Is there a way to post HTTPS body request in Arduino esp8266.
I am able to HTTPS parameter request with WifiClientSecure library,but is not safe compared to Request Body send in POST.

You do it like any other POST. It's just you happen to be using a secure client to make the connection.

Open the connection
Send the right headers, including a Content-Type and Content-Length and maybe a Content-Encoding if you encode it.
Send the body

It's not any different to an unencrypted POST request.


Posting data with ESP8266 module? I have an ESP8266 module attached to an Arduino Uno that is connected to my local network. On the network, at address 192.168.1.13, I have a nodejs/express server running on port 3000. How would I go about posting an eight digit number from the Arduino to the webserver? In my current attempts the server console isn't receiving any data when using AT+CIPSEND while connected to it.

EDIT: My Code is as follows:

     #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
  Serial.println("Sending an AT command...");
  ESP8266.println("AT+CWMODE=1");
  delay(1000);
  ESP8266.println("AT+CWJAP=\"username\",\"pass\"");
  delay(10000);
  ESP8266.println("AT+CIPMODE=1");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");
  delay(1000);
  GetData();

}
void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}
void GetData(){
  ESP8266.println("AT+CIPSEND=4");
  ESP8266.print("test");
}

and My output is this

  Sending an AT command...
Got reponse from ESP8266: AT+CWMODE=1

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CWJAP="surveillancevan4","7073199495"

Got reponse from ESP8266: AT+CIPSEND=4

Got reponse from ESP8266: testI

EDIT 2: I modified my code to this

    #include <SoftwareSerial.h>

const byte rxPin = 9; // Wire this to Tx Pin of ESP8266
const byte txPin = 10; // Wire this to Rx Pin of ESP8266
// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600); // Change this to the baudrate used by ESP8266
  ESP8266.println("AT");
  delay(1000);
  ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\",3000");
  delay(20000);
  String request = "POST /test HTTP/1.0 \r\n";
  ESP8266.println("AT+CIPSEND=19");
  delay(5000);
  ESP8266.println(request);

}

void loop() {
 while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

and now my output claims it posted successfully, but I'm still not seeing any data in my nodejs server. Here is the output:
Got reponse from ESP8266:

AT

Got reponse from ESP8266:

Got reponse from ESP8266: OK

Got reponse from ESP8266: AT+CIPSTART="TCP","192.168.1.13",3000

Got reponse from ESP8266: CONNECT

Got reponse from ESP8266:

Got reponse from ESP8266: O

Got reponse from ESP8266: busy sytes

Got reponse from ESP8266:

Got reponse from ESP8266: SEND OK

I can confirm that it is connecting to my web app because when I run the code on the module without the server running it returns an error.

ESP8266.println("AT+CIPSTART=\"TCP\",\"192.168.1.13\test\",3000");

That line is going to fail miserably for a number of reasons:

You need to provide an IP address or domain name - NOT a URL
Even if you could provide a URL this bit 192.168.1.13\test would end up, after C escaping, as 92.168.1.13        est since \t is a TAB character.

And then on top of all that I assume you are connecting to a HTTP server, yet you aren't sending a HTTP request, you are just sending the word "test", which the HTTP server has no hope of ever understanding.

You need to formulate and send a proper HTTP request and send it to the server. I suggest you go and look at a few tutorials and maybe look up how HTTP Servers actually operate and what the protocol looks like.


MkrWan freezes after short power outage My MkrWan running on 5v 3A external adapter without battery. When short time(15-20 second) power outage happens Mkrwan still seems running. I think it consumes power on capacitors on adapter but voltage value drops. When electric comes back, it doesnt work anymore. Why it doesnt reset itself ?
How to solve this problem ?

I connected Lipo battery to device. On power outages it supply power to board and brown out problem solved. Thanks a lot


add ID number to the feather m0 bootloader (flash) I'm trying to add a serial number to the bootloader's flash area of Adafruit Feather m0 board. Seems like feather m0 0-0x2000 area on the flash is non writable by the arduino sketch. i wanted to add a serial number to address 0x2000 - 8 on the flash.
The idea is for the data to be included in the bootloader elf\bin so i can easily flash it on devices and later on access it using flash address  (0x2000 - 8) with NVMCTRL.

I've started out with this solution:

downloaded the code from samd21 arduino bootloader github directory and in ./bootloaders/zero edited the boololoader ld script, first the "Memory" section

FLASH (rx) : ORIGIN = 0x00000000, LENGTH = 0x2000 /* First 8KB used by bootloader */
FLASHID (rx) : ORIGIN = 0x00002000 - 0x0008, LENGTH = 8

Then the 'sections' section:

.id_sec :
  {
    KEEP(*(.myid))
  } > FLASHID

This should have saved some room in the end of the flash for the id. now in the main.c file:

__attribute__ ((section(".myid"))) const unsigned long ID = 0xdead1234;

Which should have saved the 0xdead1234 hex value in the (0x2000-8) address.

The issue is this:
I compiled this code and linked it just fine, got .hex,.bin,.elf files.
If i'm correct (unless they are somehow compressed) i should be able to see the code 0xdead in the binary.
BUT i don't.
After objdump on the binary(any of them) i can't find the 0xde 0xad in any order anywhere.
The arm-none-eabi-size" --format=sysv -t -x build/.elf does not show the new section i added no where.
Also i do wonder, as i said the 0x2000 address on the flash is non writable once i flashed with atmel-ice \j-link even the bootloader code cannot write to it, i did define in the ld script that i want that memory region part of the flash so i do expect that the compiler + linker + jlink flasher will know to write that data to the right place but not sure.

Anyone got some experience with it ? did it before ?

This is quite an easy fix, actually.

The problem here is the compiler doesn't think the const is used for anything - so it (quite rightly) throws it away.

All you need to do is tell the compiler that it's used and all should be good:

__attribute__((section(".myid"),used)) const unsigned long ID = 0xdead1234;

And when you compile:

build/.elf  :
section             size         addr
.vectors            0x40          0x0
.text             0x18d4         0x40
.data               0x5c   0x20000000
.bss               0x34c   0x2000005c
.id_sec              0x4       0x1ff8
.ARM.attributes     0x28          0x0
.comment            0x80          0x0
.debug_frame        0x68          0x0
Total             0x1dd0

Properly, though, you should make some more changes to the linker script to properly isolate those 8 bytes of flash (though you don't have to).

You should reduce FLASH by 8 bytes.
You should include the FLASHID length in the __sketch_vectors_ptr calculation.

That's:

MEMORY
{
  FLASH   (rx) : ORIGIN = 0x00000000, LENGTH = 0x1FF8 /* First 8KB used by bootloader */
  FLASHID (rx) : ORIGIN = 0x00001FF8, LENGTH = 8
  RAM    (rwx) : ORIGIN = 0x20000000, LENGTH = 0x00008000-0x0004 /* 4 bytes used by bootloader to keep data between resets */
}

And:

PROVIDE(__sketch_vectors_ptr = ORIGIN(FLASH) + LENGTH(FLASH) + LENGTH(FLASHID));

That way the compiled bootloader code can never be placed in the FLASHID area (not that it would at the moment, but if a new version of the bootloader were released that used 100% of the lower block of flash it would conflict).

Of course, if all you need is something unique to identify the board with, all AVR and SAMD devices that have built-in USB support have a unique ID number. This is intended to be used as the Serial Number for the USB, but could also be used for a MAC address for Ethernet (or for portions of it anyway) or other unique "node" addresses.


ESP32 - DeepSleep loop or not? I'm trying to create a battery & solarpowered ESP32 for future use with sensors.
It connects to Wifi, MQTT, publishes some readings and status messages and go back to sleep. From time to time (can happen after few sleep cycles and sometimes after few hunderds cycles )I get 2 unexplained behaviours : 1) fail to connect to MQTT at boot, 2) fail to sleep.
Sometimes those behaviours happen simultaneously.
Is there a known issue with deepsleep and MQTT (using PubSubClient ) ? Most deepsleep example I see online, all code is outside loop()section - is it mandatory to be like that ?
I don't share code, since it is more a general question.
Guy
EDIT1

most of callback was commented out, remaining only printing incoming message.

LED was attached to a GPIO, generating a blink on loop() - when sleep succeeds - it goes off, when it fails, it stays on. This test shows that when this "error" happens, code actually stop running, but does not enters deep sleep ( power-wise )

Is there a known issue with deepsleep and MQTT ?

No. There may be a specific problem with the specific library you are using, but the concept of there being an issue with MQTT in general is nonsense.

Most deepsleep example I see online, all code is outside loop()section - is it mandatory to be like that ?

No, that's just being structured and tidy with your code. Whether code is in loop or in functions that are called by loop makes no difference. It can be a lot easier to manage your code if you structure it in functions rather than dumping it all in loop.


Arduino receive response from SIM800H to AT+CCLK? command I've been trying to make a program that interacts with SIM800H trough AT commands. It worked with the String class, but it was full of "memory leaks" and after a few hours it just hanged. Then I tried to write it again with char arrays, but for some reason I couldn't get it to work properly.

Can someone suggest me a correction to my program and also a way to get char by char with loop and Serial.read();? Serial in this case (Arduino Leonardo) is the USB port and Serial1 is the port to the modem.

Here is my code:

const long interval = 2000;
static long currentMillis;

char wherecclk = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256] = ""; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

int rdpos = 0;

void setup() {
    Serial.begin(9600); //USB to Computer
    Serial1.begin(9600); //UART to Modem
    Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
    wherecclk = 0;
    if (Serial1.available () > 0) { //when something comes on real serial
        strcpy(serialdata, "OK\n\n+CCLK: \"04/01/01,01:35:31+00\"\n\nOK\n"); //This is a real sample of the response coming from the modem emulated
        while (rdpos < 256) //loop timeout: 256 bytes
        {
            if (serialdata[rdpos] == '+') {
                break; //We have reached the first + char. Stop incrementing it
            }
            rdpos++;
        }
        if (serialdata[rdpos + 1] == 'C' && serialdata[rdpos + 2] == 'C' && serialdata[rdpos + 3] == 'L' && serialdata[rdpos + 4] == 'K') { //If the serial command mathes +CCLK save its position
            wherecclk = rdpos;
        }
        rdpos = 0;

        if (wherecclk != 0) {
            rtcy1[0] = serialdata[wherecclk + 8]; //getting first char with its offset
            rtcy1[1] = serialdata[wherecclk + 9];
            rtcy1[2] = '\0';
            rtcm1[0] = serialdata[wherecclk + 11];
            rtcm1[1] = serialdata[wherecclk + 12];
            rtcm1[2] = '\0';
            rtcd1[0] = serialdata[wherecclk + 14];
            rtcd1[1] = serialdata[wherecclk + 16];
            rtcd1[2] = '\0';
            rtch1[0] = serialdata[wherecclk + 17];
            rtch1[1] = serialdata[wherecclk + 18];
            rtch1[2] = '\0';
            rtcm1[0] = serialdata[wherecclk + 20];
            rtcm1[1] = serialdata[wherecclk + 21];
            rtcm1[2] = '\0';
            rtcs1[0] = serialdata[wherecclk + 23];
            rtcs1[1] = serialdata[wherecclk + 24];
            rtcs1[2] = '\0';
        }

    }

    if (millis() - currentMillis >= interval) //This is done every second
    {
        Serial1.print("AT+CCLK?\r"); //ask for the time
        //delay(50);
        Serial.println("");
        Serial.println("=====");
        Serial.println(millis());

        Serial.println("YEAR: ");
        Serial.print(rtcy1[0]);
        Serial.println(rtcy1[1]);
        Serial.println("MONTH: ");
        Serial.print(rtcm1[0]);
        Serial.println(rtcm1[1]);
        Serial.println("DAY: ");
        Serial.print(rtcd1[0]);
        Serial.println(rtcd1[1]);
        Serial.println("HOUR: ");
        Serial.print(rtch1[0]);
        Serial.println(rtch1[1]);
        Serial.println("MINUTE: ");
        Serial.print(rtcmm1[0]);
        Serial.println(rtcmm1[1]);
        Serial.println("SECOND: ");
        Serial.print(rtcs1[0]);
        Serial.println(rtcs1[1]);

        currentMillis = millis();
    }
}

Here is the output (a screenshot, because serial monitor doesn't give me full code):

You declare your variables for month and minute differently (rtcm1[3] vs rtcmm1[3]), but you load rtcm1 with month, and then a few lines later, with minutes.


very small PWM when timer says zero I'am getting a little PWM signal when my potentiometer is at zero and OCR2B always reads zero on the serial monitor.  My LED has low forward voltage but I still get a little PWM on the pin when I prob it. I use timer 1 and it works good. I have a picture of the scope.

#include "RTClib.h"
RTC_DS3231 rtc;

#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analog0(A0, true, .001);

unsigned int nowHour;

int analogOutPin3 = 3;
int sensorValueTimer2Pin3;

long z;

int analogOutPin9 = 9;
int analogOutPin10 = 10;

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  TCCR2A |= (1 << COM2A1);
  TCCR2A |= (1 << COM2B1);
  TCCR2A |= (1 << WGM21);
  TCCR2A |= (1 << WGM20);
  TCCR2B |= (1 << WGM22);
  TCCR2B |= (1 << CS22);
  OCR2A = 249;   //1KHz frequency
  TCNT2 = 0;
  //====================mode 5 pin 3,11==============//

  pinMode(3, OUTPUT);

  rtc.adjust(DateTime(2014, 1, 21, 7, 0, 0));
}

void loop() {
  DateTime now = rtc.now();
  nowHour = now.hour();
  analogWrite(9, LOW);
  analogWrite(10, LOW);
  analog0.update();
  sensorValueTimer2Pin3 = ((analog0.getValue() * 249L) / 1024);
  if (nowHour >= 7 && nowHour <= 21) {
    z = sensorValueTimer2Pin3;
    OCR2B = z;
    Serial.println(OCR2B);
  }
}

When analogWrite writes 0 or 255 value, it actually disables PWM output and sets the output to 0 or 1 correspondingly (maybe just one of them).
That's because there is just 256 values, but with both fully off and fully on PWM you'll need 257 values to archieve it.
If you're using direct access into OCRx, you have to make a choice if you want to have not fully on pwm or not fully off pwm (by setting polarity with COM2Xx)

Btw, you should clear TCCR2A/TCCR2B as all of the timers are configured by Arduino core to be running and prepared for the analogWrites...


Failed to initialise SD card on Leonardo I'm trying to connect SD card reader to my Arduino. For testing i'm running CardInfo example.

It seems like it runs ok when I'm running it on my Arduino UNO, but it fails to initialise SD Card while i'm running it on any Arduino with Atmega32U4 chip. I tried on two Leonardo's and Micro Pro.

This is my pinout:

CardReader       Arduino

CS          <->     4
SCK         <->    13
MISO        <->    12
MOSI        <->    11
VCC         <->    5V
GND         <->    GND

I'm using Library in version 1.2.1 if that's make difference.

Does anyone have any suggestions?

A Leonardo has the SPI pins on the ICSP header, not on pins 11, 12, 13.

And a Pro Micro has the SPI pins on 14, 15, 16.


What is the maximum frequency input signal that I can accurately track on a GPIO pin? This all started with me wanting to use an Arduino to make a tachometer. This is all now working fine, but it got me wondering what the highest frequency digital signal that I could read?
So I built a simple test sketch and have run this on both a Nano and an ESP32. The result was about 6300Hz on both. Anything above this gives chaotic results. This is somewhat lower than I expected.
Has anybody done better than this?

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

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

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

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

what the highest frequency digital signal that I could read?

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

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

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


My servo is misbehaving I have been trying to get my 9g tower pro servo to work and no matter what i do nothing happens. I connected the servo to the arduino with the red wire to 5v, brown to ground and orange to pin 6.

#include <Servo.h>
Servo myServo;

void setup(){
myServo.attach(6);
}

void loop() {
myServo.write(0);
delay(1000);
myServo.write(60);
}

I have been using this code to test it.
Another weird occurrence is when i disconnect the servo it sometimes start moving very slowly even though it has now power. I dont think the Uno is broken as other projects work fine on there, are my servos fried?

My guess is your drawing too much current from the Arduino 5v rail.

Try connecting the servo to it's own 5v source with of course a common ground with the Arduino.


RTClib library the second, second I'm using RTClib for my DS3231 module, the problem is the library is displaying the second without zero behind it: 22:1:1 and when i print the time on my 16x2 LCD time is displaying like this:

  22:22:59

  22:23:19

  22:23:29

  ...

  22:23:59

  22:23:10

  22:23:11

the second number of seconds is not getting cleared.
i know one solution to this is to use lcd.clear() function to update the LCD in each loop but is there any other way to clear that second number or do something so library show zero behind second?

It's your responsibility to format the time properly, not the library. The library just gives you a number. If you want a leading zero then it's up to you to provide that leading zero.

For example:

if (now.seconds() < 10) {
    lcd.print("0");
}
lcd.print(now.seconds());

Or:

char timestr[9];
snprintf(timestr, 9, "%02d:%02d:%02d", now.hours(), now.seconds(), now.minutes());
lcd.print(timestr);


Reading multiple DI pins in parallel as one byte/word I need to capture a single parallel 'snapshot' from a 10-bit shaft encoder. I understand that I can read individual bits and shift them into position, but any given input pin might change while reading the bits sequentially, which would give an bogus value. In fact, given the asynchronous nature of the device this is guaranteed to happen on occasion.

I've read hints that it might be possible to combine pins into a 'port' for this purpose but I can't find any examples. Is this ability available only on certain processors? Or is there some way to latch the input pins while scanning them into a pair of bytes, to avoid them changing while I read?

If not I suppose I could use external latches but I'm hoping to avoid additional hardware.

It did occur to me that I could sync readings using an ISR triggered by a change in the LSB, but alas, this encoder outputs Gray code. :(

Without knowing the encoder in question (which you seem extremely reluctant to disclose for some reason that I have trouble understanding) it is hard to give a good answer. However ...

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).

Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.

Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.

To read all of port D you could just do this:

byte foo = PIND;

(For inputting it is PINx, for outputting it is PORTx).

What could help is an I/O expander such as the MCP23017.

  I'm hoping to avoid additional hardware

Well, that's a pity.

I'm a tiny bit surprised that the device doesn't support some sort of "latching" of the data which gives you a finite time to extract the information from it. However without reading the datasheet I can't comment further.


send more than one integer on serial between Mega and nodeMcu i have 2 integers i want to send them from Mega to nodeMcu
i get them to talk to each other
by this one on Mega :-

#include <DHT.h>

#define DHTPIN 2      // Selecting the pin at which we have connected DHT11
#define DHTTYPE DHT11 // Selecting the type of DHT sensors

DHT dht ( DHTPIN, DHTTYPE ) ;

        void setup() {
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(9600);
      dht.begin ();

    }

    void loop() {
      //==========// DHT part
   humidity = dht.readHumidity ( ) ;  // Declaring h a variable and storing the humidity in it.
   temp = dht.readTemperature ( ) ; // Declaring t a variable and storing the temperature in it.
  // Checking if the output is correct. If these are NaN, then there is something in it.
   if ( isnan ( humidity ) || isnan ( temp ) ) {
     Serial.println ( " Sensor not working " ) ;
   }
   else
    Serial.println(humidity);

//========// Send to wifi
 if (Serial1.available()) {

    itoa(humidity,str1,10);
    Serial1.write(str1,2);
    itoa(temp,str2,10);
    Serial1.write(str1,2);
    }

and this on on nodeMcu :-

#include <SoftwareSerial.h>

SoftwareSerial swSer(14, 12, false, 256);
char str1[10],str2[10];
int i,j;

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

  Serial.println("\nSoftware serial test started");

}

void loop() {
  while (swSer.available() > 0) {

    Serial.println("Humidity is");
    for (i=0; i<3; i++){
    str1[i]=(swSer.read());
    }
    Serial.println (str1);
    Serial.println("Temp is");
    for (j=0; j<3; j++){
    str2[j]=(swSer.read());
    }
    Serial.println (str2);

  }

}

But i  get the  result on nodeMcu not in right order (sometimes humidity printed in place of temperature and verse vise and sometimes i get no.2

can some one help me please to figure what is wrong ?

I'd suggest some kind of character before each int so that the receiver knows which one it is getting.


How to access serial terminal through USBASP? I have an Arduino Pro Mini that I use with a USBASP to program. These are actually a clone Pro Mini and a clone USBASP I'm using.

With this configuration, is it possible for me to access the serial port on the Arduino, through the USBASP, using the IDE serial terminal? If so, this would alleviate another connection to the computer for debugging. How to do this?

From the USBASP documentation:

  Planned: serial interface to target (e.g. for debugging).

..and further on..

  Firmware:
  The firmware dosn't support USB Suspend Mode. A bidirectional serial
  interface to slave exists in hardware but the firmware doesn't support it yet.

Keep in mind, that's from 2011, so it's possible someone has built an updated version of the firmware with that functionality. You'd have to do some searching (I'm not familiar with any such firmware).

For now, your best bet is just getting a TTL serial-USB converter (they're cheap) and connecting it directly to the Pro Mini.


How to test the sleep / enable function of Stepper Driver? I am currently using an Arduino Mega 2560 to run this stepper motor driver (Big Easy Driver, ROB-11876 from sparkfun) https://www.sparkfun.com/products/11876.

I am trying to use the sleep or enable function on this chip to decrease the power consumption when I am not using the motor. I have all the rest of the driver working properly (steps, direction etc.) but when I hook up a wire to either the sleep or enable section and send a respective high or low it doesn't appear to do anything. (Chip works as normal, power consumption stays the same).

I have tested to see that the Arduino is outputting correctly and it seems to be. But other than this I'm kinda at a loss on what might be wrong.

Does anyone have any suggestions on why this might be or other things to test to try to narrow down the problem?

Found my answer from Sparkfun - see below

Just for future reference if anyone needs it I got the following from SparkFun:

On the Big Easy Driver Board, the Step, Dir, Sleep, Reset, and the Microstep pins are all >pulled high with 20kΩ resistors, while Enable is pulled low with the same. So sleep is >disabled (until explicitly enabled) and the stepper is enabled (until explicitly disabled).

For much of the use of this board, there is no real need to adjust these settings, but If you >want to achieve a low-power state you would pull the sleep pin low. This should disable much >of the internal circuitry on the IC. In order to reduce power, Enable should be pulled high >to disable the output FETs.
To test that the sleep function is working on the chip you can just jump it to low (ground). For me it turned out to be an error with the Arduino code rather than the chip. Here is also a good reference about pull-down / pull-up resistors. http://www.bit-101.com/blog/?p=3813


Disable interrupts when doing critical things? I've got a few functions like this that log, or do more critical things like get/save configuration variables.

/**
   Write weather data to csv
   commit: datetime,minHumidity,maxHumidity,minTemperature,maxTemperature,rainfall,irrigationRan
*/
void writeWeatherData() {
  noInterrupts();
  DBG_OUTPUT.println(F("[WEATHER DATA] Attempting to save weather data..."));
  bool writeHeader = SPIFFS.exists("/weather_data.csv") ? false : true;
  File file = SPIFFS.open("/weather_data.csv", "a");
  if (!file) {
    addPrintError("[WEATHER DATA] There was an error opening weather_data.csv for writing.");
    interrupts();
    return;
  }
  String data = "";
  if (writeHeader) {
    data += "datetime,minHumidity,maxHumidity,minTemperature,maxTemperature,rainfall,irrigationRan\r\n";
  }
  DateTime now = rtc.now();
  char buf[] = "MM/DD/YY hh:mm:ss";
  String t = now.toString(buf);
  float rainfall = getRainfall();
  data += t + "," + minHumidity + "," + maxHumidity + "," + minTemperature + "," + maxTemperature + "," + rainfall + "," + irrigationRan + "\r\n";
  if (file.print(data)) {
    DBG_OUTPUT.println(F("[WEATHER DATA] File was written."));
  } else {
    addPrintError("[WEATHER DATA] File write failed.");
  }
  file.close();
  DBG_OUTPUT.println(F("[WEATHER DATA] Task completed."));
  interrupts();
}

I surround  code with noInterrupts and interrupts however I am not sure if it is required. Assume that an interrupt is triggered at the exact moment when the above function is saving something, what exactly happens if I didn't have noInterrupts .etc.?

John Romkey provided you an excellent answer. I am adding this just to
provide another perspective, hopefully complementary.

Interrupts are meant to handle the most time-critical tasks. Those tasks
that cannot wait for the next loop() iteration, such as counting a
pulse from an encoder, or getting a byte out of the UART receive buffer.
If you delay them too much, they may miss their deadline, resulting in
unreliable operation of the whole program (counter missing pulses, UART
missing bytes...).

Sometimes you have a piece of code that cannot afford being interrupted.
Maybe it is extremely time-critical, like the generation in software of
a pulse that is exactly 0.5 µs wide. More commonly it will be
reading data from memory that is being modified by an interrupt handler,
and you don't want that data to be modified in the middle of the read
operation. Such pieces of code are called critical sections, and you
keep them safe in between noInterrupts() and interrupts(). If an
interrupt request fires while the program is running a critical section,
the request is put on hold and serviced only when the critical section
is done. This adds some latency to the interrupt which, if
excessive, can lead to the interrupt missing its deadline. This is the
reason critical sections should be kept as short as possible.

You have been told that interrupt handlers should be kept as short as
possible, but I am not sure you know why it is so. The fundamental
reason is that interrupt handlers are themselves critical sections.
While a handler is running, other interrupts are blocked. On some
architectures (notably not AVR, I don't know about the ESP), only
interrupts of lower priority are blocked, but it is still an issue. The
rationale for keeping those handlers short applies equally to any
critical section.

Now, just to provide an example of the sort of bad things that can
happen if you block interrupts unnecessarily, consider this piece of
code:

noInterrupts();
Serial.println("Inside critical section.");
interrupts();

What this does is put the string "Inside critical section." in a
software buffer. Not a huge task you may say. Actually pushing the bytes
out to the UART is the job of an interrupt handler, triggered by the
UART when it is ready to accept a new byte. But then what happens if
there is not enough free space in the buffer for the string? In this
case, Serial.println() waits in a busy loop. It waits for the
interrupt to move bytes out of the buffer and make space for the new
string. But wait, we have just disabled interrupts... See the problem?
This is the reason it is generally advised to never Serial.print()
inside an interrupt handler. The same applies to any critical section.

Edit: As Juraj points out in a comment, the HardwareSerial code
now implements a workaround against this problem: if it
detects it has to wait with interrupts disabled, it takes care of
calling the interrupt handler itself. This is a (relatively) late
addition to the HardwareSerial code. Their authors presumably
witnessed too many beginners doing debug prints from interrupt handlers
and being bitten by this issue. Note that it is a workaround, not a
solution: it will often make the critical section last for an
unreasonably long time.

I wouldn't rely on similar APIs, or even on other cores, systematically
implementing this kind of safeguards though: some library authors just
trust the user to not do silly things.


Can I power arduino uno R3 with 9v battery through Vin? I want to power up arduino through Vin port , what should be the input voltage ?

About 7.5V to 9V is best. A 9V battery is often not capable to supply enough current for an Arduino. Do you have a multimeter to measure the battery voltage drop when the Arduino is connected ?


how do you capture the top value in a fallen edge in analogs data (flex sensor) Guys i'm working with a flex sensor and I'm trying to capture a specific value which is the moment before the user lets go of a flexed flex sensor and its represented as the top point of a falling edge as sub picture A in the picture I included. using an array I tried two methods, which can produce a close value at times but at other it will give me wrong values
first I tried the following logic, whenever I detect a value below a certain threshold it indicates that a fallen edge has occurred so get me the value that came right before it as shown in sub picture C but depending on the delay this can be quite unpredictable.

the second method is to store the maximum value of but this returns the peak and it's not always the top of the fallen edge as shown in subpicture B

what do you guys suggest to capture those values?
this is my code so far

bool loaded = false;
int threshold = 760;
int index = 0 ;
int _max=0;
int values[4];
int values_size = 4;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int data = analogRead(A0);

  if (loaded) {
    values[index] = data;
    if(data>_max){
      _max=data;
      }

    if (data < threshold) {
      loaded = false;
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      _max=0;
      delay(300);
    }
    index++;
    index %= values_size;
  }
  else if ( data > threshold && !loaded) {

    loaded = true;
  }

  delay(20);

}

I suggest you consider as “top value of the falling edge” the maximum of
the values you have read during a specified time window before the edge
is detected. This means you have to compute the maximum at the time you
detect the edge. If you instead continuously compute a running maximum,
then you are going to get a global maximum. Amended source:

bool loaded = false;
int threshold = 760;
int index = 0 ;
const int values_size = 4;  // this controls the time window
int values[values_size];

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

void loop() {
  int data = analogRead(A0);

  if (loaded) {
    // Store the reading.
    values[index] = data;
    index = (index + 1) % values_size;

    // Detect falling edge.
    if (data < threshold) {
      loaded = false;

      // Find the max.
      int _max = 0;
      for (int i = 0; i < values_size; i++) {
        if (values[i] > _max) _max = values[i];
        values[i] = 0;  // clear, for next time
      }

      // Report it.
      Serial.flush();
      Serial.print('a');
      Serial.print(',');
      Serial.print(_max);
      Serial.println();
      delay(300);
    }
  }

  // Detect rising edge.
  else if (!loaded && data > threshold) {
    loaded = true;
  }
  delay(20);
}

Notice the line values[i] = 0;. It is intended to avoid the reading of
one falling edge being seen on the next one.


Counting revolutions of a DC motor with a Photo Interrupter I have a DC motor which is rated at 11 200 RPM.

I would like to count the actual RPM (it seems to be maybe 1500 RPM from what I can tell manually.)

I bought a Photo Interrupter, and have connected it to pin A0. When the beam of the Photo Interrupter is broken, the reading drops to zero.

All seems to work well when using a delay of 100, but as soon as I drop the delay to less than about 50, I get multiple reads.

This is my code:

int must_print = 1;
int sensorValue = 0;

//the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  sensorValue = analogRead(A0);

  if (sensorValue > 0)
    {
      if (must_print == 1)
      {
        must_print = 2;
        Serial.println(sensorValue);
      }
    }

  if (sensorValue == 0) {
    must_print = 1;
  }

  delay(100);        // delay in between reads for stability
}

At delay(100) the Serial Monitor looks like this for a single interrupt of 10 seconds:

354

At delay(50) the Serial Monitor looks like this for a single interrupt of 10 seconds:

298
312
328
336
349
360
366
371

Thanks!

You shouldn't use an analog pin with a photointerruptor.  The photointerruptor is a digital device.  Connect it to, preferably, an interrupt pin and use an interrupt to count your revolutions at high speed.


Working with Seed BLE Shield and Adafruit Feather BLE Long story short: I need to pair these devices:

Arduino UNO with Seeed BLE Shield
Adafruit Feather 32u4 Bluefruit LE.

The Seeed shield is configured and able to connect and communicate via the UART to an Android phone by HM BLE Terminal app from Google Play Store.

I can also connect the phone and Feather. The two independent connections work really well but a problem occurs when connecting the Seeed shield with Feather. Connection isn't troubling No errors are reported but I can't send/receive any data via the serial monitor (I'm using bleuart_cmdmode or bleuart_datamode from the Adafruit examples).

Basically my question is how to make them work: HM-11 module with BLE and the Adafruit board (nRF51822 chipset from Nordic).

Although the nRF51822 supports Central (master) mode, the Adafruit Feather's firmware only support's Peripheral (slave) mode.

  The Bluefruit LE firmware from Adafruit is currently peripheral only,
  and doesn't run in Central mode, which would cause the module to
  behave similar to your mobile phone or BLE enabled laptop.

  At some point we might consider a new firmware image offering this,
  but since 98% of the uses cases for BLE involved running as a
  peripheral we've concentrated all of our development effort there for
  now.

  https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/faq#faq-2

The HM-11 on your Seeed shield is capable of Central (master) mode though. This means your Uno will play the part that your Android phone was playing when you connected the Feather to the terminal app.

To set your HM-11 to Central mode, run the following AT command.

AT+ROLE1

Example code for the HM-11

Alternatively, you could burn the S120 Soft Device and your own custom firmware onto the Feather's nRF51822. You can find all the docs, tools, and Soft Device images on Nordic's website.


Using Arduino for Industrial process I was wondering if the Arduino is applicable for Industrial monitoring, I want to make a real time status of the presses in our company. I haven't seen or read much about people using Arduino at an Industrial level, most of what I have seen or read are prototype projects.
I'm new in electronics and don't know if there is a better way of doing this rather than using Arduino. I was thinking of using Arduino Uno and Arduino Ethernet Shield or Wifi Shield.

Any help on some information on how to start on this is helpful.

I don't see any reason not to use Arduino in an industrial, engineering, or laboratory environment, if it meets your needs and does the job well. It is highly recommended, however, that you provide some sort of pin protection to keep industrial noise or voltage spikes from frying pins. Minimum pin protection could consist of using current-limiting resistors (or better yet, the other, more robust techniques shown here) on pins used for output and input signals. Optical isolation is also a good option, especially if potentially dangerous voltages are being used. Lastly, after you prototype and test your Arduino setup you should solder the wires to the Arduino and provide a protective case. You don't want to accidentally fry the Arduino or a pin via accidental static discharge (hence the case, and pin protection above), and you don't want jumper wires vibrating loose and connections slowly oxidizing over time and loosing electrical connectivity in any type of industrial or laboratory application that is expected to be used regularly (hence replacing your jumper wires with soldered wires). Shields, however, are prob. ok for low-humidity and room-temperature environments, as they are generally much more secure and solidly connected than individual jumper wires.

Note that you can solder wires to any Arduino, even the Uno, Leonardo, or Mega, for example, simply by soldering to the exposed portions of the pins on the bottom of the board. You can also cut off and desolder the female headers and either solder directly to the holes, or solder on male headers that you then solder to other PCBs. I especially like the Arduino Nano, Pro Mini, and Micro since they are small, have exposed holes or male pin headers, and can easily be soldered onto a professionally-manufactured circuit board or cheap protoboard, for better mounting in a final application. Keep reading below for more details on this.

I am an aerospace research engineer and use Arduino in my line of work regularly to solve problems. Here are some examples of current applications in use today, that I implemented, that are based on and using Arduino boards:

sensorless brushless motor RPM sensor, motor commander, and data acquisition device for bench-top testing
linear actuator closed-loop controller (linear stepping resolution is 0.01mm [10um], full moving range is 0 to 15mm); the Arduino commands the actuator driver board via a custom PWM signal using the Timer1 library (http://playground.arduino.cc/code/timer1); position is read via a custom quadrature encoder reader algorithm on the arduino; the actuator is used for very precise aiming of certain instruments; the $30 Arduino is taking the place of a $500 board that the actuator manufacturer makes, and the Arduino gives us much more functionality than the $500 board would give us. The Arduino and actuator will be used to precisely aim a laser for experiments in a wind tunnel.
flight controller interfaces between MATLAB and off-the-shelf Radio Control transmitter (read and write RC PWM & PPM communication signals)
Professional film studio communication interface on robotic, drivable camera system (info sheet & video).

Those are just a few cases. If it works, do it.  Once you prototype with a solderless breadboard, however, it is recommended that you at least hand-solder the final configuration to a permanent prototyping board, to make it more durable and noise-resistant (ie--primarily: so that it will have solid connections that can't corrode, break, come apart, or vibrate free easily).

Here's a soldering article I wrote (http://electricrcaircraftguy.blogspot.com/2014/08/recommended-soldering-kit.html#.VP-JCPzF-So). see the links at the bottom for recommended soldering tutorials. The one about how to make "solder tracks" was especially useful to me once I got past the breadboard stage and started prototyping things on double-sided perf board.

Here are some double-sided prototyping boards (or "perf boards") to look into once you get to this stage: (Ebay search for "double sided pcb") http://www.ebay.com/sch/i.html?_from=R40&ghostText=&_sacat=0&_nkw=double+sided+pcb&rt=nc&LH_BIN=1 -- get the ones with all the little holes in them. You can put the whole thing in a plastic case if you want too. You can permanently solder an Arduino (esp. the Nanos or Micros more easily) to one of these perf boards.

Here's another example of double-sized perf board. (image source: http://www.elecfreaks.com/store/doublesided-protoboard-8cm-x-12cm-p-410.html)

Professional PCBs:

If you need to make more than a few of some device, hand-soldering wires and pieces all over a perfboard can get to be VERY tedious. In this case, you need to design a more professional PCB with custom traces and pads and layout and all for your project. If you don't have PCB-designing skills yet with a professional tool like Eagle or KiCad, you can use Fritzing (http://fritzing.org/home/) to design a PCB, and then send it off to a company like OshPark (https://oshpark.com/) for high-quality, reasonably-priced, low-quantity US-based manufacturing---or send it off to the Fritzing Fab lab in Germany for high-quality PCB manufacturing that supports the Fritzing project. Lastly, for a couple really inexpensive Chinese options, look at ITEAD Studio and Seeedstudio. Fritzing and any other PCB CAD software tool can output the necessary Gerber files for manufacturing.

Quick tip: when designing a PCB, don't use any 90 deg corners for your traces. They can act as antennas (sending or receiving) and cause electromagnetic (including radio) interference and noise. Use multiple 45 deg edges and corners instead.

Once you get your boards back, solder your Arduino to them, and solder any extra parts or hardware to them you need as well. Now you have quite a professional product, even if it has an Arduino soldered right to it.

Summary:

In summary, yes I think Arduino is great. Without it, I wouldn't know how to even blink an LED or load a single code to a microcontroller, because getting into using microcontrollers was just to enigmatic, difficult, and complicated for someone not professionally trained in it, such as an Aeronautical engineer like myself.  With Arduino, however, I learned to build up my skills and solve real-world problems in professional environments.

I am very grateful to Massimo Banzi, David A. Mellis, and others who have made Arduino possible. It has changed my life and my ability to be useful in this life.  My favorite part about it is that even though it is a tool meant to get the non-programmer or lay-person to do basic stuff like blink a light using poorly-written blocking code, it has opened up my world beyond what I ever imagined before, and it is a fully-capable microcontroller that doesn't permanently hide away the low-level stuff. The low-level AVR functions, registers, etc are ALL STILL THERE AND ACCESSIBLE once you get to a level where you need them!

Cheers,
Gabriel Staples

PS: To see many of the very helpful links which I've referenced as I've built up my Arduino and ATmega328 microcontroller skillset, please see this article here, esp. all of the links at the bottom: http://electricrcaircraftguy.blogspot.com/2014/01/the-power-of-arduino.html


Arduino Uno vs Arduino MKR1000 analogRead discrepancies I'm using an Arduino to control a BLDC motor connected with the motor driver. It is just a simple control which I'm using a PWM as a signal. Before this, I'm used Arduino Uno pin 5 to control BLDC motor, the analogue value starts from 80. Now, I'm changed to Arduino MKR1000 board with the same pin 5 to control BLDC motor. But, for MKR1000 to rotate the motor, analogue value start from 125. My question is, why two of this board using a different PWM value for rotating the BLDC motor.

The Adruino Uno is running off 5V, while the MKR1000 is 3.3V.  This means you need a bit more on-time to get the same power output.


How to control two devices with Arduino? I want to control two devices:

AC
Humidifier

I have a DHT11 sensor for temperature and humidity. I want the AC to turn on when the temperature is greater than 30°C, and off when it's less than 20°C. Same for the humidifier: on (humidity < 50 ) and off (humidity > 90 ).

It's not necessary for both to operate at the same time, i.e first check for AC then humidifier.

I want to do this task using a single Arduino Uno.

Connect both of your appliances i.e AC and Humidifier to 2 different relays. Connect the relays to the Arduino Uno digital I/O pin using a small current amplifier circuit or a Darlington Transistor pair that will amplify the current going to the relay.

Relay circuit

Darlington Pair

Now the connection of your sensor with arduino.

In your code you have to use DHT library i.e.

#include <dht11.h>

define your DHT11 object as

dht11 DHT11;    //(class object;)

define your DHT11 sensor pin like this

DHT11.read(dht_output_pin);

You can the similar code to control your relay according to the temperature and humidity here. Simply first check the AC temperature and switch on/off the AC relay and then check the Humidifier humidity and switch on/off the humidifier relay.

*** Connect your sensor output to the Digital Pin of the Arduino


Storing data from Arduino without Serial print- High Sample rate For my work, I need to acquire data at a high sample rate (>100kSa/sec) using Arduino Portenta H7, which has 3 X 16-bit ADCs. Portenta H7 has STM32H747XI microcontroller. I don't want to use Serial.print command as I came to know that this command takes much time to execute, which makes achieving the targeted sample rate impossible.  What are the other possible ways to store the data from Arduino while maintaining this high sample rate? For example, saving the data and then printing them all at once at the end of testing( 3-5 second testing period). e.g. using an SD card or through saving in Arduino internal memory? Can you suggest techniques employed for high-sample rate data acquisition from Arduino?

The Portenta has a beast of an  STM32H7 Cortex M7 and a minimum of 8M bytes of external SDRAM in addition to the 1M on-chip.
You need to capture 2channels x 2 bytes x 100K/s x 5s = 2M bytes of data, so storing it on the on-board RAM and spitting it out later seems like a viable and low-risk approach.
A slow serial link might take a few minutes to transmit 2M bytes of data, but you have various other options if that is objectionable.


AttachInterrupt in a library I'm having trouble adding attachInterrupt in a library that I am creating. I researched a lot, and I noticed that this is a common mistake, but do not quite understand the answers I found.

The error in question is this:

sketch_nov04a.ino: In function 'void setup()':
sketch_nov04a:10: error: argument of type 'void (Teste::)()' does not match 'void (*)()'

My library is as follows:

Teste.h

#ifndef TESTE_H
#define TESTE_H
#include <Arduino.h>

class Teste
{
public:
    volatile long lastWindIRQ;
    volatile byte windClicks;

  void wspeedIRQ();
};
#endif

Teste.cpp

#include "Teste.h"

void Teste::wspeedIRQ()
{
  if (millis() - this.lastWindIRQ > 10)
  {
    this.lastWindIRQ = millis();
    this.windClicks++;
  }
}

my implementation

#include <Teste.h>

Teste teste;

void setup()
{
  Serial.begin(9600);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);
  attachInterrupt(0, teste.wspeedIRQ, FALLING);
}

void loop()
{
  Serial.println(teste.windClicks);
  delay(3000);
}

EDIT: Updated the error and corrected the problem cited by Ignacio

The problem is that wspeedIRQ() is a member function (i.e. it's part of the Teste class), but attachInterrupt() expects a non-member function (i.e. a function which is static and/or not part of a class at all).

This is a very important distinction in C++ because it affects how the compiler calls the function behind-the-scenes. There is unfortunately no way to use a member function directly with attachInterrupt().

Various workarounds are possible though. The simplest is to write a wrapper function which calls the member function. For example:

Teste teste;

// This is a non-member function...
void isr()
{
    // ...which calls the member function:
    teste.wspeedIRQ();
}

void setup()
{
    //...

    // Setup interrupt to use a non-member function
    attachInterrupt(0, isr, FALLING);
}

As a side note, your implementation of wspeedIRQ() won't compile at the moment anyway. The reason is that this. is invalid. It's a pointer so the correct syntax is this->.

(In practice, you usually don't need to use this to access member data. C++ figures it out automatically, unless there's a naming conflict.)