What overheads and other considerations are there when using a struct vs a class? C on embedded systems has traditionally use structs to hold structured data.

Arduino brings C++ to the table, so we can use classes instead.

Lets say we have two different data structures which could be considered very similar:

typedef struct
{
    int valueOne;
    int valueTwo;
    int valueThree;
} value_t;

and:

class Value
{
    public:
        int valueOne;
        int valueTwo;
        int valueThree;
}

In terms of memory, what difference will this make?

I still see the struct technique being used heavily - why is this?

As taken from the accepted answer from When should you use a class vs a struct in C++?

  The only difference between a class and a struct in C++ is that
  structs have default public members and bases and classes have default
  private members and bases. Both classes and structs can have a mixture
  of public and private members, can use inheritance, and can have
  member functions.

  I would recommend using structs as plain-old-data structures without
  any class-like features, and using classes as aggregate data
  structures with private data and member functions.

Memory wise the access modifier makes no difference and given the memory constraints of the Arduino, people are less likely to use classes with complex hierarchies, but prefer the POD structs anyway.


Arduino stops logging data after ~32761 seconds I made a small set up to log temperature on SD card, everything is running smoothly until it reach 9:06:01 of logging that is  32761 seconds. I know that corresponds roughly to the maximum value of an integer. But I made all my variables unsigned long.
Here is the code in the loop and the if condition to log or not. The timer is computed with currentTime (unsigned long) and startTime (unsigned long). So even if logCount*freq are both integers, they should reach maximum value after 32761 seconds, then the if condition should always be true.

void loop() {
 String date;
 unsigned long timer;
 int freq = 60;

 sensors.requestTemperatures();
 tempC1 = printTemperature(insideThermometer, 18);
 tempC2 = printTemperature(outsideThermometer, 19);

 // start serial port
 Serial.begin(9600);

 mainMenuDraw();
 operateMainMenu();

 CurrentTime = millis();
 timer=(CurrentTime - StartTime)/1000;
 date = TimeShowFormatted(CurrentTime - StartTime);

 if (timer > logCount * freq and StopStatus == 0) {
  logCount += 1;
  LastLoggedDate=date;
  DataLogg(date);

 }
}

Instead of comparing absolute times you should use the following:

unsigned long now = millis();

if(now - time_last_log >= freq){
    logCount += 1;
    LastLoggedDate=date;
    DataLogg(date);
    time_last_log = now;
    // or if you really want fixed intervals
    // time_last_log += freq;
}

This is guaranteed to be overflow proof.


Arduino stopped working my arduino uno stopped working. It shuts off itself every time i plug it in. This golden thing is ovetheating.

Do i have to replace it or buy a new uno or what.

As Gerben has said, that "golden thing" is a resettable fuse (AKA polyfuse).

It's there to protect the USB port of your computer against excess current draw from a faulty board (which seems to be happening, by the way).

If nothing else is connected to the Arduino and the polyfuse keeps tripping, then the fault root cause is probably a short-circuit in the board. From here there are 2 possible scenarios:

Least likely: an external agent (metallic flakes, dirt, or something like that) might be causing the short-circuit. Inspect the board, clean it and electrically isolate it when plugging it again (avoid the solder joints getting in contact with a conductive surface, use a case or a mat).
More likely: a component has failed in short-circuit mode and is causing the excess current draw that trips the polyfuse. In that case you could try to debug the board (with at least a multimeter, and maybe other instruments) to locate the faulty component and replace it. That's not an easy task unless you precisely know what to do and where to look in the board. You might be better off buying a new board.

If you want to give the repair route a try, check this question. The schematic may be of some help to you. You might want to verify the integrity of the decoupling capacitor in first place.


How to use readLine from JSSC When I use JSSC and call serialPort.readLine(event.getEventValue()) from public void serialEvent(SerialPortEvent event) I've got fragments, not all string. What I must do to get all string from begin to "\r\n"? What I must do to get all string from my start marker (like "[start]") to my stop marker (like "[stop]")? What to modify in this code:

private static class PortReader implements SerialPortEventListener {
    public void serialEvent(SerialPortEvent event) {
        if(event.isRXCHAR() && event.getEventValue() > 0){
            try {
                String data = serialPort.readString(event.getEventValue());
                serialPort.writeByte((byte) 1);
            }
            catch (SerialPortException ex) {
                System.out.println(ex);
            }
        }
    }
}

The event gets fired when a single character is received, not the whole string. You have to build the string up until you get to \r\n and then process it. This is my code for a similar project. It uses a protocol where > signifies the start of a message and \r signifies the end. processMessage is a function to process the entire message and update GUI elements etc. It is invoked using runLater because the serialEvent function will be on a different thread to the GUI thread.

StringBuilder message = new StringBuilder();
Boolean receivingMessage = false;
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                if (b == '>') {
                    receivingMessage = true;
                    message.setLength(0);
                }
                else if (receivingMessage == true) {
                    if (b == '\r') {
                        receivingMessage = false;
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                    }
                    else {
                        message.append((char)b);
                    }
                }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

A simpler version for you might be the following. processMessage is called whenever a \r or \n is received and there are some bytes in the message.

StringBuilder message = new StringBuilder();
public void serialEvent(SerialPortEvent event) {
    if(event.isRXCHAR() && event.getEventValue() > 0){
        try {
            byte buffer[] = serialPort.readBytes();
            for (byte b: buffer) {
                    if ( (b == '\r' || b == '\n') && message.length() > 0) {
                        String toProcess = message.toString();
                        Platform.runLater(new Runnable() {
                            @Override public void run() {
                                processMessage(toProcess);
                           }
                        });
                        message.setLength(0);
                    }
                    else {
                        message.append((char)b);
                    }
            }
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
            System.out.println("serialEvent");
        }
    }
}

Edit:

Two things fixed:  1. Using StringBuilder instead of String to save making a lot objects every time the message is incremented. 2. Make a copy of the message string before passing to runLater otherwise when it does run it will use the up to date version of the string, which could have new characters, and thus cause problems.

Edt 2:
On Windows I found it needed if(event.isRXCHAR() && event.getEventValue() > 0) as the event would sometimes be fired with 0 bytes causing a null point exception in for (byte b: buffer)


A confusion with setting timers I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.

Here is the code I modified from the tutorial (I use Arduino's ATmega328P):

#include <avr/io.h>
#include <stdint.h>

int main (void)
{
    DDRB |= (1 << 0); // Set LED as output
    TCCR1B &= ~(1 << CS11); // Set up timer
    TCCR1B &= ~(1 << CS12); // Set up timer
    TCCR1B |= (1 << CS10); // Set up timer

    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}

I use the following formula:

  Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
  Frequency) - 1

So Target Timer Count = 0 in my case.

But I get 615kHz on scope.

My timer setting should output 16MHz since I use no prescaler:

What am I doing wrong?

If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.

The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.

If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.


Can someone help me figure out why my menu gets stuck? When I try to run my code so far with the menu and select buttons, it seems that it works, except that the main menu will not move past "Main Garden" to "Currants". There's also a problem with the submenu where after the first watering warning, pressing the select button makes it simply return to the main menu without lighting the LED on the LEDPower pin or running that watering routing for the whole watering interval.
The one guess I still haven't tried is that maybe I should change void MainMenu() to a Switch Case structure instead of If-Else?
.
edit:
.

Problem One (Menu not moving past Main Garden to Currants):
MainOld is used to increment MenuState but MainOld never gets incremented, which means it will never have a value greater than 0. Accordingly MenuState can
never be greater than 0 + 1.
Problem Two (Sub Menu looping back to main):
'Checking' the state of LEDPower like in Water1() is not the best way to accomplish what you want to accomplish. It may work but is not technically correct as LEDPower is a pin state and you never actually read the state.
The other issue in Water1 is that previousWaterMillis doesn't get updated anywhere in your code, which means that anytime Water1 is called more than 10 seconds after boot your solenoid will activate and then immediately deactivate. I would recommend a while loop inside your Water1 function. ex.
void Water1(){
  digitalWrite(Relay1, HIGH);
  unsigned long currentMillis = millis();
  previousWaterMillis = millis();
  int LEDPowerState = digitalRead(LEDPower);

  while(currentMillis - previousWaterMillis <= WateringInterval){
    digitalWrite(LEDPower, HIGH);
    Serial.println("Watering Garden with LED Lit");
    currentMillis = millis();
  }

  digitalWrite(Relay1, LOW);
  digitalWrite(LEDPower, LOW);
  SubMenuState = 0;
  SubMenuOld = 0;
}

^^ This will illuminate your LED and activate the solenoid for the 10 secs you wish to water.


Arduino Due with Atmel Studio 7 I was trying to switch to Atmel Studio for programming my Due project since it became more and more complex.
I managed to use the Arduino Importer Wizard to load a blink.ino file and included all the requested libraries more or less my hand that were marked as missing during compiling.
Now the compiling kind of works, but I still get this error:

Error       (inkerScript): No such file or directory    ECU arm-none-eabi-g++.exe   0

The (inkerScript): part is no typo. It is really like this in the console.
Taking a look in the Toolchain Options I have these settings (which I am not able to edit):

Going into the Miscellaneous Part of the Options I can edit these fields:

By editing the Linker Flags field, I can change the error message from (inkerScript): No such file or directory to e.g. HelloWorld: No such file or directory.

Is there anything wrong with my options? What is the correct setting for "Linker Flags" and what are they doing?

Unfortunately I am not a pro with C++ Compiling / Linker Errors / Settings.

Thanks.

I just encountered this.  After looking at other examples in the compiler command line options, it looks like it should be $(LinkerScript) instead of ($LinkerScript).

In Atmel Studio, go to project properties, toolchain, ARM/GNU Linker, Miscellaneous to find the option to change.


