Can anyone recommend a breadboard for the new Arduino 101? I just got an Arduino 101 board. I was told that it's practically the same as the UNO. But have no experience using the UNO and I've only done super simple things on the 101 board without using a bread board.

What I want to do is have 2 servos connect to the board. I've only connected one servo without using a breadboard. I've looked on Instructables.com and other places that connect at least 2 to up most 12 servos. They all use different breadboards without specify if the brand, model, or if size even matters. I don't know how breadboards work and which holes I plug the wires into. Furthermore, I haven't found any videos on people working on the 101 board.

Next, I'm not sure if the servos will share the same volt port. There's only 3V and 5V on my Arduino 101 board. If they all need 5V, I'm not sure how to make both servos share. I don't know how they will share the same ground port as well. I know for sure, they will have their own analog port.

A list of recommendations would be nice. Thanks.

A breadboard is nothing but a way to attach multiple wires to the same pins. There are many different kinds as can be seen in these images. There's no right or wrong when it comes to breadboards, as long as you have enough pins to prototype you should be good to go.


I want to make my stepper motor work for 1 hour I already tried code that makes the stepper motor work for a few minutes only. I'm using a clock module, a DS1302 and the stepper library already present. Also the driver I'm using is an L298n. If someone could help out it would be nice. Thanks.

#include <Stepper.h>
#include <virtuabotixRTC.h>

virtuabotixRTC myRTC(5, 6, 7);
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

const int OnHour = 12;
const int OnMin = 52;
const int OffHour = 12;
const int OffMin = 55;

void setup() {
  Serial.begin(9600);
  myStepper.setSpeed(100);
}

void loop() {
  myRTC.updateTime();
  Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print(" ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  if (myRTC.hours >= OnHour && myRTC.minutes >= OnMin && myRTC.hours <= OffHour && myRTC.minutes < OffMin) {
    Serial.print(myRTC.hours);
    Serial.print(":");
    Serial.print(myRTC.minutes);
    Serial.print(":");
    Serial.println(myRTC.seconds);
    myStepper.step(stepsPerRevolution);
  }
}

The problem you have is you are treating minutes and hours separately. That won't work - they need to be combined.  As it stands your "on" time is:

Minutes greater than W, and
Hours greater than X, and
Minutes less than Y, and
Hours less than Z.

Or, to rearrange that:

Hours between X and Z, and
Minutes between W and Y.

You can see that won't work. You will only get "on" for the block of minutes between W and Y for each hour in your "ON" period.

For example, if you want ON from 9:30 to 12:45, you get:

If hours greater than or equal to 9 and less than or equal to 12, and
Minutes greater than or equal to 30 and less than or equal to 45

So, that's 9:30 to 9:45, 10:30 to 10:45, 11:30 to 11:45 and 12:30 to 12:45

Even worse if you want 9:30 to 12:00...  the second part of the IF above becomes:

Minutes greater than or equal to 30 and less than or equal to than 0.

That can never happen. There is no number that is both greater than 30 and less than 0.

So you have to combine the two values together, to create a "minutes since midnight" value. Then your ON time is decided by the number of minutes, not the hours and the minutes separately.  It's simple enough:

int minutesSinceMidnight = myRTC.hours * 60 + myRTC.minutes;

Your ON time then becomes, for 9:30, 9 * 60 + 30 = 570, to 12:00 = 12 * 60 + 0 = 720.

So:

if (minutesSinceMidnight >= 570 && minutesSinceMidnight <= 720) {
    // Do your stepping
}


Arduino Pro micro Serial communication problem with Node MCU I recently bought an ATmega32U4 based Arduino Pro micro. I am using the Keyboard library and interfacing with my PC via USB.
I am trying to create a serial communication between the Arduino Pro micro and a NodeMCU via Rx, Tx pins (0, 1), but it isn't working i.e. not giving any output with the code below on the Pro micro:
#include <Keyboard.h>

int incomingByte;
unsigned long lastTime;

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

void loop() {
  if (Serial.available() > 0) {
    lastTime = millis();
    String payload = "";

    while (1) {
      if (millis() - lastTime > 1000)
        break;

      incomingByte = Serial.read();
      Serial.println(incomingByte);
    }
  }

On the NodeMCU there is a simple script flashed which only writes on serial some characters in a delayed loop.
When using the SoftwareSerial library with the Pro micro, it is working fine i.e. I can read data sent by the NodeMCU on custom Rx, Tx pins (9, 10). I tried this because I thought since Pro micro is communicating with a PC, the original Rx and Tx pins are busy. But after some research I got to know that unlike other Arduino boards like the UNO, the Pro micro doesn't use those for communication over USB.
Although custom serial using SoftwareSerial library is working, it is too slow and unreliable i.e. it takes 2-3 seconds to pass a string of length 10. Also its unreliable because on sending bigger length strings, the strings arrive incomplete or sometimes the data gets corrupted (characters shuffle).
Again this is not my main concern, if I can use original Rx, Tx pins as usual on any other Arduino boards, it solves my issue.
This is my circuit diagram:

RX and TX pin of Arduino Micro are Serial1. Replace Serial in your sketch with Serial1 to communicate with esp8266 over RX and TX pin.


How do I deal with this Arduino IDE installation error? I am using Linux Fedora 20 (yes I am going to upgrade it, definitely, soon) and I have installed arduino-1.8.0, but I get this message ...

  Your copy of the IDE is installed in a subfolder of your sketchbook.
  Please move the IDE to another folder

... when I click on the desktop icon, or run ./arduino. I have tried moving the tar.xz file to its own folder ArduinIDE again installed it but get the same message. Please,what should I do to get out of this? Please no answers like "just do what it says":in that case what do I move, and what criteria does the destination need to have?

Delete (or edit) your preferences.txt file - it most likely has your sketchbook folder set to your home directory.

You may find it in ~/.arduino15 for the "real" Arduino IDE, or in (I think) ~/.arduino for the arduino.org one.

Unless you have a specific reason for wanting to run 1.8.0, which is actually 1.0.6 re-numbered, you should be using the version from arduino.cc which is currently 1.6.13.


Why am I receiving random input values in my Arduino? I want to use a switch for my Arduino using digitalRead(), but I keep receiving random inputs. Whenever I connect energy to that pin, it always returns HIGH, but otherwise it goes completely random.
I have tried using a resistor for the input pin, but that didn't seem to help. I am using an Elegoo UNO, and the input pin I am using is pin 2. Here's my code in case you need it:
const int switchPin = 3;

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

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(switchPin) == HIGH){
    Serial.println("on");
  }

  else{
    Serial.println("off");
  }
}

You're getting noise pickup on the input pin when the button is not pressed. You need a pull-down resistor, about 10 kΩ to ground, to quiet the noise when the switch is open.
Or even easier, use the built-in pull-up resistor in the Arduino, which is ~10 kΩ to +5 V, wire your button to ground instead of +5 V, and reverse the if tests to test for logic LOW instead of HIGH, to detect a button press. You'd change your pinmode statement to:
pinMode(switchPin, INPUT_PULLUP);  // engage the input pullup

and your test to:
 if (digitalRead(switchPin) == LOW ){ // Negative logic

No additional (external) hardware is needed!


SIM900/Arduino UNO R3 serial communication not working For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial.
I tried several ways to wire it up:
shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial.
shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial.
shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial.
Tried even different pins other than 7 & 8. None worked.
I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop.
Any suggestions ?
Here's the code:

#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

To make everything work fine with this exact code and wiring from the lastminuteengineers, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins D8(RX) and D7(TX), which are the pins at the top of the yellow plate, to the two pins in the middle of the yellow plate.


Interfacing LM35 and MQ2 with Arduino When I interface LM35 temperature sensor and MQ-2 gas sensor with Arduino - my LM35 sensor gave incorrect values. From research I've found out that MQ-2 gas sensor dragging the AREF voltage down and causing the error due to its 31ohm heater that drawn 161mA current . What'll I do to solve this problem?

A wiring diagram would help! But it sounds like you're powering your sensor from the Arduino's AREF pin. That is not the purpose of AREF; AREF is there for you to provide an accurate +5v or other reference voltage to the A/D convertor.
You need to power the sensor independently from your 5v supply (and not through the Arduino either, because of the sensors current draw); connect the sensor's Analog Out to one of the Arduino's A/D pins, sensor Ground to the supply ground. The digital out appears to be optional, if all you want is a go/no-go output that you adjust with the on-sensor potentiometer.


Arduino UNO and TB67H303HG Ic driver: Wiring question I would like to control the TB67H303HG (a full bridge driver IC for DC motor
adopting MOS in output transistor) with my Arduino UNO.
This is its datasheet.

I was thinking to connect:

PIN 3 INPUT to Arduino Digital Output 13 and set it to LOW to use the direct PWM mode
PIN 5 Vref to 24VDC
PIN 6 Vcc to 24VDC
PIN 7 STBY to Arduino pin 8
PIN 8 IN1 to Arduino Pin 12
PIN 9 IN2 to Arduino Pin 11
PIN 16 OUT1A and 12 OUT1B in parallel to the Motor
PIN 14 OUT2A and 10 OUT2B in parallel to the Motor
PIN 13 and 17 to GND
PIN 20 Vcc to 24VDC
PIN 22 PWM to Arduino PWM 10

I do not know if I'm wrong, but I think I should use IN1 and IN2 to select the motor spin rotation and the Pin 12 PWM to change the velocity by setting the Arduino pin 10 with the PWM output from 0 to 255. Is it correct?

Can you tell me if the wiring is correct?
Thank you a lot!

The Vref potential should not be 24V. As mentionned in the datasheet:

Vref = 0.3V to 1.95V depending on what you want.


How to get keyboard input to arduino from the computer its plugged in to? I have an arduino uno connected to my laptop.
and i need to get keypress info from the laptop's keyboard
with only the arduino sketch and without any program running on the laptop.
Is there a specific library or some way of doing so?

You can't. It's impossible.

Or not as you have requested it, anyway.

The Arduino can only talk over Serial, so you will have to have some software running on the PC that transfers data (however that data is generated) over serial to the Arduino to process.

The only other option will be to have one of the Arduino boards that is capable of acting as a USB Keyboard device, such as a Leonardo, plus either a PS/2 keyboard or a USB keyboard plus a USB Host shield. Your Arduino the receives the keystrokes from the keyboard, processes them, and sends the result on to the PC.


How much time does the Arduino need to call a Function or to read a Variable? How much time does an Arduino Uno or Mega need to only call a function. And how does the time change if this function is inside a Class, for example inside a Library?

The same thing for a variable. How much time does a micro-controller need to read a declared variable?

How to determine this values? Is there a mathematic formula? Can we predetermine this type of delays and other similar micro-controller related delays?

It is hard to give a general answer, as it depends on the specifics of
your code and on how the compiler compiles it:

  How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

the caller puts the arguments on some predefined CPU registers, unless
they are already there from a previous operation (the compiler tries
to optimize the code so that this happens whenever possible)
the caller issues the call instruction to do the actual function
call
the callee pushes some CPU registers into the stack in order to use
them without clobbering the caller's data
the callee does its job
the callee pops the previously pushed registers
the callee issues the ret (meaning return) instruction
the caller finds the return value in some CPU registers

On the Uno, the call and ret instructions cost 4 CPU cycles
each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs)
each. push and pop are 2 cycles each, and you need one such
pair for every 8-bit register you need to save.

  And how does the time change if this function is inside a Class, for
  example inside a Library?

The only difference is that a class method receives an extra hidden
parameter called this. Except if it's a virtual method, which is more
expensive because it involves some pointer dereferencing.

  How much time does a micro-controller need to read a declared
  variable?

“Reading” generally means transferring the contents of the variable to
some CPU registers. Local variable are usually allocated to CPU
registers in the first place, so there is no need to read them. Global
(and local static) variables are stored in RAM, and reading them takes
2 cycles per byte (e.g. 4 cycles for a 16-bit int).

  How to determine this values?

Disassemble the code generated by the compiler. Then look up the
instructions in the instruction set manual: it documents the number
of clock cycles needed by each instruction.


How can I stop SoftwareSerial from receiving data and re-enable it at some other point? My project involves and RFID reader connected to an Arduino Pro Mini (5V, 16MHz) and an Adafruit CC3000 breakout WiFi chip. The device reads RFID tags and sends them to my web service. I am using Software Serial to read the RFID device data.

After I scan something, the Arduino tries to send the value that was read to the web service. This obviously causes a delay and the program only continues execution (i.e. next iteration of the loop() function) after the data has been sent.

My problem is simple. While the value is being sent, the serial buffer is can still accept scans from the RFID reader and on subsequent iterations, because there is data in the buffer the device attempts to send data again.

My question is how can I stop the software serial port from receiving data while I am trying to send data to the web service? Then when the data is sent successfully, how can I re-enable the software serial port from accepting data?

Call serial.end() to stop receiving.

Then call serial.begin(...) again when you want to start listening again.


Having an issue running an Arduino sketch I just got my USB host shield attached to my Arduino Uno, opened the program sketch for USBDESC.ino and I'm getting an error. It says "usbhub.h not found". It won't compile. How did I go wrong?

I am using the Mac version of the Arduino IDE and downloaded the USB host shield Master v 2.0 file directly into /Arduino/java/examples. This was how I have added every previous library download. Please help. Thanks.

I don't know how you came up with that location as the right place to put libraries. It is wrong. Oh so very wrong.

Libraries go in ~/Documents/Arduino/libraries as stated in the first hit for "arduino macos libraries" on Google.


Can I connect an Arduino Uno Wifi to Arduino Cloud? Can I connect an Arduino Uno Wifi to Arduino Cloud? If yes, how? If no, what cloud is compatible?

I have tried to look online but I could not find anything that raises this question.

If you sign in to Arduino Cloud the very first thing it asks you is which board you are using. One of the options is the Arduino WiFi Shield 101. That is a shield that you can attach to any Uno-footprint board (including the Uno) to give it encrypted WiFi.

Another option is the Yun shield which turns your Uno into a kind-of Yun.

There are many many other "clouds*" that support Arduino, and many that if you are a reasonable programmer should be simple enough to make work with Arduino, since 99.99% of them all work through some form of HTML-based interface.

* Cloud: n. An idiotic buzzword used to describe pretty much any website these days.


Comparing custom variable type definitions In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:

// states
typedef enum {
    OBD_DISCONNECTED = 0,
    OBD_CONNECTING = 1,
    OBD_CONNECTED = 2,
    OBD_FAILED = 3
} OBD_STATES;

...

// get connection state
virtual OBD_STATES getState() {
      return m_state;
}

How can I get the state into a variable such as boolean isConnected or int state so it can interact with the rest of my code? I have tried the following with no luck:

boolean isConnected = obd.getState() == OBD_CONNECTED;
if(isConnected) { ... }

int state = (int) obd.getState();
if(state == 2) { ...}

In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.

Anyway, it is better to use a switch statement:

Serial.write("ODB State: ");
switch (odb.getState()) {
  case ODB_DISCONNECTED:
    Serial.write("Disconnected");
    break;

  case OBD_CONNECTING:
    Serial.write("Connecting");
    break;

  case OBD_CONNECTED:
    Serial.write("Connected");
    break;

  case OBD_FAILED:
    Serial.write("Failed");
    break;

  default:
    // Error case
    break;
}
Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.


Turn on relay for amount of time by continuous input I have a project having two input status

first the input is not continuous the output buzzer relay will be on for 10 seconds and then turned off or it can be off directly by push button

the second state if the input is continuous the output buzzer relay will be on for 10 seconds and then turned off or it can be off directly by push button

I made this code but it does not work can anyone suggest an edit without using millis() because it will crash after 49 days and without using delay function.
Note that the device will work 24 hours / 365 days.
const int input1 = 19;
const int input2 = 36;
const int relay1 = 10;
const int relay2 = 21;
const int reset = 40;
const int buzzerreset = 45;
const int buzzerrelay = 46;

int buttonState1 = 0;    //for input1
int buttonState2 = 0;    //for input2
int buttonState3 = 0;    //for pushbutton
int buttonState4 = 0;    //for buzzer reset
int b4 = 0;              //for buzzer reset

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(buzzerrelay, OUTPUT);
  pinMode(input1, INPUT);
  pinMode(input2, INPUT);
  pinMode(reset, INPUT);
  pinMode(buzzerreset, INPUT);

  digitalWrite(relay1, LOW);
  digitalWrite(relay2, LOW);
  digitalWrite(buzzerrelay, LOW);
}

void loop() {
  buttonState1 = digitalRead(input1);
  if (buttonState1 == HIGH) {
    digitalWrite(relay1, HIGH);
    digitalWrite(buzzerrelay, HIGH);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState3 = digitalRead(reset);
  if (buttonState3 == HIGH) {
    digitalWrite(relay1, LOW);
    //digitalWrite(buzzer, LOW);
  } else {
    buttonState4 = digitalRead(buzzerreset);

    if ((buttonState4 == HIGH || buttonState1 == HIGH) && b4 == LOW) {
      digitalWrite(buzzerrelay, LOW);
    }
    // while (digitalRead(input1) == HIGH);
    // digitalWrite(buzzerrelay, LOW);

    (buttonState2 = digitalRead(input2));
    if (buttonState2 == HIGH) {
      digitalWrite(relay2, HIGH);
      digitalWrite(buzzerrelay, HIGH);
      //delay(10000);
      //digitalWrite(buzzer, LOW);
    }

    buttonState3 = digitalRead(reset);
    if (buttonState3 == HIGH) {
      digitalWrite(relay2, LOW);
      //digitalWrite(buzzer, LOW);
    } else {
      buttonState4 = digitalRead(buzzerreset);
      if (buttonState4 == HIGH) {
        digitalWrite(buzzerrelay, LOW);
      }
      //while (digitalRead(input2) == HIGH);
      //digitalWrite(buzzerrelay, LOW);
    }
  }
}

I would suggest having a buzzerPlaying state, an oldInput state, and a buzzerOffTime (unsigned long millis when you should turn the buzzer off.
Ignore input if buzzerPlaying == true and just check the buzzerOffTime. When buzzerOffTime passes, turn off the buzzer, set buzzerPlaying to false, and start checking the input again.
If the buzzerPlaying == false and input is high:

check buzzerPlaying. If it's true, do nothing.

If buzzerPlaying is false, check oldInput. If oldInput is high, do nothing (The input has not been reset.) else set buzzerPlaying to true, set oldInput to high, turn on the buzzer, and calculate buzzerOffTime.

If the buzzerPlaying == false and input is low, set oldInput to low (Once the buzzer has stopped playing and the input has dropped low, start looking for more inputs.)


Running quartz clock off an arduino I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/

For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)

Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:

    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    void setup()
    {
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 9 to be an output output
    }

    void loop()
    {
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
    }

For this reason I have tried to merge it with the 1 wire clock project and got

const int a1  =  8;     //use digital I/O pin 8
const int a2  =  9;
const int tick1 = 1000;
const int tick2 = 50;

int cyclesPerSecond = 974;

//pins
int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
int pwmOut = 6; //pin 6

//timekeeping
int seconds = 0;
int masterClock = 0;//number of square waves

void setup()
{
attachInterrupt(clockInterrupt, clockCounter, RISING);
pinMode(a1,OUTPUT);   //set pin 8 to be an output output
pinMode(a2,OUTPUT);   //set pin 8 to be an output output

Serial.println(pwmOut);
analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
}

void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
masterClock ++; // with each clock rise add 1 to masterclock count
if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
{
seconds ++; // after one cycle add 1 second
masterClock = 0; //reset clock counter
}
}

void loop()
{
  if (seconds == 1){
   digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
   else if(seconds == 2)
   seconds = 0;
   digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
  }
}

However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.

As I said in my comment, the idea of using the Arduino's own PWM as a
clock source is completely misguided. It will be no more accurate than
using millis() or micros(): both these functions and the PWM rely on
the same primary clock source, namely the ceramic resonator clocking the
chip.