Receiver sleep mode RDA5807M Good afternoon guys!
I have a radio receiver connected to an arduino and I want it not to work all the time, but to turn on by the arduino timer for a certain time, and the rest of the time the receiver must be turned off by software.
I have a working sketch that allows you to tune this receiver, and it also allows you to re-tune the receiver (set the volume and frequency) by calling a function.
#include <Wire.h>

#define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
// registers
#define RDA5807M_REG_CONFIG 0x02
#define RDA5807M_REG_TUNING 0x03
#define RDA5807M_REG_VOLUME 0x05
// flags
#define RDA5807M_FLG_DHIZ 0x8000
#define RDA5807M_FLG_DMUTE 0x4000
#define RDA5807M_FLG_BASS 0x1000
#define RDA5807M_FLG_ENABLE word(0x0001)
#define RDA5807M_FLG_TUNE word(0x0010)
//masks
#define RDA5807M_CHAN_MASK 0xFFC0
#define RDA5807M_CHAN_SHIFT 6
#define RDA5807M_VOLUME_MASK word(0x000F)
#define RDA5807M_VOLUME_SHIFT 0
#define RDA5807M_RSSI_MASK 0xFE00
#define RDA5807M_RSSI_SHIFT 9

//uint8_t volume; // 0..15
//uint16_t freq = 1077; // 107.3FM
uint16_t reg02h, reg03h, reg05h, reg0Bh;

void setup() {
  Serial.begin(9600);
  Nastroika(1, 4, 1077); // Receiver setting: incl. or off (on, off), volume (0 ... 15), frequency MHz * 10 (107.7 = 1077)
}

void loop() {
  Nastroika(1, 4, 1077);
  delay(5000);
  Nastroika(0, 4, 1077); // Nastroika(0)
  delay(5000);
}

void setRegister(uint8_t reg, const uint16_t value) {
  Wire.beginTransmission(0x11);
  Wire.write(reg);
  Wire.write(highByte(value));
  Wire.write(lowByte(value));
  Wire.endTransmission(true);
}

uint16_t getRegister(uint8_t reg) {
  uint16_t result;
  Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(0x11, 2, true);
  result = (uint16_t)Wire.read() << 8;
  result |= Wire.read();
  return result;
}

void Nastroika(byte Key, uint8_t volume, uint16_t freq) // Receiver configuration after power failure
{
  Wire.begin();
  // Регистр 02h - inclusion, settings
  if (Key == 1)
  {
    reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
  }
  else if (Key == 0)
  {
    reg02h = reg02h & ~RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;

  }
  setRegister(RDA5807M_REG_CONFIG, reg02h);
  // Регистр 03h - radio station selection
  // After reset in register 03h, the default value is 0
  // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
  reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
  setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

  //Register 05h. Set the volume, do not change the rest of the beats
  reg05h = getRegister(RDA5807M_REG_VOLUME); // Reading the current value
  reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the bits VOLUME
  reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Setting a new volume
  setRegister(RDA5807M_REG_VOLUME, reg05h);
}

I need to modify this sketch and add the ability to wake up the receiver and put it into sleep mode. There is "RDA5807M_FLG_ENABLE" here. As I understand it, you need to change it?
Added later:
The method of turning off the receiver for a while, suggested in the comments, works.
However, for everything to be correct, when calling the function when the receiver is disconnected, we will send Nastroika(0, 4, 1077); that is, when turning off, we still specify the volume and frequency, although these parameters are superfluous here. It would be correct to write simply Nastroika(0); , But this cannot be done just like that, because there should be exactly three input arguments for the function, and not one.

Switch off:
reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

Switch on:
reg02h = reg02h | RDA5807M_FLG_ENABLE;
setRegister(RDA5807M_REG_CONFIG, reg02h);