Also, you should avoid using delay() for timekeeping. The time it
takes to run around the loop() is the sum of all your delays plus the
time needed to execute the actual instructions, which you do not know
accurately. It is far better to use either millis() or micros().

Here is a tentative sidereal clock code, not tested:

// Pins driving the clock.
const int a1 = 8;
const int a2 = 9;

// Length of one sidereal second in microseconds.
const unsigned long SIDEREAL_SECOND = 997270;

void setup()
{
    pinMode(a1, OUTPUT);
    pinMode(a2, OUTPUT);
}

void tick()
{
    static int activePin = a1;

    // Pulse the pin.
    digitalWrite(activePin, HIGH);
    delay(50);
    digitalWrite(activePin, LOW);

    // Next time use the other pin.
    if (activePin == a1) activePin = a2;
    else activePin = a1;
}

void loop()
{
    static unsigned long last_tick;
    if (micros() - last_tick >= SIDEREAL_SECOND) {
        tick();
        last_tick += SIDEREAL_SECOND;
    }
}

You can tune the speed of the clock by changing the constant
SIDEREAL_SECOND. I set the constant to the actual length of a sidereal
second, in microseconds, but you may find that the clock does not run
exactly at the correct speed. This is because the ceramic resonator
inside the Arduino is not very accurate. You can remove most of the
inaccuracy by calibration: measure how fast or slow it runs and change
the value of SIDEREAL_SECOND to compensate. You will still face some
residual inaccuracy owing to the fact that the resonator's frequency is
not very stable, and is highly temperature-dependent.

If you want to build a clock that has decent accuracy, your best bet is
to use a 32768 Hz quartz crystal, as suggested by Ignacio
Vazquez-Abrams in his comment. I did that on a bare ATmega chip (a
“barebones Arduino”) to make a
24-hour analog wall
clock. You should be
able to easily adapt the code I published in that page to fit your
project.


Circuit with a tip120 works with a Led but, don't with a vibrator motor I have 2 Arduino Nano's. One with RF transmitter and the other with an RF receiver of 433 MHz and both have two 3v vibration motors. I want one Arduino to send a string to the other Arduino to let him know which vibrator he needs to vibrate. The connection works, when the Arduino with the transmitter sends a message, the other Arduino gets the message and sets pin 2 (the pin for the vibrator via a tip120) HIGH. But the vibrator does not vibrate. When I change the vibrator with a led it works, the led goes on and off. So why does the led work but the vibrator motor not?

I use the VirtualWire library for the RF modules.

Here is the code and I also provided a summary:

Summary: This is the receiver Arduino code. message_received is the string variable where the message is stored and in the loop, that message is to check what it contains. And then the led goes off and on.

#include <VirtualWire.h>

byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = 255; // the size of the message

String message_received;

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  Serial.println("RECEIVER MONITOR");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (vw_get_message(message, &messageLength)){ // Non-blocking
    Serial.print("Incoming message: ");
    for (int i = 0; i < messageLength; i++){
      Serial.write(message[i]);
      message_received += (char)message[i];
    }
    Serial.println();
  }
  if(message_received == message_go_on){
    digitalWrite(2, HIGH);
  }
  if(message_received == message_go_off){
    digitalWrite(2, LOW);
  }
  message_received = "";
}

Summary: This is the code of the transmitter. I have 2 messages that I want to send every 200 milliseconds. The send method is for the transmitter and it needs a char array so I change the string to a char[] with a toCharArray() method.

#include <VirtualWire.h>

String message_go_on = "GO_ON";
String message_go_off = "GO_OF";

char buf1[VW_MAX_MESSAGE_LEN];
char buf2[VW_MAX_MESSAGE_LEN];

void setup() {
  Serial.begin(9600);
  vw_setup(2000); // Bits per sec

  message_go_on.toCharArray(buf1,VW_MAX_MESSAGE_LEN);
  message_go_off.toCharArray(buf2,VW_MAX_MESSAGE_LEN);
  Serial.println("TRNASMITTER MONITOR");
}

void loop() {
  send(buf1);
  delay(200);
  send(buf2);
  delay(200);
}

void send (char *message)
{
  vw_send((uint8_t *)message, strlen(message));
  vw_wait_tx(); // Wait until the whole message is gone
}

The circuit of the receiver Arduino:

I think the vibrator might be undersupplied but why would the led work?

Thanks for the help!

The TIP120 is possibly the worst transistor you could choose for this job. It is a Darlington Pair transistor, and those have a (relatively) massive forward drop of between 2 and 4 volts. It works with the LED because an LED needs a tiny amount of current to operate compared to the motor and has a fixed forward voltage of its own. The motor doesn't, and is being starved of power by that huge voltage drop (it's getting maybe half the voltage it should be getting).

Throw away that TIP120 and replace it with a decent N-channel MOSFET - one with a "threshold voltage" (VGS) of 2.5V or less ideally.


String to float on Arduino I'm trying to convert a String to a float but I'm running into issues with precision, even with the Arduino's own String example I'm getting bad results.

Example 0:
Input string: 1.234567  After conversion to float: 1.2345669

Example 1:
Input string: 60.123456 After conversion to float: 60.1234512

Example 2:
Input string: 9.876543  After conversion to float:9.8765430

Why is this happening and how do I get rid of this?

There are two issues at play here:

1 – Limited precision of the float data type

A float has a precision of roughly 10−7, and any number that
is not an exact float is supposed to be rounded to the nearest float.
For example, the two floats closest to 1.234567 are
10356298 × 2−23 = 1.2345669269561767578125 and
10356299 × 2−23 = 1.23456704616546630859375.
The latter is the closest.

2 – Naive string to float implementation in the Arduino core

The Arduino core aims at being small and consume few resources.
Sometimes it cuts corners, at the cost of accuracy. In this case,
although a correct implementation is supposed to round 1.234567 up,
because the nearest float is above that number, the actual
implementation ends up rounding down. Thus you end up with roughly
1.234566927, which is off by 0.61 ULPs (units of the last place), instead
of the expected error of 0.39 ULPs.


Arduino to read from RS232 converter to TTL serial module (updated) Here's the system I want to work on:

The weight controller device detects weight which can transfer data via RS232 serial connection
I used RS232 converter to TTL serial module to connect the weight controller device to Arduino
The TTL connections were made to respective pins of Arduino UNO Board (GND-GND, VCC-5V, RX-0, TX-1)

The serial print from serial connection should produce 17 character length string : ST,GS    1.58,kg

Why am I getting strange results at times?

// Read Serial (RS232) data from Weight Controller Device via RS232 to TTL Converter Module

// Ignore the include statement, the editor does not allow pasting certain characters

include SoftwareSerial.h

int RX_PIN = 2;
int TX_PIN = 3;
int BAUD_IDE = 9600;
int BAUD_WEIGHT_SENSOR = 9600;

// serial port from weight controller
SoftwareSerial mySerial = SoftwareSerial(RX_PIN, TX_PIN);

void setup() {
  mySerial.begin(BAUD_WEIGHT_SENSOR);
  Serial.begin(BAUD_IDE);
}

void loop() {
  while (mySerial.available()) {
    int inChar = mySerial.read();
    if (inChar != '\n') {
      serialData += (char)inChar;
    }
    else {
      int dataSize = serialData.length();
      Serial.print(serialData);
      Serial.print(" length:  ");
      Serial.print(dataSize);
      Serial.print("\n");
      delay(3000);
      serialData = "";
    }
  }
  serialData = "";

}