EDIT: (to answer a comment of Антон)
Nastroika (настройка) means "tuning". Is that right? Then I would use this method only for tuning. Create two methods one for switching off and one for switching on.
void switchOff()
{
   reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

void switchOn()
{
   reg02h = reg02h | RDA5807M_FLG_ENABLE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
}

In the Nastroika Method you should only perform the tuning and let the module of. If you insist to switch on at the same time you could use your old version.
Example:
void Nastroika(uint8_t volume, uint16_t freq)
{
   // !!!!! This is the wrong place for Wire begin
   // move it to the setup method.
   // Wire.begin();
   reg02h = reg02h | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   // or if you insist / you want to keep the module be started here
   // reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
   setRegister(RDA5807M_REG_CONFIG, reg02h);
   reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT;
   setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

   reg05h = getRegister(RDA5807M_REG_VOLUME);
   reg05h &= ~RDA5807M_VOLUME_MASK;
   reg05h |= volume << RDA5807M_VOLUME_SHIFT;
   setRegister(RDA5807M_REG_VOLUME, reg05h);
}

Usage:
void setup()
{
   Serial.begin(9600);
   Wire.begin();
   Nastroika(4, 1077);
}

void loop()
{
  switchOff();
  delay(5000);
  switchOn();
  delay(5000);
}


Preventing relay switch-off crashing Ethernet controller I have an Arduino Uno with Ethernet Shield controlling some relays. Initially everything works fine but then when switching the relay off, the Ethernet controller frequently 'crashes'. Ethernet stops responding to pings, although the Arduino Uno keeps running. Pressing the reset button brings the Ethernet controller back to life.

I am using three relays to control:

The 'Call for Heat' contact on the boiler (normally connected to a thermostat)
A Honeywell V4043 zone valve (6W / 0.42A)
A Grundfos UPS2 underfloor heating pump (0.06A - 0.42A)

This is my setup:

I am using 2N7002 MOSFETs to drive the relays
I have 1N4004 diodes across the coils

There is a circuit diagram for the 'Relay Driver Shield' part of the circuit here:
https://github.com/njh/relay-driver-shield

This is what I have done to attempt to solve the problem:

I have moved the Arduino + Ethernet further away from the relays
I switched to higher quality Omron Relays (G2R-1-S-DC12)
I have tried both Wiznet W5100 and ENC28J60 Ethernet controllers

But so far nothing has solved the problem.

Of the three relays, it appears to be the Honeywell V4043 zone valve that is causing the problem. While testing with no loads connected to the relays, it was working fine. My assumption is that the problem is related to discharges across the contacts, partly due to the inductive loads. But I am not sure what to do to fix it.

Thanks,

nick.

I would suggest two things:

Use opto-isolators instead of (or as well as) the MOSFETs to control the relays, and
Add RC snubber circuits across the contacts.

The latter is the most important, since the spark across the contacts when they open will cause massive amounts of EMI.

The simplest circuit is a simple series resistor and capacitor placed across the contacts:

simulate this circuit – Schematic created using CircuitLab

Of course, ensure that the resistor and capacitor are rated for at least the voltage you are switching, preferably double.

Selecting the right values for the components depends very much on the load being switched and how much energy needs to be absorbed. I have shown ball-park figures that are usually "ok" for many situations.


Can Arduino post multiple sensor data to one Google Spreadsheet? Let's say I have one MQ5 gas sensor at home and one MQ135 gas sensor at the park. They are wirelessly hooked to Arduino.

My questions are:

Can Arduino post the data from two or more sensors to one Google Spreadsheet and organize it in two different charts?

Can only one Arduino accomplish this?

If not, what are the alternatives?

Not directly but with addon service like Pushingbox, temboo and so on it can.

If you google on your topic there are a ton of ways to do it!


Powering fans and arduino pro mini from single 12v supply So, I have a 5V Arduino Pro Mini, which is running the logic behind a multi-DHT22 sensor array, and using that input to control a 12v 24mm fan (12v, 0.16 A).

This is currently a working board on an Arduino Nano with two separate power supplies (1 to USB, 1 to fan). I want to simplify it and make a more permanent installation.

What I'm keen to do is something like the following:

Wall Wart (12v, 500mA) ------------------------> Relay -> Fan
                \ (1) -> Arduino Pro Mini @5V -> /

In order to power the Arduino efficiently at 5V, and avoid drawing power all the time (i.e. when the Arduino is asleep), is the best way to apply a Linear (or Switching) Regulator with minimal burn when idle at (1) in the diagram, and power the Pro via its VCC line, or is it better to just run via the internal regulators and RAW?

Will this actually just generate a high burn whenever the arduino is on to convert the 12v-5v? What is the most power efficient approach here?

If you want to minimize power usage, the best thing would be to start with devices that use more power! :D

It's time for math! I'm going to use the generic L7805CV 5V, 1A linear regulator. Poking in the datasheet, we find that the quiescent (standby) current is max of 6 mA. I'm assuming this power drawn is 12V, not 5V.

Since a linear regulator is basically a variable resistor, we can figure out that the efficiency is:

Vout / Vin

...thus, our efficiency in this application is...

5V / 12V = 0.416666667% efficiency

... Read more here.

So, we can use the inverse of the efficiency function (Vout / Vin → Vin / Vout) to establish the amount of power it'll use. Final equation:

Power Used (W) = (12V / 5V) * Current Draw + (0.006A * 12V)

...which simplifies to:

Power Used (W) = 2.4 * Current Draw + 0.072 W

So, all we need to find is the power consumption of the Arduino. This forum post states the power consumption of different sleep modes:

SLEEP_MODE_IDLE: 15 mA
SLEEP_MODE_ADC: 6.5 mA
SLEEP_MODE_PWR_SAVE: 1.62 mA
SLEEP_MODE_EXT_STANDBY: 1.62 mA
SLEEP_MODE_STANDBY : 0.84 mA
SLEEP_MODE_PWR_DOWN : 0.36 mA

Let's give the Arduino a generous 15mA to sleep:

Power Used (W) = 2.4 * 0.025 + 0.072 W = 0.132 W

So, 132 milliwatts, idle. A bit further, we can calculate that, if your wall wart has an efficiency of 10%, it will actually draw 1.32 W from your wall socket. Using a general cost per killawatt hour ($0.125), we can calculate that it will cost you about $1.45 a year for that Arduino to be ran in sleep mode 24/7 (given that we used the maximums for everything).

It's pretty cheap, so I wouldn't worry about that power. A good switching regulator will cost more than to run it for a few years with a linear regulator. I'd use the onboard one.

If you still want to optimize things, the wall wart or the fan should be looked at first. Consider getting a switching wall wart instead; this will give you a higher return on your investment since both the fan and the logic use this.


I want to play a sound based on my ultrason sensor reading The idea is to play the tone that is given by the center value read it by the center ultrasound sensor.

The code that is in Arduino is this one:

#include NewPing.h

#define PING_CENTER  2  // Arduino pin tied to both trigger and echo pins on the ultrasonic sensor.
#define PING_RIGHT  3
#define PING_LEFT  4
#define PING_MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
#define buzzerPin = 10

long buzzerFreq1; // The frequency to buzz the buzzer
unsigned int BUZZ_FREQ_MAX = 2500; // Maximum frequency for the buzzer
unsigned int US_MAX = 2023; // Maximum value for ultrason sensor
int c1;

NewPing sonar2(PING_CENTER, PING_CENTER, PING_MAX_DISTANCE); // NewPing setup of pin and maximum distance.
NewPing sonar3(PING_RIGHT, PING_RIGHT, PING_MAX_DISTANCE);
NewPing sonar4(PING_LEFT, PING_LEFT, PING_MAX_DISTANCE);

void setup() {
  Serial.begin(9600);
  pinMode(buzzerPin, OUTPUT); // set pin for buzzer output
}

void loop() {
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  buzz(buzzerPin,buzzerFreq1,10);
  // tone(buzzerPin, center);
  delay(500);  // Wait 500ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int center = sonar2.ping() / US_ROUNDTRIP_CM; // Send ping, get ping time in microseconds (uS) and convert it to centimeters (cm)
  unsigned int right = sonar3.ping() / US_ROUNDTRIP_CM;
  unsigned int left = sonar4.ping() / US_ROUNDTRIP_CM;
  // Serial.println("Distance: " + String(distanceInCms) + "cm");

  Serial.println(center);
  Serial.println(right);
  Serial.println(left);

}

 // buzz(buzzerPin, buzzerFreq1, 10);
 void buzz(int targetPin, long frequency, long length) {
 // int c1 = center;
  buzzerFreq1 = (center * BUZZ_FREQ_MAX) / US_MAX;
  long delayValue = 1000000/frequency/2;

  int numCycles = frequency * length/1000;

  for (int i=0; i < numCycles; i++){
    digitalWrite(targetPin,HIGH);
    delayMicroseconds(delayValue);
    digitalWrite(targetPin,LOW);
    delayMicroseconds(delayValue);
  }
}

And I receive the following error that I have no idea how to solve it.

ultrason_onewire_sound.cpp: In function ‘void setup()’:
ultrason_onewire_sound.cpp:26:11: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void loop()’:
ultrason_onewire_sound.cpp:38:8: error: expected primary-expression before ‘=’ token
ultrason_onewire_sound.cpp: In function ‘void buzz(int, long int, long int)’:
ultrason_onewire_sound.cpp:48:18: error: ‘center’ was not declared in this scope

#define buzzerPin = 10 shouldn't have an = in it.

With the = pinMode(buzzerPin, OUTPUT); will turn into pinMode(= 10, OUTPUT); by the pre-processor. Which would give the error, complaining about an = token, you got.


How can big Arduino programs be analyzed easily? I have an Arduino project code, but the problem is it has multiple functions and flow of control.

How could I convert this code into flowchart or control flow diagram?

Any software or online website?

Although there are programs who can automatically make some documentation (like doxygen), I haven't seen any software so far that can make USEFUL flowcharts or diagrams. The main reason is that such software does not know which are the important parts and which are not.

To do it manually:

Assuming your code contains multiple files, use an UML (Unified Modeling Language) application. Than if classes are used, you can easily port them to UML, otherwise assume each (.c) file is a 'class'.

By adding properties/fields and methods (functions) and drawing dependencies between the classes/files you get a good idea how everything works together.


I'm getting watchdog timer resets in NodeMCU. How can I permanently disable or stop that? I'm using NodeMCU for my project. At first it works fine, but after some days it is resetting frequently because of the watchdog timer. I have used the Esp.wdtfeed() method also. But it is not working. Can you please tell me what the problem exactly with or any solution? Here is my code:

void setup(void) {
  ESP.wdtDisable();
  ESP.wdtEnable(WDTO_8S);
  Serial.begin(9600);
  int n = WiFi.scanNetworks();
  Serial.println("");
  if (n == 0)
    Serial.println("no networks found");
  else {
    for(int i=0;i<n;i++) {
      if(WiFi.SSID(i)==ssid1) {
        WiFi.begin(ssid1,password1);
        ssid=ssid1;
      } else if(WiFi.SSID(i)==ssid2) {
        WiFi.begin(ssid2,password2);
        ssid=ssid2;
      } else if(WiFi.SSID(i)==ssid3) {
        WiFi.begin(ssid3,password3);
        ssid=ssid3;
      }
    }
  }
  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_16);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawStringMaxWidth(15,15, 128,"Display started");
  display.display();
  // Wait for connection
  display.clear();
  int j=0;
  while(j<10) {
    display.drawStringMaxWidth(15,15, 128,"connected to");
    display.drawStringMaxWidth(15,32, 128,ssid);
    display.display();
    display.clear();
    delay(1000);
    j++;
  }
  display.drawStringMaxWidth(15,32, 128,"");
  display.display();
  Serial.print("Connected to ");
  display.clear();
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (mdns.begin("esp8266WebForm", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("Connect to http://esp8266WebForm.local or http://");
  Serial.println(WiFi.localIP());
  server.on("/", getvalues);
  pinMode(buzzPin,OUTPUT);
  pinMode(but,INPUT);
}

void loop(void) {
  ESP.wdtFeed();
  if((WiFi.status()== WL_DISCONNECTED)||(WiFi.status()==WL_CONNECTION_LOST)) {
    display.drawStringMaxWidth(15,15, 128,"disconnected");
    display.display();
    int n = WiFi.scanNetworks();
    Serial.println("");
    if (n == 0)
      Serial.println("no networks found");
    else {
      for(int i=0;i<n;i++) {
        if(WiFi.SSID(i)==ssid1) {
          WiFi.begin(ssid1,password1);
          ssid=ssid1;
        } else if(WiFi.SSID(i)==ssid2) {
          WiFi.begin(ssid2,password2);
          ssid=ssid2;
        } else if(WiFi.SSID(i)==ssid3) {
          WiFi.begin(ssid3,password3);
          ssid=ssid3;
        }
      }
      int j=0;
      display.clear();
      while(j<10) {
        display.drawStringMaxWidth(15,15, 128,"connected to");
        display.drawStringMaxWidth(15,32, 128,ssid);
        display.display();
        display.clear();
        delay(1000);
        j++;
      }
      display.clear();
      display.drawStringMaxWidth(15,32, 128,"");
      display.display();
    }
  }
  getvalues();
  delay(20000);
}

here my way to find the bug first
1.comment out the watchdog from the code.
2.debug the code flow and find it get struck. Debugging in the sense put "Serial.print()" in between your code where you feel stuck but here don't disable your watchdog.


How can I copy and compare a string? I have the following code (I realise String isn't very efficient, but this sketch doesn't have to be)
debugOutput gets called every loop, but I only want to spam the serial bus (to debug) if the status changes.
However, it runs once, despite changes to the pins being made.
String prevState = "";
void debugOutput() {
  String s = "";
  //s = s + digitalRead(6) ? "1" : "0";
  //s = s + digitalRead(5) ? "1" : "0";
  s = s + digitalRead(4) ? "1" : "0";
  s = s + digitalRead(3) ? "1" : "0";
  s = s + digitalRead(2) ? "1" : "0";
  if(!prevState.equals(s)) {
    Serial.println("State Change: "+s);
    //strcpy(s, prevState);
    prevState = s;
  }
}

My suspicion is it was because of the pointers being the same, but I declare a new string every time this function runs. Just in case, I tried to swap this to strcpy, which isn't valid since I'm using String instead of character arrays.
What can I do, I'm really confused.
This is the Serial output, btw
State Change: 1 So it's clear to me that my string appending isn't even working as expected.

There is this thing called "operator precedence" that defines the hierarchy of operators.
The ?: will be calculated after the +. That's why
s = s + digitalRead(2) ? "1" : "0";

actually means
s = (s + digitalRead(2)) ? "1" : "0";

But you want
s = s + (digitalRead(2) ? "1" : "0");


Arduino NRF24L01+ arduino to netmf transmit issue I want to communicate between Arduino Mini Pro (china import) and a stm32f4 running netmf runtime. At the moment I'm able to communicate between SPI1 and SPI2 on the stm32 board.

After that I switched on the Arduino. I'm using the RF24 library and modified the GettingStarted sample to simply open pipes and send the same byte array again and again to the stm32.

It works for the first transmit but after that I did not receive any interrupts on the receiver side.

Both NRF24L01+ are power supplied by a breadboard power supply module which supplies 500ma (max USB bus). The Arduino is connected and power supplied by a CP2102 USB/Serial adapter.

NETMF Address: 0F0F0F0F0F
Arduino Address: 0F0F0F0F0E

As arduino uses little endian, I reverse the bytes on stm32 side before writing the address into the pipe. But I'm already unsure if I need that step (adding the Arduino address on netmf side).

Here's my Arduino code:

#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"

RF24 radio(9,10);

const int payload_size = 4;
const char payload[] = "PING";

void setup(void)
{

    Serial.begin(57600);
    printf_begin();
    radio.begin();
    radio.enableDynamicPayloads();
    radio.setChannel(77);
    radio.setAutoAck(true);
    radio.setRetries(15,15);
    radio.setDataRate(RF24_2MBPS);
    radio.openWritingPipe((uint64_t)0x0F0F0F0F0FLL);
    radio.openReadingPipe(1,(uint64_t)0x0F0F0F0F0ELL);
    radio.stopListening();
    radio.printDetails();
}

void loop(void)
{
    unsigned long time = millis();
    bool ok = radio.write( payload, payload_size );

    if (ok)
        printf("SUCCESS %lu...\n",time);
    else
        printf("fail %lu...\n",time);

    // Try again 1s later
    delay(1000);

}

Here's my NETmf code

NRF24L01Plus _module = new NRF24L01Plus();

public override void Init()
{
    _module.Initialize(SPI_Devices.SPI2, Pins.GPIO_PIN_D_8, Pins.GPIO_PIN_D_10, Pins.GPIO_PIN_B_12);
    _module.Configure(new byte[] { 0x0F, 0x0F, 0x0F, 0x0F, 0x0F }, 77, NRFDataRate.DR2Mbps);

    // both handlers are never executed
    _module.OnDataReceived += this.OnReceive;
    _module.OnInterrupt += _module2_OnInterrupt;

    _module.Enable();

}

I have a couple of projects that use the NRF24L01+ and the RF24 Library.

As I mentioned in my comment, the examples provided is not asynchronous. I am not sure if the library supports asynchronous operations. Nevertheless, in your example, one radio should be in transmit mode and the other receive. If you look at the examples, the author uses modes (role_ping_out and role_ping_back). Basicly, the author wrote the code so you can both send and receive. But you can't do send and receive at the same time.

If you look at the example cope in the library, you can see where you need to stop receiving and start sending:

radio.stopListening();

// Send the final one back.
printf("Sent response.\n\r");
radio.write( &got_time, sizeof(unsigned long) );

// Now, resume listening so we catch the next packets.
radio.startListening();

And on the other radio stop sending and start receiving:

radio.startListening();

// Wait here until we get a response, or timeout (250ms)
unsigned long started_waiting_at = __millis();
bool timeout = false;
while ( ! radio.available() && ! timeout ) {
__msleep(30); //add a small delay to let radio.available to check payload
  if (__millis() - started_waiting_at > 200 )
    timeout = true;
}

// Describe the results
if ( timeout )
{
  printf("Failed, response timed out.\n\r");
}
else
{
  // Grab the response, compare, and send to debugging spew
  unsigned long got_time;
  radio.read( &got_time, sizeof(unsigned long) );

  // Spew it
  printf("Got response %lu, round-trip delay: %lu\n\r",got_time,__millis()-got_time);
}

If this is a bit confusing, I would suggest you load the Getting Started example on both your radios. Once you get that working, you can get a better idea on how it works.

Good Luck


Serial - Send data to Arduino while Arduino sending data Arduino send data to PC each iteration. When I'm trying to send data to Arduino while receiving data from it, it takes too long. Serial.available() returns false even I sent data from PC. But if I add delay like 20-30 ms, problem fixed. Can't I use serial simultaneously?

PS: It's Arduino mega and I'm using http://www.teuniz.net/RS-232/ library for serial communication.

Example code:

void loop(){

  if(Serial.available())
    Serial.write("goodbye", 7);
    Serial.write("hello", 5);
  }

In this situation, it takes long time to write "goodbye" after I sent data to Arduino.

Following up on what Nick Gammon says, don't try to use the serial output to debug serial.  Perhaps try using the built-in LED instead; you can use an oscilloscope to find out how much time it is spending reading characters.

The following is how I've been reading a line at a time using non-blocking operations:

const int SERIAL_BUFFER_LENGTH = 100;

// The +1 assures we'll always have room for null termination
char g_serial_buffer[SERIAL_BUFFER_LENGTH+1];
int g_char_count;         // index into serial buffer

void setup() {
  Serial.begin(9600);  // or 115200 if your host supports it
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
  g_char_count = 0;
}

void loop() {
  while(Serial.available() > 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    char c = Serial.read();   // won't block because Serial.available() > 0
    if (c == '\n') {
      g_serial_buffer[g_char_count] = '\0';  // null terminate
      process_buffer(g_serial_buffer);
      g_char_count = 0;
    } else if (g_char_count < SERIAL_BUFFER_LENGTH) {
      g_serial_buffer[g_char_count++] = c;
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print(".");
}

// process_buffer: do whatever it is you intended to do with a
// line of received text...
void process_buffer(char *buffer) {
}


Can a 9V battery be used as a backup power supply (to Arduino Uno) while plugged directly into Vin and ground? Sorry if this has been asked before, but I've read tons of threads and it seems the answer is only implied on a couple of occasions.

I'm an electrical noob, but I understand that a 9v battery plugged into a wall wort with a diode would serve as a battery backup if the power was cut from the wall wort.  I also understand that Vin on an arduino already has a diode to do this.

I'm currently powering a temp/humidity that is dumping data into MySQL using a standard A-B USB cable and 5V DC USB power supply.  I'd like to incorporate a 9V battery plugged into Vin and ground, so that if DC power turns off, I can dump the data onto the SD card instead (since my MySQL server may or not be running during an outage).

My problem with that is that the other side of the diode on the Arduino is normally powered up. So for example if you have a 12V supply in the power jack you'll have 11.3V at Vin (because of the diode drop). Thus you are pumping 11.3V into your 9V battery which won't be designed to handle it. It will probably get hot and explode.

You would need another diode specifically between the battery and Vin. And make sure that Vin is at least 10V so that the normal mains power does not charge the battery.

Bear in mind a 9V battery doesn't have much capacity. With the power LED on,  taking sensor readings, and sending data via Ethernet (if that is what you are doing) you may have only bought yourself 15 minutes.

I have a post about a temperature and humidity sensor which runs all the time from 3 x AA batteries. I think the batteries need replacing about every two years. The data is written to an SD card which you remove and plug into your computer when you want to.

  when you have 9V hooked up to Vin and 5V coming in from the USB, it will use power from the 9V battery

Looks like I misread the question. @mwwalk is quite right. If you supply more than 6.6V through Vin then the circuitry switches the USB off. See here:

Vin is provided by the power jack (after a diode which drops it by 0.7V) - see blue ellipse. In any case (power jack or not) Vin goes through a voltage divider (two 10k resistors to the left of the red circle). This is compared to the output of the 3.3V voltage regulator. Therefore GATE_CMD is HIGH if Vin exceeds 6.6V. This turns off the MOSFET (green circle) and disconnects the USB power.


Could someone help me with an Arduino Uno program? I am thinking to do a gas leakage and fire detector using a GSM module in my home. I got all the contents like an Arduino Uno, MQ22 gas sensor, LM 35 heat sensor and GSM module SIM800L to send SMS and red and green LEDs.

About the program, I am thinking to make it like this: if there is a gas leak the GSM sends an SMS to my cellphone, whereas if there is a fire the GSM will send an SMS to the fire station.

About the LEDs, I want the green one to run when the state is stable, while the red one is on when there is a gas leak or fire.

Any help would be appreciated.

Mansor Its not clear from your post that this is just a simulated system, not a real system to save peoples lives and I think people wanted to point that out for you, because the parts you are listing hardly fall into the safety critical category.  Plus if you are asking this level of question the chances are you software won't be very safe either (no offence intended), after 30 years of writing software I'm not sure I could write code good enough to trust peoples lives with!

Find libraries for each of the sensors you have listed and get them working one by one.  Then start adding them one at a time to your setup and loop functions.
For the SIM800 you are going to need at least 3Amps, so look for a 5A(?) wall wart.  You will need to talk to it over serial, software Serial works most of the time I think (never tried it, just from what I have read on here).
LEDs should be easy, just get them the right way round and remember the resistors.  All you need is a Digital pin set to output and then send high and low to it. (Again do it as a separate program and then integrate it).

This is supposed to be a sight for solving problems, and unless you have some code and a circuit diagram showing your problem you can get a negative response.  So tonight get the first sensor running or post why it didn't work (and your code) and people will help.


Consequences of dynamically changing input/output configurations of digital pin? I am creating an IC checker for a large chunk of the 74ls series (basic TTL logic chips), which means that I have 14 pins running to the IC to verify its functionality. One pin is power (+5V) and another ground (GND), which are both consistently in the same seven and fourteen pin positions respectively, but the remaining 12 are various inputs and outputs that vary depending on the IC type.

With that stated, will there be any consequences to dynamically reconfiguring a pin from input to output -- or vice versa -- as different IC types are selected? Weird behavior or electrical failure? What if the IC remains plugged in while the the pins reconfigure? What if said IC is powered on and providing power to a pin as it reconfigures?

If you were curious, I am using a joystick and LCD display as an interface to selecting the appropriate IC to check.

There's no problem reconfiguring pins.  It happens all the time.  One example is with ping sensors where the pin is used as an  output to send the ping and then switched to an input to wait for the response.  The only caveat is that you must be sure what you're connected to.  For instance, if you set a pin to OUTPUT and LOW and it just happens to be connected to a HIGH OUTPUT then you just fried your board.


Understanding how methods and pointers inside a function work After this question i starteted going deep with the theory, and started studyng step-by-step with the "Beginning C, for Arduino "
Jack Purdum.

I finished to study the functions chapter, but i still have some doubts on the code, i hope this will be not a dumb question.

Why there is a Method "Print" not a Data Type inside the Function Argument List?

static void printImuData(Print &printer, int16_t Time0,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{
    printer.print(Time0); printer.print(",");
    printer.print(AcX);   printer.print(",");
    [...]
}

[...]

printImuData(dataFile, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);
if (Serial_plus_SD)
    printImuData(Serial, Time0, AcX, AcY, AcZ, GyX, GyY, GyZ);

I though the answer was "because you can pass data to a function by-value or by-reference" in fact the first input in the argument list is the left value (memory address) of a Method, but i am very confused.

Function arguments are used to pass data to the function that it may need to perform its task.

I tried to answer to the following questions to understand the code.

1. What task does this function perform?

The function will print some data on a Serial Monitor or SD Card

2. What data do i need to send to the function?

I need to send one Method through the left value of a pointer and 7 intergers.
I can't understand why a method.

3. What data do I get back from it?

Nothing because is a void, it will perform some task inside the function (print inside the object thas is pointed?) but nothing will return to the caller.

In the book  basic example is a function that returns the value 0 or 1 if is a Leap Year.

The function argument is an int and returns an int.

void loop()
{
    if (Serial.available() > 0) {
        int bufferCount;
        int year;
        char myData[MAXCHARS + 1]; // Save room for null
        bufferCount = ReadLine(myData);
        year = atoi(myData); // Convert to int
        Serial.print("Year: ");
        Serial.print(year);
        Serial.print(" is ");
        if (IsLeapYear(year) == 0) {
            Serial.print("not ");
        }
        Serial.println("a leap year");
}
}
/*****
Purpose: Determine if a given year is a leap year
Parameters:
int yr The year to test
Return value:
int 1 if the year is a leap year, 0 otherwise
*****/
    int IsLeapYear(int yr)
    {
    if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
        return 1; // It is a leap year
    } else {
        return 0; // not a leap year
    }
}
/*****
Purpose: Read data from serial port until a newline character is read ('\n')
Parameters:
char str[] character array that will be treated as a null-terminated string
Return value:
int the number of characters read for the string
CAUTION: This method will sit here forever if no input is read from the serial port
and no newline character is entered.
****/
int ReadLine(char str[])
    {
        char c;
        int index = 0;
        while (true) {
        if (Serial.available() > 0) {
        index = Serial.readBytesUntil('\n', str, MAXCHARS);
        str[index] = '\0'; // null termination character
        break;
        }
    }
    return index;
}

Like in my the last question, I have a civil engineer background and i am a self-taught, so is my first time with coding :)

Thank you for your patience.

"There are no stupid questions, just stupid answers"

  Why there is a Method "Print" not a Data Type inside the Function Argument List?

There is no "Method" Print in the argument list.  There is a reference (not a pointer which would be a * not a &) to an object called printer that is of type Print.  The code you have provided doesn't define Print but its a could guess that it is probably something to do with printing.  By supplying the printer argument you can print this data to anything that inherits from the Print base class, Serial is a good possibility, but you could write a class that derived from Print and wrote the data to an LED matrix, etc.
I can tell its not a Method, because you are calling the print method of printer, so it has to be either a class or structure.

  The function will print some data on a Serial Monitor or SD Card

I can see why you thought that but you are being too specific, it prints to anything that derives from Print, Serial and dataFile derive from it, but they might not be the only things.

  I need to send one Method through the left value of a pointer and 7 integers. I can't understand why a method.

An example might help:

class CGPrinter : public Print
{
  // Some code....
  virtual void print (const char* input) {// do something}
}

void loop()
{
  CGPrinter cgp;
  printImuData (Serial, 1,2,3,4,5,6,7);
  printImuData (cgp, 1,2,3,4,5,6,7);
}

Serial is an object, a variable, a specific instance of type of class that can print data.

CGPrinter is my new super sexy printing class that will read the characters that you 'print'.  To print the 7 integers to CG's printer class is exactly the same call as the one to write it to the Serial Monitor, because both classes derive from Print.

  What data do I get back from it?

Yes, correct on both points.

Does it make more sense now?  If not, just say and I'll try and clarify it.


Is DateTime from RTClib giving garbage dates/times? The RTC is working fine, but I'm having trouble with the DateTime class. Based on the following test, it seems like its math is wrong.

#include <RTRlib.h>
void loop()
{
    auto ts = TimeSpan(0, 8, 0, 0); // 8 hours
    auto zero = DateTime(0, 0, 0, 0, 0, 0);
    auto alarm = zero + ts;
    Serial.println(String("Zero date: ")+zero.year()+" "+zero.month()+" "+zero.day()+" "+ zero.hour()+":"+zero.minute()+" "+zero.second());
    Serial.println(String("Alarm as timespan: ")+ts.days()+"d "+ ts.hours()+":"+ts.minutes()+" "+ts.seconds());
    Serial.println(String("Alarm date: ")+alarm.year()+" "+alarm.month()+" "+alarm.day()+" "+ alarm.hour()+":"+alarm.minute()+" "+alarm.second());
}

My output is (repeating):

Zero date: 2000 0 0 0:0 0
Alarm as timespan: 0d 8:0 0
Alarm date: 2043 4 30 1:31 44

Also, when creating DateTime(0), I would expect the hours, minutes, and seconds to be zero. That's not the case. What's up with this library, and how did it get to be so popular if it doesn't work?

You are experiencing the consequences of code that doesn't do sanity checking. The library allows for dates that do not make sense (in addition to giving us all a new reverse-Y2K bug of assuming only dates later than year 2000.

When you create DateTime(0, 0, 0, 0, 0, 0);, you are saying to use Month 0 and Day 0. Those have no meaning in date calculations, which always assume that the first month is 1 and the first day is 1.

The rest of the library's code assumes valid dates, so when you give it invalid dates, unexpected behavior is to be expected!

Of you only modify your zero assignment to DateTime(0, 1, 1, 0, 0, 0); you will see behavior that is more expected.


String to persistent memory (EEPROM?) I am creating a server node that I want to be able to save the wifi SSID and the password into persistent memory so that when it starts ups it can connect to the network. I have looked for several hours and found just a few bits of information. One bit I found here http://playground.arduino.cc/Code/EEPROMWriteAnything

#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value) {
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value) {
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

This code will not store String values to the EEPROM. So as I thought I would ask for advice from the Stack Exchange geniuses.

Thanks!

EEPROM library has two functions put and get , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.

Here is a sample code to get you going.

int address = 10;
char arrayToStore[20];                    // Must be greater than the length of string.
String testString = "hello there";

testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

EEPROM.put(address, arrayToStore);                 // To store data
EEPROM.get(address, arrayToStore);                 // To read data


Did I fry a Sainsmart 1602LCD (not shield, just LCD), HD44780 compatible Each new circuit I build, I seem to make every possible mistake, including inverting 5V and ground.
I did that precise mistake on this 2x16 Sainsmart LCD. The backlight definitely works, but is the only thing I seem to be able to make work. Do you believe I fried the screen, or do they maybe have a diode to protect from erroneous cabling, and my mistake is another one?

EDIT :

I found this somewhere, on a board that might be the one driving this LCD screen or not :

Operating Voltage VDD -0.3 to +7.0 V
Driver Supply Voltage VLCD VDD - 10 to VDD + 0.3

So I mistakenly put 5V in VLCD, and 0V in VDD, which makes VLCD 5V and not 0.3V above VDD, would you suppose I fried it?

Thanks for your input :)

For me, it's extremely hard to tell if you did or did not fry a device.
Even if you have the device right in front of you, it's often hard to tell.

You've got two options:

Attempt to diagnose it

First you should try to run example code and follow the "instructions". I believe this product is relatively well documented (/libraried?) and shouldn't be all too hard to set up.

If this isn't working, it's likely the device is dead (given the situation). You could go on and fiddle around with it for hours, which might not be worth the effort.

Buy a new one

This will cost you some money. But if you get the new one working, you can test the same code on your old one.

Tips

First connect the wires, check the wiring and AFTER THAT connect the power. (Especially take care on GND/VCC wiring.)
Use black wires for GND/ground and red wires for VCC/5V.(It'll be easier to manage/spot)
Check the devices datasheets (which pins, what maximal voltage)
Try to use female connectors as power-output. (They don't short everything they touch)
Try to use irreversible connectors.
Don't have loose leads dangling around.
Put a casing/backplate on your Arduino (and/or avoid placing it on metal)
Keep your desk clean, bits of solder, wire, leads or screws may cause shorts between pins.


Sending data via bluetooth I am trying to both send and receive data using bluetooth module.

Receiving data works fine with this code:

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

void loop() {
    if (Serial1.available()) {
        Serial.println(Serial1.read());
    }

    delay(20);
}

But I cannot send any data. This is what I am doing:

void loop() {
    if (Serial1.available()) {
       Serial.println(Serial1.read());
    }

    delay(20);

    if (digitalRead(bluetoothInput) == HIGH) {
        Serial1.write("2");
        // only "send" prints. Nothing in android terminal
        Serial.println("send!");
        delay(1000);
    }

    delay(20);
}

What am I doing wrong?

I am using Arduino Leonardo and Bluetooth terminal app on Android device.

I've found the problem

It should be:

Serial1.println("2");

instead of:

Serial1.write("2");


Specific values not showing when using a numeric keypad I have attached a 3x4 keypad to my Arduino Leonardo as an input method. Whenever I press the buttons, the majority of the keys work but specific ones don't. Here's my code, I've set it up to beep a piezo buzzer when it gets a keypress.

#include <Keypad.h>

int buzzerPin = 0;
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {12, 13, 8, 10}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {11, 7, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

void setup(){
    Serial.begin(9600);
    pinMode(buzzerPin, OUTPUT); //Set buzzerPin as output
    keypad.addEventListener(keypadEvent); //Add an event listener for the KeyPad
}

void loop(){
    char key = keypad.getKey();
}

void keypadEvent(KeypadEvent eKey) {
        // When the KeyPad will be pressed, the results will appear on the serial monitor.
        switch (keypad.getState()) {
        case PRESSED:
                Serial.print("Enter: ");
                Serial.println(eKey);
                beep(10);
                delay(10);
                break;
        }
}

void beep(unsigned char delayms) { //creating function
    tone(buzzerPin, 2000); //Setting pin to high
    delay(delayms); //Delaying
    noTone(buzzerPin); //Setting pin to LOW
    delay(delayms); //Delaying
}

I based my rows/columns off of this pin-out: https://www.jaycar.com.au/12-key-numeric-keypad/p/SP0770,
but I later found out some of the columns had to be swapped :P

Here's a diagram of what's happening:

The keys in red do not work.

I wouldn't have posted this on stack exchange but it looks like an oddly specific pattern, and no matter what I changed, it didn't work.

(And yes, that is the exact keypad I bought from Jaycar)

Edit: I forgot to mention that I was using a prototype shield to plug the keypad into, but all pins are confirmed working on that.

A row against a row does not work, or a column against a colum.
That means there is a logical explanation. Row #2 is swapped with column #2.
Button 5 does work, because that still has a row against a column (but then the other way around).


LED Cube lighting wrong LEDs randomly So I built my First LED Cube and the thing turns ON!!! Pretty happy about that but here is my problem.

When I try and get the Cube to display say a basic "outline" (a wire form of a cube only the outer most LEDs are on)

The shift registers, that I have daisy chained together, give the correct display 80% of the time, but the other 20% give completely wrong LEDs lighting up.

I have used 4 74HC595 shift registers linked together so I am only using 3 of my Arduino ports to control the 5*5*5 Cube.
The basic shape is there but the ones that are not meant to be lighting up cause a lot of flickering (or ghosting?) in the center of the cube.

I have thought about using pull up or pull down resistors but I find that, when I run my program at a slower rate, the LEDs that are lighting wrongly are lighting up controlled so I think it has to be something with my code or setup.

Has anyone got any experience with LED cubes doing this?

Also I am only using the output enable and disable to make use the wrong this is not displayed when I am shifting the data out, should I be using the clear?

One last thing, does anyone have recommendations for the delay time to let each layer shine for?

My code is below

int clockPin = 8;
int dataPin = 7;
int set = 6;

void setup()
{
  //set pins to output so you can control the shift register
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(set,OUTPUT);
}

void loop()
{
      digitalWrite(set,HIGH); // DISABLES OUTPUT
  // level 1 ( top )
      shiftOut(dataPin, clockPin, MSBFIRST, B00000011);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

       digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 2
      shiftOut(dataPin, clockPin, MSBFIRST, B00000101);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);  // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 3
      shiftOut(dataPin, clockPin, MSBFIRST, B00001001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 4
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B00010000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00000000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00010001);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);

      digitalWrite(set,HIGH); // DISABLES OUTPUT
 // level 5 ( bottom )
      shiftOut(dataPin, clockPin, MSBFIRST, B00100001);//from left 3rd to the 7th = levels 5-1,, The right first LED
      shiftOut(dataPin, clockPin, MSBFIRST, B11111000);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B11000110);// Makes the " wire cube "
      shiftOut(dataPin, clockPin, MSBFIRST, B00111111);// Makes the " wire cube "
      digitalWrite(set,LOW);   // enables output
      delay(2);
}

Any help would be appreciated

Thanks

A simple way to test for short between LEDs is to write a loop that lights one of them at a time, one right after the other, for 50ms or so. It's relatively easy to notice two lighting together (a short) or a missing blink in the sequence (an open - and assuming you can see all the LEDs at once).


How is the integration time set for a camera? I using the TSL1401R-LF Linescan Camera Module, which reads in a 1 X 128 line of pixels, and I'm having trouble understanding how the integration time is set for this device.

I understand from page 9 that the minimum integration time is a constent that results from a function of the clock speed, but I don't fully understand when this integration period takes place.

According to the timing waveform (Figure 1 on Page 5) the integration period appears to be set after the first 18 clock cycles. Does this mean that the integration period is set while the camera is outputting pixels?

How is that even possible? Also does this mean that in order to achive the minimum delay time I would have to take that time and divide it across those remaining 110 clock cycles (i.e. 307 ns for a total of 33.75 us)?

UPDATE:

This is how I am currently programming the camera. I'm using delayMicrosecond() after the HIGH and LOW clock impulses as well as at the end. I have enough delays to achieve the minimum 33.75 microsecond delay, but I'm still having sensitivity problems.

int delayTime = 20;

void readPixels()
{
  digitalWriteFast(SI, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(SI, LOW);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  for(int i = 0; i < 128; i++)
  {
    digitalWriteFast(CLK, HIGH);
    pixelsArray1[i]=analogRead(Cam1Aout);
    pixelsArray2[i]=analogRead(Cam2Aout);
    pixelsArray3[i]=analogRead(Cam3Aout);
    delayMicroseconds(delayTime);
    digitalWriteFast(CLK, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  delayMicroseconds(20);

}

It is quite a difficult system to get your head around, as you have noticed.  I'll try and break it down more logically for you...

An important thing to note is that there are two capacitors in each pixel - the integrating capacitor and the sampling capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the integrating capacitor. Simultaneously that stored voltage level is mirrored in the sampling capacitor.

When you send the pulse on SI a signal called HOLD is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2.  At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.

Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.

So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading this set of clock's integration, but the last set of clocks integration.

So you have:

SI pulse - HOLD generated, samples frozen
18 clocks of clearing the integrators and reading nothing much.
110 clocks of reading nothing much (nothing is sampled yet) and integrating.
1 clock to terminate
SI pulse - HOLD generated, samples frozen
10 clocks of clearing the integrators and reading the previously integrated samples 1-18
110 clocks of reading the previously integrated samples 19-128 and integrating new ones
1 clock to terminate
... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.

The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.


Increasing range of a DC-offset signal (software) I am trying to read a signal with a DC offset of 511 (as seen by the ADC). The signal's tiny with regards to the offset, and I'm feeding it to a library that does a Fourier transform on it. It comes from a 3.5mm audio jack with AC coupling and the offset so I can see the full signal.

How may I increase the range of the signal? I am thinking something like the input signal is (490-530) and I want an output of (400-630) or something (numbers solely for example). The issue is that I still need the resulting signal to be centered around 511 AND I don't know the exact amplitude of the input (since it varies based on volume and particular audio going in at the moment).

I can assume that the volume of the audio input is relatively fixed (I need to be able to adjust this gain later, but I'm assuming the volume will be constant at some value per time I'm running the project), so I don't need envelope-following or something, but I'm not sure how to do this even so.

You can't magic more resolution out of thin air (well, you can, but it slows down your sampling - you would "oversample" and average a number of sequential samples).

Instead you need to boost your signal before it gets to the ADC using an op-amp.  The simplest circuit (which also inverts the signal, but you don't really care about that I suspect) is:

simulate this circuit – Schematic created using CircuitLab

That circuit will both invert the signal (if you care, just do a little bit of maths in your program to flip the signal, but for FFT you don't really care) and double the amplitude around the mid-point. The doubling is controlled by the ratio of R1 to R2 (20000:10000 = 2:1 = doubled). The mid-point offset is created by R3/R4 - you don't need to manually add your own offset.


How to sleep a whole circuit? I have just completed my first project, a clone of the Simon game of the eighties. The main parts of the circuit are an ATMega328, a 1602 2x16 LCD, and a small joystick.
It is powered directly from 3x1.5V batteries with solder bridges connecting all power pins on each part directly to the batteries. Therefore, if I sleep the ATMega, it won't change a thing comsumption-wise, as the LCD will still be powered.

What are (my first project, I am very unknowledgeable) the possible strategies to sleep the whole circuit?

I thought of using an ATMega pin as a positive lead for the joystick and LCD. Is that feasible?

Another strategy would be to interface some component (a relay?) between the battery and LCD, and command that component from an ATMega pin. Does someone know the right part for the job (I have a 220V relay in my parts, but it seems overkill)?

Lastly, even though it seems unlikely, is there a possible strategy without using any ATMega pins, as I currently use every single one (4 buttons, 4 leds, joystick x, y, and button, 1 buzzer, and 6 pins for the LCD, for a total of 18) except Rx and Tx?

The first and most smart solution is to use a switch between the batteries and everything else. This way, you slide the switch in the off position and the whole circuit is completely detached from the batteries: power consumption: 0.

If you can't (because, for instance, you want it to automatically power off after a while) you can use a transistor (PMOS, for instance) instead of the switch. you have then to put a complementary transistor (NMOS) on its gate, then a button in parallel to it. Just another passve component is required: a resistor (value e.g. can be 100k). When you press the button, the circuits becomes momentarily powered on. You will have to pull the nmos gate to a logic 1 with the atmega to keep the circuit powered. When you want to turn everything off, pull the pin to a logic 0 and your circuit will immediately shut down.

If, third solution, you want to give the atmega complete control over the powering, it needs to be always on. You can then omit the complementary transistor and use a reverse logic on the pin (so 0 = on, 1 = off) and then you can do whatever you want with the power (turn on and off whenever you want).
edit: as a comment suggests, it can be better to put a resistor to set the appropriate voltage on the gate at power up. Even if the commenter told to put a pull-down, I suggest you to put a pull-up (pull-down = normally on, pull-up = normally off). edit 2 as Paul suggested, there could be cases in which you need to be able to turn on and off automatically the circuit, and then store it for longer times without consuming battery. In this case it could be a good idea to put something (a mechanical switch, a jumper, a detachable wire) to completely detach the battery even from the arduino (even if, in this case, you can just remove the batteries from the housing).

Here is a small paint-made sketch to show the solutions. If you have any questions just ask ;)

EDIT: If you want to let the atmega control the power, you'll have to give him a way to do so. Which means.. You should use a pin. If you want you can use safely the RX and TX pins, as long as you don't enable the serial interface. If you need more pins, you can try to optimize your pins usage (for instance using a 4:1 multiplexer for the buttons you will have 2 control pins and 1 input, for a total of 3 pins, instead of 4), even if I think that the best solution is to use a port expander. for instance in the past I used the MCP23017, which has a I2C interface, or the MCP23S17, with a SPI interface. You will have to use the serial interface you choose (I2C: 2 pins - SCL and SDA, SPI: 4 pins - MISO, MOSI, SCK, SS, but they are the same pins used for programming), and then you will have 16 more pins for your uC

EDIT BY foivaras:

The same result can be achieved utilizing an NMOS instead of a PMOS.This would have an advantage over PMOS solution if power line was >5v and arduino was powered by a dc to dc converter. On this scenario, PMOS solution would need one more transistor to work.
Notice that the NMOS has to be placed on the low side of the power line and it will cutoff the power to joystick and lcd with 0v  and enable the power with 5v on its gate.(See 4th image)

COMMENT BY fra87

This solution is not a valid alternative in my opinion. Usually interrupting ground is a bad idea, because usually the rest position of the I/O pins is ground: if you interrupt the ground for the LCD, for instance, you will have +5V on the VCC pin, and a floating ground, but you will have 0V on all the I/O pins, possibly damaging the internal circuits. Moreover having a floating ground is bad in terms of noise protection.

The only advantage COULD be in the particular case explained by the editor, which is a DC/DC converter powering the arduino but not the LCD and the Joystick. This is a strange setup, though, and the proposed solution is better at a first glance (requires one less transistor), but is wrong. For instance, let's suppose the joystick is powered at 12V. If you detach the ground, the joystick will "shut down", which means that all its pins will float up to 12V. This means that on the arduino pin you will see 12V: you can damage it.

So, in the end, I discourage this solution. The only case when you can need it is when you are in a hurry and do not have any feasable PMOS: even in this case, however, I suggest you to replace the NMOS with a PMOS as soon as possible.

Just one more note: edits to the posts, in my opinion, should be done to improve the quality of the answer, by better formatting the content, removing orthographic errors and so on. If someone needs to add some comments or other solutions, it's better to use the comments or add another answer to the thread


Digital Input using a button doesn't work properly when using it to control a relay I'm trying to control a relay both via Bluetooth and using a switch. The problem is that, when the LED is off, I can turn it on with the switch but then if I turn off the switch the relay will stay on. Is there something wrong with my code? Thanks in advance. The switch is installed as follows:

Here is my code: Switch is connected to pin 3 and the relay is connected to pin 2.

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 0; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 if (state == '0'&& valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 else
 if (state == '1' || valor== HIGH) {
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
 }

}

New code:

//bluetooth hc-06
int ledPin = 2; // usamos un pin de salida al LED
int state = 1; // Variable lectrura serial
int interruptor=3;

void setup() {
    pinMode(ledPin, OUTPUT);   //Declara pin de Salida
    pinMode(interruptor, INPUT);
    digitalWrite(ledPin, LOW); //Normalmente Apagado
    Serial1.begin(9600);
    }

void loop() {
  int valor=digitalRead(interruptor);
 //si el modulo ha mandado dato, guardarlo en estado.

  if(Serial1.available() > 0){
       state = Serial1.read();
  } // esta parte del código es para solo 1 Carácter o Unidad.

 // si el estado es 0 ese sería Apagado “OFF”
 if (valor== LOW) {
    digitalWrite(ledPin, LOW);
    Serial1.println("LED: off");
 }

 // de lo contrario si el estado es 1 ese sería Encendido “ON”
 else
 if (valor== HIGH) {
     if (state== 1){
     digitalWrite(ledPin, HIGH);
     Serial1.println("LED: on");
     }
     else if (state== 0){
     digitalWrite(ledPin, LOW);
     Serial1.println("LED: off");

     }
 }

}

You have to invalidate the ‘state’ variable when Serial is not available, otherwise you will produce strange behaviours.

if(Serial1.available() > 0){
       state = Serial1.read();
  } else {
       state =-1; // not valid
    }

Also, you have to check ‘1’ and ‘0’ characters and not 1 and 0 values. ‘if (state == ‘1’)..’


Is my LM35 not working? I connected LM35DZ - plugged 5.25V from USB to VIN and ground from USB to GND. Then I checked the voltage across GND and VOUT - 0.0V. Then I tried VOUT and VIN - 4.75V. It should have been 0.23V (in room temperature) between GND and VOUT, as I understand. Then I decided to use higher voltage (12V), because,  datasheet specifies that VIN can be 4-20V. The moment I turned on my power source, smoke came out of LM35DZ. What happened? Was it some cheap chinese knock-off? There's no resistor needed or anything else. At least smoke smells nice...

The data sheet sample circuit shows either an open output (presumably into a high impedance input such as the '328's A/D), or connected to -Vs via a resistor chosen to draw 50 mA. Access to -Vs is not typical of our applications but they do show a current-limiting resistor to ground in that case. So I'd expect that grounding the output caused the device to draw more current than it could dissipate without overheating.


Can't detect I2C displays with Arduino Nano All cables tested and work:

SCL - A5
SDA - A4
VCC - 5V
GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

This is the code I used, i2c_scanner, and this output:

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

... is all I get.

Any suggestions, or is my board output fried?

You seem to have two issues here:

As already pointed out, you have the white wire connected to the wrong pin on the Arduino
Also, you need to solder the headers on the Arduino. There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers


code for automatic door I want it running as a normal automatic door so both sensors work as a separate activate. The only problem I've seen is that the servo remains active waiting for another high read and you can hear the buzz of it trying to keep position.

It didn't used to do this before the code change. While its open, if it reads another high it will remember and rerun the open wait close after it closes.

Eg. The door activates and while open 3 people walk thru so when the door closes it will then run 3 more times with out anyone being there.

Edit: Code changed

    #include <Servo.h>

  Servo myservo;

  int pos = 0; //variable to store servo position

  //amount of time we give the sensor to calibrate(10-60 secs according to       the datasheet)

  int calibrationTime = 30;

  int pirPin = 12; //digital pin connected to the PIR's output
  int pirPos = 13; //connects to the PIR's 5V pin
  int pirPin2 = 6; //digital pin connected to the PIR's output
  int pirPos2 = 10; //connects to the PIR's 5V pin
  const int position_closed = 0;      // door closed position [deg]
  const int position_open = 90;      // door open position [deg]
  const uint32_t delay_step = 15;     // delay between servo steps [ms]
  const uint32_t delay_open = 60000;  // how long the door stays open [ms]

  void setup()

  {
      myservo.attach(4); //attaches servo to pin 4
Serial.begin(9600); //begins serial communication
pinMode(pirPin, INPUT);
pinMode(pirPos, OUTPUT);
digitalWrite(pirPos, HIGH);
pinMode(pirPin2, INPUT);
pinMode(pirPos2, OUTPUT);
digitalWrite(pirPos2, HIGH);

//give the sensor time to calibrate
Serial.println("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++)
{
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
}
Serial.println();
Serial.println("done");
  }

  void loop()
  {
static enum { CLOSED, OPENING, OPEN, CLOSING } state;
static int position;          // door position
static uint32_t last_change;  // last time state or position changed
uint32_t now = millis();

// When presence is detected, switch to the OPENING state.
if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
        && state != OPENING) {
    state = OPENING;
    last_change = now;
}
else switch (state) {
    case CLOSED:
        break;
    case OPENING:
        if (position == position_open) {
            state = OPEN;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(++position);
            last_change = now;
        }
        break;
    case OPEN:
        if (now - last_change >= delay_open) {
            state = CLOSING;
            last_change = now;
        }
        break;
    case CLOSING:
        if (position == position_closed) {
            state = CLOSED;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(--position);
            last_change = now;
        }
        break;
      }
  }

KennetRunner already explained what is wrong with your code. Here I will
try to give advice on the proper way to implement the automatic door.

First thing is to get rid of delay(). While your program is inside a
call to delay(), it can do nothing but wait until the delay is over.
This is acceptable if the program has only one single task to perform,
like blinking an LED. As soon as you have two tasks, delay() is a
nuisance because it blocks all the tasks.

Case in hand: after keeping the door open for one minute, your program
would close it, irrespective of whether there is someone in the way. It
could not see the person come because it was busy delaying the closing
of the door.

The standard way to get rid of delay() is to never wait inside
loop(). Instead, if there is something to do right now, do it; if
not, just don't do it, but do not wait. Pseudo-code:

void loop()
{
    if (it_is_time_to_do_foo()) {
        do_foo();
    }
    if (it_is_time_to_do_bar()) {
        do_bar();
    }
    /// etc...
}

You would use the millis() function to know when the time has
come to do some task, as explained in the Blink Without Delay
Arduino tutorial. This is really the second tutorial every Arduino user
should read, right after learning how to blink an LED.

Next, you have to learn how to implement a finite state machine. I
recommend the Finite State Machine tutorial by Majenko,
a regular contributor to this site.

Your problem can be very naturally mapped into a machine with four
states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules
about what to do in each state, and when to transition to another state.
For example:

when the door is CLOSED

if the sensors detect someone, transition to the OPENING state

when the door is OPENING

if it's time to move the servo by one step, do it
if we have already moved all the way to the open position, we can
say the door is OPEN now

when the door is OPEN

if it's time to close it, transition to the CLOSING state
if the sensors detect someone, reset the timer <<<< note this!

when the door is CLOSING

if the sensors detect someone, transition to the OPENING state
if it's time to move the servo by one step, do it
if we have already moved all the way to the closed position, we say
the door is now CLOSED

A few things to note here:

See the line marked by “<<<<”: this will prevent the aforementioned
problem of the door closing into someone.
The first rule for the CLOSING state follows from a similar rationale.
I made up some of these rules, as the job of your program was not
completely specified in your question. Feel free to change those rules
to your taste.

And here is my proposed implementation. Warning: not tested. As
usual with FSMs, it is based on a big switch/case statement going
through all the possible states. However, to avoid repeating rules, I
factored the “if there is someone, start OPENING” rule out of the
switch. I also folded “if there is someone, reset the timer” into the
same rule.

const int position_closed = 0;      // door closed position [deg]
const int position_open = 180;      // door open position [deg]
const uint32_t delay_step = 15;     // delay between servo steps [ms]
const uint32_t delay_open = 60000;  // how long the door stays open [ms]

void loop()
{
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
    }
}


My DHT22 module doesn`t work at all I had bought this DHT22 module on AliExpress. The module looks fine, but it does not work at all. I had tried lots of sketches, I tried to change the pin, I tried to change the cables, but I always have the same result:
Failed to read from DHT22 sensor!.
That's what I get if I use the standard sketch DHTtester.ino:

That's what I get if I use the standard sketch DHT_Unified_Sensor.ino:

Can you help me? Or is the module corrupted?

The product page you linked to has modules of different types.
Make sure you have uncommented the matching type in the this section of the example:
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

Also makers of these boards sometimes label them incorrectly or describe them incorrectly when selling them.  If you're unsure what you have, try them all.


Controlling flexinol with an arduino board? I am looking to wire up 16 pieces of flexinol (http://www.musclewires.com/MWFlexinol.php)  using an arduino board. Ideally I would like to be able to activate them independently, meaning that they could all be on, off or in any combination in between. My understanding that they would need to draw more current than the board could handle so some type of shield would be necessary?

Any suggestions would be greatly appreciated.

First thing's first, this just seems to be a wire that has special characteristics. If so, we just need to find out the resistance and use Ohm's law.

From the product page, I found this image:

I can tell from that that it has a resistance of 20 ohms and a recommended current of 1 amp. First, let's see how much current it would draw with a 5V supply. I prefer using a Ohm's law triangle, just because I'm a very visual person. So with this math:

  5 / 20 = 0.25

That's 250 mA, but an Arduino can only provide 40 mA! Furthermore, it is only 1/4 of the recommended current that the manufacturer specifies.

To get the full current the OEM specifies you'll need a 20 V power supply capable of at least 1A. Even then, you might want to put in a power resistor to limit the current.

Driving this with Arduino: So, we have a few problems here:

It is 20W, which is quite a bit in the Arduino world
We need to control the current/voltage dynamically
You need 16 of them, so we don't want something too costly
You probably can't find something to fit your needs that is one shield.

What comes to mind is a transistor. I'm not skilled with picking them out, but there are a lot of guides online. You'd then want to add a capacitor and a resistor to make some sort of filter and connect it to a PWM pin to send a varied voltage to the transistor, which will vary the amount of power going through it.

Alternatively, you could use a relay. However, that only does ON or OFF. A solid state relay (SSR) would allow you to use PWM on the relay and then you could add a capacitor/resistor combo on the other end of it, but you'd need a pretty large capacitor or a pretty large frequency for the PWM (which you can modify).


Communicate from Arudino to computer over 3.5mm port I'm wondering if it would be somehow possibly to have easy communication with a computer for Arduinos that don't have USB like the pro mini. That would make an easy way of having two-way communication with a computer. The computer could just play or record audio using software written specifically for this purpose. Would something like this require any special circuitry or would it just be a matter of connecting the right wires?

I didn't read the all page, but it seems it can be achieved, see David Awehr's blog (this one is conected to a android phone instead to a PC tho) and this Hackaday page where they seems to it, but the PC's audio input normally use 44,1kHz or 96kHz, so if you wanna go for the higher Serial speed (let's say just 115200bauds) you should think about it this.


Formula / calculation of the function random() / randomSeed() In which file can I find the calculation that is called with random()? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE.

I found this in the "WMath.cpp" but that is not the final calculation.

void randomSeed(unsigned int seed)
{
  if (seed != 0) {
    srandom(seed);
  }
}

long random(long howbig)
{
  if (howbig == 0) {
    return 0;
  }
  return random() % howbig;
}

long random(long howsmall, long howbig)
{
  if (howsmall >= howbig) {
    return howsmall;
  }
  long diff = howbig - howsmall;
  return random(diff) + howsmall;
}

The underlying random() function isn't part of the Arduino code. It's actually part of avr-libc. The Arduino IDE only comes with pre-compiled object code for it (as far as I know).

It's open source though. You can get information about it here:

http://www.nongnu.org/avr-libc

If you look down the page a short way, you'll find the "Source code and documentation" link.

The random() function is under libc/stdlib/random.c. I would paste the source code here, but technically I'd have to include a whole copyright notice with it.


Can you connect an output pin from one Arduino to the input pin of another? I have a system that uses two Arduino boards.  One is used to control several different functions, and the other is dedicated to driving a 45 second countdown display (comprised of two large 7 segment displays.)  All this second Arduino needs is a single signal to tell it when to start.  I would like to simply connect an output pin (on #1) to an input pin (on #2) and and send a single pulse to get the clock started.  Fo something this simple, I wanted to avoid using I2C.  Can I do this?  If so, is there anything else I need to be aware of (like connecting ground to ground?)

Yes, you can. That is indeed the most easy way of communication.

And like you said, you have to connect the grounds of both arduino's.

Optionally you could add a pull-up of pull-down resistor, so the countdown doesn't accidentally start if the first arduino is still starting up, or is disconnected.


Adafruit Trinket M0 persistent storage? I am using an Adafruit Trinket M0 to program a small game and would like to save the game state every so often. I am programming it through the Arduino IDE as the chip does not have enough space to run my game with circuitpython (too many libraries). Does the Trinket M0 have any form of persistent storage that I can use, or will I need to use a different device?

I couldn't find EEPROM in the documentation, but I wasn't able to find a definitive answer whether or not it has any form of long term storage. Knowing the board is based on the Attiny85 I would expect it to have 512 bytes or so, but the arduino library is giving me problems when I try to use it as well, so there is no way for me to trial and error this.

The M0 boards use a SAMD chip. It has no EEPROM. To store data without additional hardware like external EEPROM or SD card, you can use the flash memory of the SAMD. But it has a drawback of limited count of writes to flash memory.

An EEPROM emulation library exits. It uses the flash memory, so the drawback of limited writes, applies. I used it, it works. The library is almost official. The author is Arduino's coworker.


Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up I have a problem like that....As I connect my Arduino to the laptop with the usb cable and the motor shield connected, my led won't turn on neither does the led on the Arduino. And the small chip like thingy beside the usb cable also heats up really bad...please help!

0

You might have burned one of the onboard voltage regulators. In my case, it was AMS1117 which was burned and my Arduino was behaving similarly. You will notice that the Arduino will work with an external power supply connected to the Vin pin of Arduino and it will not become hot.

 In short, the small chip which is getting hot is a voltage regulator may be AMS1117 and you have to replace it manually or buy a new Arduino


POV using ATmega328 powered with cr2032 cell I am planning to make a POV (persistence of vision) display using ATmega328 with 5 red LEDs for display.
Below are my aims:

I want to power it with cr2032 coin cell, so power consumption has to be taken care, I am ready to keep single or 2 coin cell in parallel to meet current requirement.

Using 8MHz clock instead of 16MHz can help

Does it require separate boot-loader to be installed?
During boot-loading do I require to put external 16MHz clock?
How to ask controller to use the internal 8MHz clock?

Supply voltage of 3V instead of 5V can also help, and cr2032 gives out 3V

What care should I take while using it at 3V?
Any mechanism to set the threshold for controller to stop working?

To reduce the weight of whole circuit so I can rotate the board using small toy motor (I don't have a gear box).
I am planning to control the speed of motor using LM317 voltage regulator as a constant current source.
I will mount the LEDs on straw, keep the controller and the coin cells at the center. (Guessing that will reduce the torque required by the motor as torque=Force*radius and weight being at center reduced the radius)
I am okay, if this circuit works for just few hours OR days.

Not exactly an answer, but too big to place into the "comments" area.

Clock
For the 8MHz vs 16MHz, you should be able to run your project at 1MHz. Just use a bare AVR MCU with the Internal 8MHz oscillator divided by 8 - search for AVR Fuses. You can program it using an ISP (or and Arduino as ISP)

Battery
About the CR2032 or coin-cells in general are not designed to constantly supply current. You can use it for very low currents, up to 2-4mA or in pulses. Otherwise you damage the cell, reducing it's total usable capacity. Maybe have a look on sub AAA batteries instead of coin-cells.

Motor
For the motor, have a look on the micro coreless dc motors. They are really tiny and should offer an excellent efficiency. Motor example

Motor Driver
Not sure about the LM317. You don't want any kind of regulation as it would waste energy. To drive the motor a small Mosfet should do the trick. You can control the Mosfet using PWM, which will define the motor speed. Don't forget to implement some kind of rotary encoder to count the motor RPM so you can precise speed control - a tiny magnet and a hall-sensor should be enough.


Why is CLK_FLASH separate from CLK_CPU? The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.