// this one works perfectly but i want to store as string to process
// information and use for other functions
/*void loop() {
  if (mySerial.available()){
    Serial.print((char)mySerial.read());

You need to disconnect the Arduino`s RX and TX pins from any device before trying to upload a sketch via USB, because the Serial data is directly wired from the USB chip to these pins. It's as if you're trying to flash the thing behind your RS232 adapter.


Push button control of multiple relays I'm new to arduinos and have not been able to find/create a working bit of code for my project. I'd like to control several different relays (standard 5v optical relays) with push buttons. I want one pushbutton1 to turn on/off relay1, pushbutton2 to turn on/off relay 2, etc.

I ran into troubles using delay statements as debouncers because I guess it locked out the remainder of the code while it ran? I then tried to use a flagging approach covered here:

https://github.com/VRomanov89/EEEnthusiast/blob/master/03.%20Arduino%20Tutorials/01.%20Advanced%20Button%20Control/ButtonSketch/ButtonSketch.ino

const int numOfInputs = 2;
const int inputPins[numOfInputs] = {2,3};
const int outputPin = 10;

int LEDState = 0;
int inputState[numOfInputs];
int lastInputState[numOfInputs] = {LOW,LOW};
bool inputFlags[numOfInputs] = {LOW,LOW};
int inputCounters[numOfInputs];

long lastDebounceTime[numOfInputs] = {0,0};
long debounceDelay = 50;

void setup() {
  for(int i = 0; i < numOfInputs; i++) {
    pinMode(inputPins[i], INPUT);
    digitalWrite(inputPins[i], HIGH); // pull-up 20k
  }
  Serial.begin(9600);
  pinMode(outputPin, OUTPUT);
}

void loop() {
  setInputFlags();
  resolveInputFlags();
  resolveOutputs();
}

void setInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    int reading = digitalRead(inputPins[i]);
    if (reading != lastInputState[i]) {
      lastDebounceTime[i] = millis();
    }
    if ((millis() - lastDebounceTime[i]) > debounceDelay) {
      if (reading != inputState[i]) {
        inputState[i] = reading;
        if (inputState[i] == HIGH) {
          inputFlags[i] = HIGH;
        }
      }
    }
    lastInputState[i] = reading;
  }
}

void resolveInputFlags() {
  for(int i = 0; i < numOfInputs; i++) {
    if(inputFlags[i] == HIGH) {
      // Input Toggle Logic
      inputCounters[i]++;
      updateLEDState(i);
      printString(i);
      inputFlags[i] = LOW;
    }
  }
}

void printString(int output) {
      Serial.print("Input ");
      Serial.print(output);
      Serial.print(" was pressed ");
      Serial.print(inputCounters[output]);
      Serial.println(" times.");
}

void updateLEDState(int input) {
  // input 0 = State 0 and 1
  if(input == 0) {
    if(LEDState == 0) {
      LEDState = 1;
    }else{
      LEDState = 0;
    }
  // input 1 = State 2 to 6
  }else if(input == 1) { // 2,3,4,5,6,2,3,4,5,6,2,
    if(LEDState == 0 || LEDState == 1 || LEDState > 5) {
      LEDState = 2;
    }else{
      LEDState++;
    }
  }
}

void resolveOutputs() {
  switch (LEDState) {
    case 0:
      digitalWrite(outputPin, LOW);
      break;
    case 1:
      digitalWrite(outputPin, HIGH);
      break;
    case 2:
      analogWrite(outputPin, 30);
      break;
    case 3:
      analogWrite(outputPin, 70);
      break;
    case 4:
      analogWrite(outputPin, 100);
      break;
    case 5:
      analogWrite(outputPin, 155);
      break;
    case 6:
      analogWrite(outputPin, 255);
      break;
    default:
    break;
  }
}

But was unable to alter the code to get it to work... could someone help me write a bit of code which will allow me to do what I want it to do? I'd rather not buy a matrix-style shield to accomplish this, but I will if I have to.

What I want to do:

Turn on relay1 by pressing momentary pushbutton1
Turn off relay1 by pressing momentary pushbutton1
Turn on relay2 by pressing momentary pushbutton2
Turn off relay2 by pressing momentary pushbutton2
etc.
etc.

Thank you in advance!

To use this sketch, you will need the Bounce2 Library, and two N.O. switches connected between GND and the Arduino Digital Pins specified. I'm not sure if there is a limit to the number of Bounce2 objects you can create. Have a look at the Bounce2.h and Bounce2.cpp files.

#include <Bounce2.h>
byte buttonOneState = 0;
byte buttonTwoState = 0;
const byte buttonPin1 = 4;
const byte buttonPin2 = 5;
const byte debouncerInterval = 50;

// Instantiate ONE OR MORE Bounce2 object(s).
Bounce debouncer = Bounce();
Bounce debouncer2 = Bounce();

void setup(){
  Serial.begin(9600);
  pinMode(buttonPin1, INPUT_PULLUP);
  pinMode(buttonPin2, INPUT_PULLUP);
  debouncer.attach(buttonPin1);
  debouncer.interval(debouncerInterval);
  debouncer2.attach(buttonPin2);
  debouncer2.interval(debouncerInterval);
}

void loop(){

  // Button 1
  if(debouncer.update()){
    if(debouncer.read() == 0){
      if(buttonOneState == 0){
        Serial.println("Turn Relay 1 ON");
        buttonOneState = 1;
      }
      else{
        Serial.println("Turn Relay 1 OFF");
        buttonOneState = 0;
      }
    }
  }

  // Button 2
  if(debouncer2.update()){
    if(debouncer2.read() == 0){
      if(buttonTwoState == 0){
        Serial.println("Turn Relay 2 ON");
        buttonTwoState = 1;
      }
      else{
        Serial.println("Turn Relay 2 OFF");
        buttonTwoState = 0;
      }
    }
  }

}


What is the most memory-friendly way to declare integer literals? I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:

for(byte i=0;i<16;i++) buf[i]=(char)ap1[i];

Would it make any difference if I declared the integer literal 16 as a constant?

const byte BUFSIZE=16;

Or using the preprocessor:

#define BUFSIZE 16

There's also the macro PROGMEM which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.

const byte BUFSIZE PROGMEM=16;

AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.

This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use

I'm not familiar with the Atmel megaAVR microcontrollers or Arduino.  But generally speaking, your memory optimization ideas are misguided.

For example, it's likely that the compiler implements local loop variables within a register so that they don't consume any RAM at all.

And the integer literal constants, such as 16 from your example, also likely don't consume any RAM.  The compiler likely incorporates these constants into the code.

Whenever you optimize something it's best to go after the big fish first.  You're focusing on the tiniest fish.  To find the big fish, look at the *.map file produced by the linker.  The map file should show how much RAM and Flash memory is used by your program.  The RAM sections might be labeled "bss" and "data" in the map file.  Hopefully the map file will also detail how much RAM is used by each compilation unit.  Find the compilation units that are using the most RAM and focus on them.  Maybe there are large buffers or arrays defined in those compilation units that can be reduced in size or redesigned.

The map file is also where you could check to see if your optimizations have made any difference.  For example, try some of the optimization you described and see whether the map file changes significantly.


How can I light one led from two different sensors? I want to light one led with two sensors, the first one is a PIR and the other one is a Photocell sensor.

The idea is to turn on the led if the PIR sensor detects movement, and also to turn the led on if the room gets darker(detected by the photocell).

I managed to make a code, but with TWO led's, a different one for every sensor.

int ledPin = 13;
int ledPin1=12;
const int ldrPin = A0;
int inputPin = 2;
int pirState = LOW;
int val = 0;

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

void loop() {

  int ldrStatus=analogRead(ldrPin);
   if(ldrStatus<=400)
 {
    digitalWrite(ledPin, HIGH);
    delay(500);
    Serial.println("LED ON");
 }
   else digitalWrite(ledPin, LOW);
    val = digitalRead(inputPin);
      if (val == HIGH) {
        digitalWrite(ledPin1, HIGH);
          if (pirState == LOW) {
            Serial.println("Motion detected!");
            pirState = HIGH;
         }
      } else {
          delay(5000);
          digitalWrite(ledPin1, LOW);
            if (pirState == HIGH){
             Serial.println("Motion ended!");
             pirState = LOW;
           }
     }
  }

int ledPin = 13;

int ldrPin = A0;

int PIR_Pin = 2;

void setup()

{

    Serial.begin(115200);

    pinMode(ledPin, OUTPUT);

    pinMode(PIR_Pin, INPUT);

    Serial.println("Started Monitoring!");
}

void loop()
{

    boolean lightStatus = ( analogRead(ldrPin) <= 400 ) ;
    digitalWrite(ledPin,  lightStatus);

    if(lightStatus) Serial.println("Light Triggered!");

    if(digitalRead(PIR_Pin) == LOW)
    {
         Serial.println("Motion Triggered!");
         digitalWrite(ledPin, HIGH);
         delay(5000);
         digitalWrite(ledPin, LOW);
     }
}

To keep it simple serial code is removed, if needed can be added easily that should not be a big issue.
Still this can be done in much more efficient way. This is just one solution.

Note: haven't complied/error checked the code as i am writing this on a phone. Hope it should work as intended, errors if any, shall be minor ones.  Comment below if any issues.

Update 1: added code to send triggered status over serial comm.

Update 2: corrected "Boolean" to be as "boolean"


Why is Toolchain Not Updated with Arduino IDE Install on Mac I have not been doing any Arduino work for about a year.  The last time I ran the Arduino IDE was in the previous version of MacOS.  Now that I have updated to the latest MacOS Version Catalina (10.15.2) I discovered that the IDE will not compile because the avr-g++ compiler is 32 bit and will not execute on the now 64-bit required MacOS.

So I did the obvious thing.  I went to the arduino.cc web site and downloaded the latest version of Arduino IDE thinking that this should solve the problem.  I updated to version 1.8.11 of the IDE but the 32-bit problem persisted.

I finally decided that the IDE was updating (new Arduino IDE app) but that the avr toolchain was not being updated.  To force this update, I deleted the entire avr toolchain from my ~/Library folder.  Now, re-running the IDE is all it took:  It discovered the toolchain missing and re-installed and installed with the correct 64 bit binaries (which were part of the new Arduino App all the time).

Perplexing -- why was the toolchain not updated with the install?  Is it a requirement to delete the existing toolchain before doing a new install of the Arduino App?

The boards packages maintained by Boards Manager and associated tools are installed in .arduino15 folder. The AVR boards package bundled with IDE is only used when there is no AVR boards package version in the .arduino15 folder.

To locate the .arduino15 folder open Preferences in IDE and there at the bottom of the window is displayed the location of the preferences file with full path to .arduino15 folder.

The content of .arduino15 folder is not changed with IDE update.


6 channel PWM with 2 - 5 kHz frequency Is it possible to set all 6 PWM frequencies to a value between 2 and 5 kHz?

I've read that the base frequency for pins pins 5 and 6 is 62500 Hz.
And the divisors for the pins 5 and 6 are only this ones: 1, 8, 64, 256, and 1024.

The closest I can get is 7.812,5 Hz with the 8 divisor. Are there any other possibilities to achieve this?

Judging from your mentioning 62.5 kHz as the base frequency for
pins 5 and 6, I assume you are talking about an Arduino Uno or
something similar.

If you set the timer 0 to phase correct PWM mode (which is how the
Arduino core configures the other timers), then its base frequency is
about 31.373 kHz (F_CPU/510). With the prescaler set
to 8, you get a PWM frequency of about 3.922 kHz on pins
5 and 6.

Note that you can set all three timers in this mode and have 6 PWM
channels at this frequency. But note also that by reconfiguring
Timer 0 you loose all the standard Arduino timing functions.


Powering a DC motor with an external battery I'm working on a project where i need to control a 6 volt motor with an Arduino. The motor that I'm using requires 6 volts so I'm using a 9 volt with a voltage divider to get those 6 volts. My problem is that when I use the external power, the motor keeps spinning and ignores the input from the Arduino. If I use a 5 V battery and draw the 5 V from the Arduino, it works fine. I made sure that the voltage divider sends out 6 volts and the current code should have the motor not spinning. Here is the circuit: Motor Schematic.

What could I do to make the motor take the input from the Arduino?

Note: The schematic isn't like my actual circuit. In reality I have 6 V power supply instead of a 9 V and a voltage divider. I also am using a motor that requires 6 volts, while the one in the schematic requires 5 V.

Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate.
More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.

Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.

(Still I would not use divider 9->6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)


Cannot run arduino as web client I have ethernet shield mounted on arduino mega, I am able to run it as server but when i try to run it as client it doesnt work , most of the time it assigns itself 255.255.255.255 ip address which i get to know as i am printing from my sketch using Ethernet.localIP()  it sometimes randomly works but then it does nt establish connection with server, I have double checked there is no firewall on my router that can block arduino ethernet web client.

#include "Ethernet.h"
#include <SPI.h>
#include<dht.h>
dht DHT;

#define DHT11_PIN 8

double tempInC;
int humidity;

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
//IPAddress ip(192, 168, 1, 177);

// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,177);

byte subnet[] = { 255, 255, 255, 0 }; //assigning subnet mask
byte gateway[] = { 192, 168, 1, 1 }; //assigning gateway

EthernetClient client;
char server[] = "192.168.1.3"; // IP Adres (or name) of server to dump data to

String data;

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

  while (!Serial) {
    ; //wait for serial port to connect. Needed for native USB port only
  }
  Ethernet.begin(mac, ip, gateway, subnet);

  Serial.print(F("connected. My IP is "));
  Serial.println(Ethernet.localIP());
  // give the Ethernet shield a second to initialize:
  delay(1000);
  data = "";
}

void loop() {
  int chk = DHT.read11(DHT11_PIN);
  delay(200);
  tempInC = DHT.temperature;
  humidity = DHT.humidity;
  Serial.print("Temp: ");
  Serial.print(tempInC);
  Serial.print(" Humidity: ");
  Serial.println(humidity);
  if (client.connect(server, 80)) {

    // Make a HTTP request:
    client.print(F("GET /arduino/add.php?temp1="));
    client.print(tempInC);
    client.print(F("&hum1="));
    client.print(humidity);
    client.println(F(" HTTP/1.1"));
    client.print(F("Host: "));
    client.println(server);
    client.println(F("Connection: close"));
    client.println();

  }
  else {
    Serial.println(F("connection failed"));
  }

  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }
  else {
    Serial.println("Client not available");
  }
  if (client.connected()) {
    client.stop();  // DISCONNECT FROM THE SERVER
  }
  //  delay(60000); // WAIT FOR A MINUTE BEFORE SENDING AGAIN
  delay(10000);
}

Here is the output of what I get from above sketch

connected. My IP is 255.255.255.255
Temp: 26.00 Humidity: 63
connection failed
Client not available

Even when it gets correct IP assigned which I am setting up in the sketch the connection to server fails.
I am very upset not being able to run client. Please help.

This could be an SD card SPI bus issue.

Note that because the W5100 and SD card share the SPI bus, only one can be active at a time. If you are
using both peripherals in your program, this should be taken care of by the corresponding libraries. If
you're not using one of the peripherals in your program, however, you'll need to explicitly deselect it. To do
this with the SD card, set pin 4 as an output and write a high to it. For the W5100, set digital pin 10 as a
high output.

  Check the Arduino shield datasheet.

Changing pin mode:

pinMode(4, OUTPUT);
digitalWrite(4, HIGH);


Briefly "wake up" Arduino in response to an event I want to connect a device to a door handle, so whenever someone opens the door I'll be able to send a message via my arduino that is connected to a WIFI shield.

I have a simple orientation sensor, so I know when the handle is being pushed. The problem is I don't want to keep the Arduino on all of the time (energy issues).

The orientation sensor closes a circuit for about 100ms, so I thought to connect the battery to the Arduino in series with the sensor, but the problem is that it might take more than 100ms to connect and send the data - I need at least 5 seconds to be sure.

Any ideas on how to make the Arduino "power up" for 10 seconds each time someone uses the door handle and then to cut off the power?

Easy answer: Don't.

Have the Arduino sleep most of the time, and let the door handle invoke an interrupt that wakes it up. Then do whatever processing is required, and then go back to sleep.

This won't work as well with a full Arduino as it would with a bare MCU since the rest of the board has its own quiescent load, but once you get it working with an Arduino you can get a bare MCU, wire it up, write the code to it, and away you go.


Pause code untill a button is pressed I need some code to pause the Arduino code until a button is pressed. I have a long program and at point I need a condition that if a Button on pin A2 is pressed then go forward, otherwise wait.

I tried using if with a condition but it failed for my purpose. I think this is because when if(...) detects that the button is not pressed, it moves to next lines (as usual). But I have a long program and I want to wait forever until the button is pressed.

The construct you are looking for is called while.
Instead of doing "If the button is pressed then continue" you need to do "while the button is not pressed do nothing".
Assuming you have an "active low" button (that is, a resistor pulling it up to +5V when not pressed, so digitalRead(A2) == LOW is "pressed"), you can do:
while (digitalRead(A2) == HIGH) {
  // Do nothing
}

So while it's not pressed (digitalRead(A2) == HIGH) don't do anything.  As soon as digitalRead(A2) returns LOW (so it is not == HIGH any more) the while loop will finish and your sketch can continue.
I write all about the while loop in an article here.


Why does the arduino respond so slow to serial input I have this really simple sketch where I blink a led light.
If I send another value threw the serial monitor then first there is always a brief second where the light doesn't blink anymore. Why is that, and how can I get rid of that?

int the_delay = 300;

void setup() {
  Serial.begin(115200);
  pinMode(12, OUTPUT);
}

void loop() {
  digitalWrite(12, HIGH);
  delay(the_delay);
  digitalWrite(12, LOW);
  delay(the_delay);
}

void serialEvent() {

  if (Serial.available()) {
    the_delay = Serial.parseInt();
    Serial.println(the_delay);
  }
}

In case it helps, eventually I would like to send values with 60fps.

It's because you're using Serial.parseInt().  It uses a timeout to find the end of the data on the serial port, and while it's waiting for that timeout it can do nothing else.

You would be better off manually reading the serial data a character at a time to build up an input string (C-string, not Arduino String) with a proper line terminator (line-feed, \n) and then convert that into an integer with atoi().


limit length of the generated timestamp from ESP32 with DS3231 to 13 I am using ESP-WROOM-32 (Olimex ESP32-PoE) with DS3231. I have used the a patch from PR on RTClib to avoid the rollover from the DS3231.

Since the DS3231 RTC provides Unix Epoch Timestamps which have a precision of only seconds, I wish to concatenate the millis() to the above mentioned timestamps to provide millisecond precision.

This is critical since I want to store information to InfluxDB from the nodes with ms precision. For that the timestamps should always be 13 digits.

code

#include <RTClib.h>
#include <Wire.h>

// PoE setting for Olimex PoE board

#define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT
#define ETH_PHY_POWER 12

// Pins for I2C on Olimex PoE board
#define I2C_SDA 13
#define I2C_SCL 16

RTC_DS3231 rtc;
RTC_Millis software_time;

void setup() {
  // put your setup code here, to run once:
  Wire.begin(I2C_SDA, I2C_SCL, 400000);
  Serial.begin(9600);
  if (!rtc.begin()) {
    Serial.println("No RTC Detected");
  }
  // adjust RTC Time
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  // adjust software timer
  software_time.adjust(rtc.now());

}

void loop() {
  // put your main code here, to run repeatedly:
  DateTime rtc_now_time = rtc.now();
  DateTime software_now_time = software_time.now();
  Serial.println();
  Serial.print("RTC now: "); Serial.print(rtc_now_time.unixtime());
  Serial.println();
  Serial.print("millis: "); Serial.print(millis());
  delay(100);

}

Output

RTC now: 1538502183
millis: 28
RTC now: 1538502183
millis: 128
RTC now: 1538502183
millis: 228
RTC now: 1538502183
millis: 328
RTC now: 1538502183
millis: 428
RTC now: 1538502183
millis: 528
RTC now: 1538502183
millis: 628
RTC now: 1538502183
millis: 728
RTC now: 1538502183
millis: 828
RTC now: 1538502183
millis: 928
RTC now: 1538502184
millis: 1028

I will store the timestamps in String so I was thinking of concatenating the .unixtime() with millis(). However since I want all my timestamps to be of fixed lenght (13) with the increasing millis value seems to be difficult because as soon as the number goes more that 999 the a digit increases making the string length 14.

Side Effect

if the timestamps for ms do not match length of 13, InfluxDB rejects the data passed through

Epoch Time

the output provided above is of 10 digits which is the epoch time since 1970. The precision of the timestamps above is of seconds. If one wants to add milliseconds to it one needs to add 3 more digits behind it. If precision needs to be microseconds it should have 6 digits and so on..
One can check the timestamps above on [https://epochconverter.com]

Any suggestions on overcoming this issue ?

For getting millisecond resolution out of an RTC, I think the only
viable solution is to sync with the 1 Hz square wave output, as
suggested by Jot in a comment. Note that, since you are only counting
seconds and milliseconds, you probably don't care about hours, minutes,
days, months, etc. So you won't use the RTC for timekeeping: only for
providing the 1 Hz reference signal and, maybe, an initial
timestamp at program startup.

Connect the SQW pin of the DS3231 to an interrupt-capable input of your
MCU. Add the following to your setup():

pinMode(SQW_PIN, INPUT_PULLUP);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);

Use the interrupt routine to both keep track of the total second count
(seconds elapsed since the Unix epoch) and record the micros() value
of the last tick:

volatile uint32_t seconds_since_epoch;
volatile uint32_t micros_on_tick;

void tick() {
    seconds_since_epoch++;
    micros_on_tick = micros();
}

Now you can combine these two values to get a millisecond-resolved
timestamp as follows:

uint64_t millis_since_epoch() {
    noInterrupts();
    uint32_t seconds = seconds_since_epoch;
    uint32_t microseconds = micros_on_tick;
    interrupts();
    uint32_t extra_micros = micros() - microseconds;
    uint16_t extra_millis = extra_micros / 1000;
    if (extra_millis > 999)
        extra_millis = 999;
    return (uint64_t) seconds * 1000 + extra_millis;
}

The value returned from this function is the 13-digit number you want,
provided seconds_since_epoch has been sensibly initialized.


How to connect Arduino and Beaglebone I am newbie, I am afraid of doing harm and getting a burned-out Beagle Bone Black. I have soldered this SparkFun Logic Level Converter - Bi-Directional.

I have several questions:

How can I check if my converter works correctly without connecting it to any board or at least only to an Arduino?
How should I connect all my schematic from bbb to converter and then to an Arduino. I have a bi-directional converter, BTW. Can someone draw a simple picture of how to connect?

I would be grateful for any help.

The simplest method of connection is just to plug the Arduino into the BBB's USB socket.  That way there's no level conversion or anything needed - you can just open the serial port and communicate through that - what could be simpler?

You can even install avrdude on the BBB itself and upload code (HEX files) direct from the BBB, and the BBB supplies all the power.


ESP8266 in AP Mode -determining if a station is connected I have an ESP8266 running in AP mode using softAP and i want to conserve battery life.
I am wanting to turn on wifi and advertise SSID for 20 seconds. If no station connects to the ssid within the 20 seconds, I want to go to sleep for 1 minute, otherwise I do not sleep.

My problem is that I cannot get "WiFi.softAPgetStationNum()" working. when I build i get a message that this is not part of ESP8266WiFi class. I have attached simplified code.

Can someone help me to achieve this please?

#include <ESP8266WiFi.h>

//WIFI Access point setup
const char* Ssid = "SSID";
const char* Password = "Password";
IPAddress ip(10,0,0,10);
IPAddress gateway(10,0,0,1);
IPAddress subnet(255,255,255,0);
WiFiServer server(80);                    // Set web server port number to
80

// GPIO pins
const int output_set = 5;
int delay_loop=0;

void setup()
{
  // Data Direction
  pinMode(output_set, OUTPUT);

  // Output initial Values
  digitalWrite(output_set, LOW);

  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(Ssid,Password);
  server.begin();

// check to see if a station is connected to this AP. If no station
connected within 20 sec timeframe, go to sleep.

while (WiFi.softAPgetStationNum()==0)              //loop here while no AP is connected to this station
{
    delay(1);
    delay_loop++;
    if (delay_loop>=20000)
    {

        ESP.deepSleep(60e6);                          //go to sleep for 60 sec -wake pin externally connected to reset pin
    }
}
}

void loop()
{
   digitalWrite(output_set, HIGH);      //Flash led once station is connected
   delay(200);
   digitalWrite(output_set, LOW);
   delay(400);
}

Followup answer from comments:

The issue was an outdated version of the ESP8266-Arduino framework. The function WiFi.softAPgetStationNum() is available in 2.4.1

For the sake of completeness: The function itself is simply a wrapper for the Espressif non-os SDK function:

/**
 * Get the count of the Station / client that are connected to the softAP interface
 * @return Stations count
 */
uint8_t ESP8266WiFiAPClass::softAPgetStationNum() {
    return wifi_softap_get_station_num();
}

See Espressif Non-OS SDK API reference chapter 3.5.36.

That function should also be available on older framework versions. However, upgrading is the recommended way to use that function.


Are all Arduino shields compatible with all Arduino boards? Are all Arduino shields compatible with all Arduino boards? Like is the Wi-Fi one compatible with the Arduino Nano & Micro as well as the Uno, etc., or do I need to be careful when buying shields that they'll be compatible with my board? Also, the shields just plug into the boards, don't they?

When you want to choose a shield for your board you should check:

1- Pin-out, this one is the least concerning one , Most arduino boards are Shield pin-out compatible and you can verify it visually, for others, normally there are some converter boards (e.g for NANO), and in the worst case, building a converter board or wiring the shield to board is trivial in most situations.

2- Shield operating voltage should match your board's, most shields operate at 5V, 3.3V or both. Normally AVR-based boards (e.g. UNO, Mega, ...) operate at 5V and ARM based ones (e.g. Due, ...) operate at 3.3V, So we should choose the shield accordingly (just keep in mind that most shield are designed with Arduino UNO in mind so it's more likely that your shields operate at 5V).

3- Library, Lots of Libraries for Arduino shields bypass Arduino library abstraction (mostly for performance reasons) and use hardware specific features (e.g directly write on specific ports), here is source of some incompatibilities between your board and the shield, for example there are handful of TFT LCD shields in the market which their library only supports UNO boards, in these cases you should either port it to your board's (based on micro-controller model and it's architecture, sometimes its as easy as changing some pin/port definitions and sometimes as hard as writing the library from scratch).


Detaching interrupts I am using the following code to enable an interrupt for a pin:

*digitalPinToPCMSK(pin) |= bit (digitalPinToPCMSKbit(pin));  // enable pin
PCIFR  |= bit (digitalPinToPCICRbit(pin)); // clear any outstanding interrupt
PCICR  |= bit (digitalPinToPCICRbit(pin)); // enable interrupt for the group

But I can't disable it. I am trying with this code:

if (*digitalPinToPCMSK(pin) == 0)
*digitalPinToPCICR(pin) &= ~(1<<digitalPinToPCICRbit(pin));

but it isn't working.

Don't you mean:

  PCICR  &= ~bit (digitalPinToPCICRbit(pin));


How to get serial data in Arduino from a barcode scanner? I want to interface my barcode scanner with an Arduino using RS232. I have connected 2 (RX), 3 (TX) and 5 (GND) of the RS232 with the corresponding pins of MAX232. I am taking TTL outputs on Arduino pins 6 and 7.

This is the code of the Arduino program:

#include <SoftwareSerial.h>

SoftwareSerial mySerial(6, 7); // RX, TX

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

void loop() {
  // run over and over
  if (mySerial.available()) {
    byte x = mySerial.read();
    Serial.println(x);
  }
}

I am not getting any output on the serial monitor when I scan a product.

Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.

However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.

Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.

Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.


How can i do something like multi threathing in arduino? I am checking for ways to implement multi threathing in Arduino, I have also tried using the library TimerOne but it doesn't seem to work, what I'm trying to make is an Arduino application then, every time a certain amount of time passes, it pops an item from the stack, and between these times, the application allows me to add items to the stack, both processes working in parallel of course.

The items popped and pushed are numbers.

I have already tried some other questions, but their solutions don't work, especially one that seems very useful, but for some reason doesn't work, I'm speaking about the one of the TimerOne library.

Any suggestion to fix the problem some other way would be cool.

Here is the code:

#include <TimerOne.h>
#include <QueueList.h>
#include <StackList.h>

const uint16_t  NOTE_B0     =   31;
const uint16_t  NOTE_C1     =   33;
const uint16_t  NOTE_CS1    =   35;
const uint16_t  NOTE_D1     =   37;
const uint16_t  NOTE_DS1    =   39;
const uint16_t  NOTE_E1     =   41;
const uint16_t  NOTE_F1     =   44;
const uint16_t  NOTE_FS1    =   46;
const uint16_t  NOTE_G1     =   49;
. . . ETC . . .
const uint16_t  NOTE_DS8    = 4978;

uint16_t Notas[] =
{
      NOTE_B0
    , NOTE_C1
    . . . ETC . . .
    , NOTE_C8
    , NOTE_CS8
    , NOTE_D8
    , NOTE_DS8
};

QueueList<int> KeyNotesNode = QueueList<int>();
StackList<int> StackNote = StackList<int>();

char receivedChar1 = '<';
char receivedChar2 = '<';

char receivedChar[] = {receivedChar1, receivedChar2};

int TempInt = 0;
bool newData = false;

bool itPopUp = false;

int modality = 0;

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

  if(modality == 0){
    Serial.println("Ingrese el tipo de funcionalidad deseada");
    Serial.println("1.- Constructor de canciones en tonos");
    Serial.println("2.- Juego de imposicion musical");
  }

  Timer1.initialize(150000);
  Timer1.attachInterrupt( setForPop );
}

void loop() {
  //Checa y controla la recepcion de los char a traves de la consola de arduino

  if (Serial.available())
  {
    receiveChar();
    showReceivedChar();
  }

//   . . .  Here is some code to process the reception of data from serialData  . . .

// From somewhere here start the loop

// . . . LOOPED . . .

    //Here is used the data
    if(modality == 1){
       //This option doesn't matter
    }
    else if(modality == 2){
      StackNote.push( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.println("Agregado receivedChar exitosamente a la Pila");
      Serial.print("Tamano Total Lista: ");
      Serial.println(StackNote.count());
      Serial.print("Dato:");
      Serial.println( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.print("Dato(get):");
      receivedChar[0] = '<';
      receivedChar[1] = '<';
    }
}

    //Run and show the data on the stack
     if(modality == 1)
     {
           //This option doesn't matter
      }
      else if(modality == 2)
      {

        if(itPopUp){   //With this variable i want to control when it is show, this code is inside loop()
          Serial.print("Reproducido con exito la nota: "); //se escribe 'éxito' pero la consola no acepta tildes, que se arrepienta :P
          TempInt = StackNote.pop();
          Serial.println(TempInt);
          tone(9,Notas[((int)TempInt)],500);
          delay(500);
        }
      }

  } //Here the loop() end

//This function i want to run it asyncronously
 void setForPop(){
    if(itPopUp){
      itPopUp = !itPopUp;
    }
    else{
      itPopUp = !itPopUp;
    }
 }

You will not have full parallel execution in an Arduino (only one CPU).

You might do multi-threading by implementing a small OS (e.g. FreeRTOS)
Or write your own task scheduler.
Or even just do state machine looping forever checking if push or pop has to be executed.
Last and preferred solution: I would consider running the normal Push task always and execute the Pop task (function in fact) using interrupts.


USB Communication like serial RS232 with an Attiny Basically I want to use an Attiny running an Arduino boot loader as an usb device. I'm not sure how to even start or what phrases to search for.

So here's what I ultimately wish to do.

Load a listener like that of an RS232 serial communication program
trigger pin states based on received commands
plug the Attiny directly into a windows environment USB port for
communication.

I understand that this will require some kind of driver to do this but i don't know what. I do have experience with serial port communication using Visual Studio C# as well.

Assuming what I would like to do is possible, im looking for pointers in how to make the Attiny can be seen by windows.

Generally there are (or could be many) USB Devices and (only one controlling) USB Host.  The differences are discussed in this stackexchange.com question. Briefly, USB Hosts are usually very complex hardware and software devices that may know about many many different types of peripherals.  They are usually only found on computers.  USB Devices are usually dedicated peripherals.  They only need to know about them selves.  Many people do not realize that there are many protocols built into USB.  These are normally called Device Classes.  The USB Serial Protocol (or CDC) is one of dozens of Device Classes.

So, assuming you want a build a Serial Port USD Device, you would first need a processor with built in USB Device hardware.  (There are likely some project out in the wild that have implemented this feature using software. It might be a good experience.  But for practical purposes it is usually better to use hardware for this.)  The next feature you need to implement is a software USB Device driver.  This is not trivial.  But is much simpler than the USB Host software.  The next feature you need to implement the serial protocol inside the USB protocol.

In the real world, the USB code, even for a USB Device, is complex enough that most developers use the USB code provided by the processor manufacturer.  This is very common as most manufacturers want you to use their hardware and provide the USB code for free. Here is Atmel's support page for CDC USB (serial port) support. (Of course, Atmel makes the processor found in most Arduino boards.)

Thus far this answer has been general and is likely difficult to implement in a practical sense.  A more turn key solution is to use an existing platform which contains a USB CDC Device. The Arduino Uno comes in several versions.  One has a USB CDC chip made by FTDI.  Another has a 2nd processor programmed specifically to handle USB CDC type communications. Either version provides a USB CDC interface used for programming.  I believe this web page explains how you can also use this port to communicate with your sketch.


Adafruit Huzzah ESP8266 Battery Power issue I'm trying to connect a ~5.5V (2 x 3V coin cells in series, but their voltage drops a little) to the VBat (or V+) of my Adafruit Huzzah ESP8266 module (not the black Feather one, the smaller blue one: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/pinouts)
Whenever I do that the voltage output from the 3.3V pin drops to ~0-1 V and thus the ESP stops working.

However when I use the FTDI cable (3.3 V) and connect it to my laptop, there is no problem, I get almost 3 V.

I also added a 1000mF capacitor to smooth out voltage signals and actually that also helps to increase the volt a little (without it I get almost a 0 V on the 3.3V output)

Any ideas?

After tinkering more, I figured out that the Huzzah module is happy to take in up 4.5V via a 3 AAA battery cell so I guess it's ok up to 5V since my previous battery input was over 5V.

That's a little weird considering that in Adafruit's page, it says

  ..to make it easier to power, we put a high-current-capable 3.3V
  voltage regulator on the board. It can take 3.4-6V in but you should
  stick to 4-6V since the ESP8288 has high current usage when WiFi is
  on.

Hope this may help someone else.


Problem Uploading to arduino nano (atmega 328p) I am using Arduino 1.8.1 and arduino nano (mega 328p) and ftdi driver.
In device manager it seems no problem, because it is detected as COM99. But it says a problem while uploading to the board as picture given.
Please Helpp..

Looking at the error in the end about the invalid library, it seems a configuration problem and not a communication problem.

Try:

Close and reopen the Arduino IDE (and check again)
Remove the library and add it again (in the Manage library options in the menu), close/reopen the Arduino IDE (and check again)
Reinstall the Arduino IDE (and check again)


Why Windows 10 does not see Nodemcu device? I am using a Windows 10 laptop. Behind the nodemcu it says that download CH340G driver.
I already had arduino ide and the esp libraries were already
installed because i was using a esp8266 01 device before.
I bought a Nodemcu i downloaded the driver for it CH340G driver.
When i install the driver it says that The drive is successfully
pre-installed in advance!
When I plug my Nodemcu to my computer with a new cable blue lights
come from the board and it stops. And windows doesn't make a sound
which indicates that it sees the device.
I don't think the nodemcu is the problem. How do i fix this?

Read through https://stackoverflow.com/questions/43007501/nodemcu-not-detected-by-computer#:~:text=I%20had%20to%20install%20the,Afterwards%2C%20it%20worked.&text=For%20future%20people%20with%20this,and%20it%20wouldn't%20detect. and  also search few ways to remove oxidation from pins like using autosol (I have never used it ) . Try uploading code through FTDI modules or just get it replaced.


DT-06 WIFI. How to program with Arduino Uno I have a DT-06 wireless WiFi. I can connect using my phone but I cannot access 192.168.4.1/status.html or /wifi_set.html like in the tutorial

I put this module in wiring with Arduino Uno on 5v. I notice that the LED is low lighting until I put pin state in GND. Then I get full power red led. I put RX module to TX Arduino and TX module to RX Arduino but i can not access it using Arduino.

How can I program this module or how can I access? Any tutorial links are welcome.

Thanka. Sorry for my English.

L.E.

Module RX - Arduino TX
Module TX - Arduino RX
Module VCC - Arduino 5v
Module GND - Arduino GND
Module STATE - GND

My module has a red led on it. This led is low lighting until i put pin STATE in GND. After that the red led is full lighting.

After i put VCC and GND i can "see" my module using my phone wireless connection

Are you wiring it to Arduino pins 0 & 1? These are hard-wired to the other processor on the Arduino board that handles USB to/from your PC. There may be interference with the DT-06 unless you disconnect from your PC after upload. But then you'll need an alternate source of power to the Arduino.

You can pick another pair of pins and use the SoftwareSerial library (up to 9600 baud) to talk to the DT-06. Make sure Arduino and the DT-06 use the same baud-rate. You may have to experiment to find what baud-rate the device has now, in order to set it to 9600.

Update:

  Do i have to use any resistence?

Two sites I looked at described the DT-06 voltage requirement as:
"Working voltage: 4.5V~6.0V, TTL working voltage: 3.3V (compatible with 5.0V);", so you should be OK without voltage divider resistors.

  And what settings to make in arduino IDE before uploading code?

You won't need to change your IDE to upload code to the Uno.


DHT11 is returning nonsensical values I am trying to get humidity and temperature readings (eventually to trigger a misting system), but the values keep returning as 0C and 0%humidity (in general).  Originally, I was using an am2320 sensor and using the analog pins.  Here, I used the following code:

#include "dht.h"
#define dht_apin A2 // Analog Pin sensor is connected to
#define MIST 7
#define LIGHT 2

dht DHT;

void setup(){
 pinMode(MIST, OUTPUT);
 pinMode(LIGHT, OUTPUT);
  Serial.begin(9600);
  delay(500);//Delay to let system boot
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");
  delay(1000);//Wait before accessing Sensor

}//end "setup()"

void loop(){
  //Start of Program

    DHT.read11(dht_apin);

    Serial.print("Current humidity = ");
    Serial.print(DHT.humidity);
    Serial.print("%  ");
    Serial.print("temperature = ");
    Serial.print(DHT.temperature);
    Serial.println("C  ");

    delay(5000);     //Wait 5 seconds before accessing sensor again.

  }

  //Fastest should be once every two seconds.

// end loop()
}

Thinking the sensor may have not been working, I tried using a different sensor (DHT11), and following the tutorials got the same result using this code:

#include <dht11.h>
#define DHT11PIN 4

dht11 DHT11;

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

}

void loop()
{
  Serial.println();

  int chk = DHT11.read(DHT11PIN);

  Serial.print("Humidity (%): ");
  Serial.println((float)DHT11.humidity, 2);

  Serial.print("Temperature (C): ");
  Serial.println((float)DHT11.temperature, 2);

  delay(2000);

}
// end loop()

The Arduino is being powered by a wall wart and is also connected to my computer via USB (I read that sometimes the USB doesn't supply enough power).  The weird part is that for about 1 minute I got reasonable results (humidity ~50%, temp 22C).  Then, I tried adding an if loop to turn on an LED if the humidity dropped below 60% (thinking I could use the same code to operate a relay to turn on a misting system).  The LED lit up, but the readout went back to the 0%humidity and 0C.  I have since deleted this loop but cannot seem to get reasonable measurements.  If I change the signal pin, I sometimes get a new readout 255% humidity and 255C, but I haven't been able to repeat this reliably.

For the wiring:  S to pin, + to 5V, - to GND

Note:  I have tried every analog pin and "regular" pin, so the code may designate something that is different in my picture.  When testing, I have triple checked that the signal pin in the code is correct for my wiring configuration.  I've also tried with a different Arduino with the same result.  I'm pretty new at this, but the code is pretty much copy-paste and there are only 3 wires.  I've read that there are many DHT libraries, so I'm thinking my issue has something to do with that, but I have no clue how to judge the appropriateness of a library for my application.

[[[[[[[[[[[[p

You need to add the following line of code in the setup() function:

    dht.begin();


Is there any way to group variables like group.variable as you can in Java/Delphi I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like
c = A.Ux + B.Uz;
Where A&B have various parameters Ux,Uy,Uz etc
In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.

Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong.
Thanks in advance, Brian

What you are looking for is a struct:

struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

Then:

struct foo A;
struct foo B;

And:

A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:

// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

Or:

// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

You can read more about structs here.


multiple RC522 RFID on arduino yun I was trying for one month to make multiple RC522 rfid readers work together on SPI on an arduino yun, one works fine, but if I plug 4, each with a specific slave select, only one, sometimes 2, sometimes none are working.

The library i use is RFID.h (i think the miguelbalboa one) , but I had the same results with MFRC522.h wich have a specific readUidMultiReader so I dont think my code is at fault.

Searching for this issue, I found this question wich is basically my issue, as I suspect the readers I bought are not supporting multidrop. These readers dont work either.

I read about solutions using multiplexers for SPI lines, tristate buffers on miso lines and/or diodes but these are workarounds, and there should be a more straightforward solution.

Also I tested with no resistors most of the time, but tried putting 10kΩ from all MISO to 3v3, no change, as i really dont understand what their use are, even if I feel they could be mandatory.

I am using a yun for the builtin ethernet, because I tried nanos with ethernet shields and again the shields are ignoring the Slave select and thus not working with spi multidrop, so each time I plugged the shield on nano, even not using it, rfid stopped working.

I suppose that digital output power from yun is insufficient to drive all four readers - so, you need to add some digital buffers to MOSI, SCK, and RST lines.

74LS07 digital buffer:


Infrared TV Remote to Arduino On the hardware side of things, what is involved in making the Arduino receive signals from a TV Remote? What kind of infrared receiver is needed? Do TV remotes use some kind of channels, encoding, or encryption requiring special receivers or else additional programming work to decrypt the signals?

The most common (not sure what others are used) carrier frequency is 38khz. You need an IR receiver tuned to that frequency to get the signal from the remove. See this page for way more information.

There is no encryption or special receivers needed as long as the carrier frequencies match.

That's really all the hardware you need. On the software side of things, you read this signal and decode it. There's a neat little library for doing exactly that. It's called Arduino IRemote.

It even has an example sketch which tells you just what the decoded value is of whatever button you pressed so you can use that in your other programs.


Bluetooth shield/module for file transfer? I'm currently working on a project that requires to display images on a touchscreen on my arduino. These images are neither stored in arduino nor any memory card. I want to be able to send the images via Bluetooth from an app and display it on the touchscreen. The problem is I couldn't find a good and solid Bluetooth shield or module that provide file transfer via bluetooth from an iOS app to arduino. If you can name a few bluetooh shields or modules that'd be great. In the thread below, someone claimed hc-05 works. Can anyone support that claim? Thanks.
http://forum.arduino.cc/index.php?topic=208306.0

I would use an HC-05 (or HC-06 - there seems to be little difference) - You will need to do your own file transfer protocol - for small images, zmodem or xmodem (usual file-over-serial) are probably completely overly complex. You would also need your own app for the phone.

Alternatively, you could use a network (ethernet or wifi) addon on your arduino - I think I read the Arduino Yun has built in ethernet and wifi.http://arduino.cc/en/Tutorial/WebServer has a webserver, this could be adapted to accept uploaded files. You can then use a webbrowser on your phone (or indeed anywhere else!) to send the files. If you want to send from outside your local network, you may need to set up port forwarding on your router (google: port forward) - the port you want to forwards is 80.


Solution to interrupt Arduino every n seconds I'm a very beginner with electronics and of course with Arduino. Actually I've been in the software field (.NET) for the past 12 years. I am trying to develop a simple system to run for longer using Arduino Nano. Longer means roughly it could be for years continuously, expecting normal wear and tear.

So what I understood is Arduino loop always executes based on any values from sensors while in the loop. And also Arduino has some interrupt mechanism too.

But since the looping system feels pretty awkward for some situations, I tried to stop the loop using exit(0); inside the loop. So loop will stop  after the first execution.

I am trying to build an external simple interrupt hardware system (like any timer object in software) which interrupts Arduino in a specified interval, say 20 sec. So when that interrupt on that particular pin occurred we can call some function there to do the job and that's all from Arduino side and it can go back to sleep.

So I believe this will reduce the load on Arduino and of course since no looping it will not get heated at all. How can we make such a system (external timer) to interrupt Arduino in specific intervals? This is just a theory in mine, not an idea how to implement it in electronics.

How can I achieve this above scenario?

So, since you're coming from the application domain there are some things you might want to consider:

Make sure to always stay inside the super loop. With an Arduino or any other Microcontroller (not using a RTOS) you do not have anything defined that's going to happen after the superloop. Everything that happens after this loop is basically undefined (it typically is a reboot or jump to a default interrupt handler but may also be a lockup). Simply telling the processor to "exit" will .. well, exit - but you have no idea where it's going after that. To allow for interrupts and further execution of your main code, you need to have your processor in a defined state (and that basically is the super-loop). as a comparison with your PC, after you exit a thread, the operating system will take over. On your Arduino there is no such concept. The super-loop IS your OS (well, at least it's some minimum implementation of a non-preemptive scheduler).
If you want to have only interrupt actions active while the processor is using only little power, you will need to use the processors sleep modes. These are modes, where special functionality is disabled but which keeps the processor alive or in some idle mode where it's actually just waiting. Whilst the Arduino may have various sleep modes, none of them are what can be achieved with other architectures, such as the MSP430 platform or some SAMxL platform. Those are dedicated as low power processor and provide the necessary deep sleep modes.
When using a deep sleep mode, it depends on the actual sleep mode which interrupts can wake the processor. Typically for the deepest sleep modes, only few interrupt sources will actually wake the processor up as all other peripherals are inactive either because their clock was gated or power was turned off for that function block.
You will always have some power drain for the processor but keep in mind that it's not only the processor which will require power. At some point, you have leakage currents through your capacitors/resistors and other ICs on your board which require power as well. When you're talking about "years", you will also need to account for the battery discharge as well. No battery is perfect.
Jack Ganssle is probably well known for his insight into anything related embedded, but he explicitly wrote some articles for ultra-low-power systems. You must read those if you want to start somewhere. While having the software side covered using low power techniques you will also need to tackle the hardware side, yet as I said - the Arduino wasn't made for such tasks even if it provides some basic sleep modes.


Need help with calculator logic I am trying to build a calculator with an Arduino, an LCD display, and a keypad. Getting inputs from the keypad is not the issue. Before I can add, subtract, multiply, or divide any two numbers, I want to make sure the calculator registered the given number. I am trying to program it (so far) so that I type in a number and press enter (the @ sign I assigned to my keypad) and the LCD prints out that number. As you will see, I attempted to devise a logic mechanism for the Arduino to recognize the typed number.

I thought since as you type more numbers the value of the first number typed increases by 10 fold each time (if you start by pressing 4 then if you press another number such as 5 following it, that 4 will become 40, and 400 if another number is pressed, etc...) I could multiply that number (and every following number) by 10, 100, 100, etc...

But it doesn't work and I need help so that the number can be collected by the Arduino.

Here's my attempt at it:

    #include <LiquidCrystal.h>
    #include "Arduino.h"
    #include "Keypad.h"

    int count = 0;
    int row = 0;
    int column = 0;

    //const int buzzer = 0;

    int value1;
    int value2 = 0;

    int spot1 = 0;
    int spot2 = 0;
    int spot3 = 0;
    int spot4 = 0;
    int spot5 = 0;
    int spot6 = 0;
    int spot7 = 0;
    int spot8 = 0;

    LiquidCrystal lcd(1, 2, 3, 4, 5, 6 );

    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] = {10, 9, 8, 7}; //connect to the row pinouts of the
    keypad
    byte colPins[COLS] = {13, 12, 11}; //connect to the column pinouts of
    the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS
    );

    void setup() {
      //pinMode(buzzer, OUTPUT);
      lcd.begin(16,2);
      lcd.print("---Calculator---");
      delay(2000);
      lcd.clear();
      lcd.print("Value1: ");
      lcd.blink();

    }

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

if(key != NO_KEY){
  lcd.print(key);
  if(key != '%' && key != '@'){
    count++;
  }
  else if(count == 1){
    spot1 = key;
  }
  else if(count == 2){
    spot2 = key;
  }
  else if(count == 3){
    spot3 = key;
  }
  else if(count == 4){
    spot4 = key;
  }
  else if(count == 5){
    spot5=key;
  }
  else if(count == 6){
    spot6=key;
  }
  else if(count == 7){
    spot7=key;
  }
  else if(count == 8){
    spot8=key;
  }

  if(key=='@'){
    if(count == 1){
      value1 = spot1;
    }
    else if(count == 2){
      value1 = (spot1*10)+(spot2);
    }
    else if(count == 3){
      value1 = (spot1*100)+(spot2*10)+spot3;
    }
    if(count == 4){
      value1 = (spot1*1000)+(spot2*100)+(spot3*10)+spot4;
    }
    if(count == 5){
      value1 = (spot1*10000)+(spot2*1000)+(spot3*100)+(spot4*10)+spot5;
    }
    if(count == 6){
      value1 = (spot1*100000)+(spot2*10000)+(spot3*1000)+(spot4*100)+(spot5*10)+spot6;
    }
    if(count == 7){
    }
    if(count == 8){
    }
    lcd.print(value1);
  }

  if(key  == '%'){
    count = 0;
    lcd.clear();
    lcd.print("Value1: ");
    lcd.blink();
  }
}

}

PS: If you know any better way to accomplish this goal, I would love to hear it.

if(key != '%' && key != '@'){
  count++;
}
else if(count == 1){
  spot1 = key;
}
else if(count == 2){
  spot2 = key;
}

You've got a problem here.  If key isn't '%' and isn't '@' then you increase count but since all the rest are else if to that then it skips over all of them and never actually puts the digit int the spot.


How do you wire a ssr relay to a arduino nano I am trying to wire a fss1-102z 5v ssr relay to my arduino nano but i cant get it to work here is my circuit. It stays stuck on and i cant get it to turn off.

Bluetooth control code

char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT

    Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
    ;
  }
  val = Serial.read();         // read it and store it in 'val'

  if( val == 'a' )               // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2
  }

  if( val == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
  }

  if( val == 'b' )               // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3
  }

  if( val == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
  } //else (ledpin = 3, LOW)        //set led pin 3 to low state

  if( val == 'C' )               // if 'C' was received led 2 on for 1 second
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'D' )               // if 'D' was received led 3 on for 1 second
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 3
  }

  if( val == 'E' )               // if 'E' was received led 2 on for 5 seconds
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'F' )               // if 'F' was received led 3 on for 5 seconds
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);       // turn Off pin 3
  }

  if( val == 'G' )               // if 'G' was received turn led pin 2 on for 500ms then switch off and turn on pin 3 for 500 mili seconds then off
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'h' )               // if 'h' was received switch off all pins
  {
    digitalWrite(ledpin = 13, LOW);    // turn Off pin 13
    digitalWrite(ledpin = 2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, HIGH);      // turn Off pin 3
}

  if( val == 'H' )               // if 'H' was received switch pin 2 on and off 1000 times

  for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin = 2, HIGH);  // turn ON pin 2
   delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin = 2, LOW);  // turn Off pin 2
   delay (1000); //wait 1000 mili seconds

  }

}

According to its datasheet, the FSS1-102Z doesn't work with DC-voltage. Also the minimal voltage required is 50VAC. Here is the excerpt from the datasheet: