The working of a MFRC522 and its Interface protocols? I've actually messed up and posted into the stackoverflow site, even though I'm probably not meant to. I've been given this datasheet, but even though it does explain somewhat how each host interfaces works, it does not fully answer the questions I have at the moment and I probably don't even know what I'm doing in the first place, hence I'm giving this question another shot in the right place.

I've enrolled recently into a programming course, and one of the subject seems to be embedded software development revolving around an Arduino. Now, I'm tasked with explaining to the class how the MFRC522 works and where it might be applicable, but before all that, I probably am lacking the basic knowledge before I can proceed with my work.

I have here the image of the pinout from a MFRC522 and I have the following questions:

Theres UART, I2C and SPI. Are they all separate communication protocols or are they all involved somehow with each other on this device? If I plan to use only UART for example, is it possible that I just only use the RX and TX?
Are there restrictions as to which pins on the Arduino or the MFRC522 I could possibly use, depending on the protocol or circumstances? I can see in the datasheet the pins D1 to D7 being referenced, but I cannot find it anywhere on the MFRC522 itself.
In case they are separate protocols, I would like to know how each protocol is applicable for this specific device? Like a general idea as to why a protocol is suited for a certain every day device we have been using.
The device itself uses only 3.3V, but is it also 5V resistant? Like, will plugging it into a 5V fry the circuit board or will it work just as fine?

Thanks everyone for your time.

Let's have a look at the datasheet of that chip:

Paragraph 8.1 says

  The MFRC522 supports direct interfacing of hosts using SPI, I2C-bus or serial UART interfaces. The MFRC522 resets its interface and checks the current host interface type automatically after performing a power-on or hard reset. The MFRC522 identifies the host interface by sensing the logic levels on the control pins after the reset phase. This is done using a combination of fixed pin connections.

But it seems that on this specific board the control pins are preconfigured for SPI. But, the supporting library only supports SPI so I guess that's OK. For other applications the control pins will be connected differently, and the pins will take up an i2c or serial async role. Applications for the other interfaces include microcontrollers without an SPI interface but with an i2c interface, or eg general purpose computers that have easy access to serial async interfaces, like PC's

the pin names D1-D7 in the datasheet are not related to the Arduino's pins with the same names, that's just a coincidence. If you use the aforementioned library, the Arduino pins to use are documented:

     * Pin layout should be as follows:
     * Signal     Pin              Pin               Pin
     *            Arduino Uno      Arduino Mega      MFRC522 board
     * ------------------------------------------------------------
     * Reset      9                5                 RST
     * SPI SS     10               53                SDA
     * SPI MOSI   11               51                MOSI
     * SPI MISO   12               50                MISO
     * SPI SCK    13               52                SCK

what the device will tolerate in terms of voltage on its pins is documented in chapter 11. Absolute max on most pins is 4.5 V, so the chance that 5V will fry the component is so high you probably don't want to try.

I think this is your board, and luckily they include a schematic on that page:

Here's it clearly visible that pin 1 is connected to ground, and pin 32 is connected to 3.3V, which shows that it's indeed hardcoded to SPI mode.


How to use 3 digital input pins on Arduino Uno for frequency inputs and total the output? I am working on a Arduino tachometer that reads the RPM of a BLDC motor. The motor circuit does not use the hall sensors so I would like to use them for RPM sensors. I have already hooked up an Uno board using one pin as an input with the internal pull up enabled and it works fine.The reason I want to use all 3 hall sensors is to increase the pulse count per revolution to steady the reading on my LCD display at lower speeds.
I have been searching for information on how to read 3 inputs, and totalize the pulses for this purpose but have not been able to find the information.

Assuming that only one sensor will trigger each time then (as jsotola suggested) tie them together and connect the common output to an interrupt pin. Arduino UNO has interrupt functionality on pins 2, 3.
As an example for counting the pulses using pin2 on falling edge (modified from https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/):
const byte interruptPin = 2;
volatile int numPulses = 0; // change type of variable according your needs

void setup() {
    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), sumPulses, FALLING);
    Serial.begin(9600);
}

void loop() {
    Serial.println(numPulses);
    delay(500);
}

 void sumPulses { // keep the ISR as short as possible
    numPulses++;
 }


Why do I get access denied when I do have mysql root user added to grant all privileges? I am using the below mysql example sketch to upload data directly to mysql db.

#include "SPI.h"
#include "Ethernet.h"
#include "sha1.h"
#include "mysql.h"

/* Setup for Ethernet Library */
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 1, 177);
IPAddress server_addr(192, 168, 1, 3);
//char server_addr[] = "192.168.1.3";

/* Setup for the Connector/Arduino */
Connector my_conn; // The Connector/Arduino reference

char user[] = "root";
char password[] = "secret";
char INSERT_SQL[] =
 "INSERT INTO test_arduino.hello VALUES ('Hello, MySQL!', NULL)";

void setup() {
  Ethernet.begin(mac_addr, ip);
  Serial.begin(9600);
  delay(1000);
  Serial.println("Connecting...");
  if (my_conn.mysql_connect(server_addr, 3306, user, password))
  {
    delay(500);
    Serial.println("Connection Successfull,inserting to database.");
     /* Write Hello, World to MySQL table test_arduino.hello */
     my_conn.cmd_query(INSERT_SQL);
     Serial.println("Query Success!");
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
}

I am getting the error in serial Monitor:

  Connecting...

  Error: 76 = Access denied for user
  'root'@'192.168.1.177' (using password: YES).

  Connection failed.

even when I have all prvialages on root user for the ip of client !

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.177';
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT host FROM mysql.user WHERE User = 'root';
+---------------+
| host          |
+---------------+
| 127.0.0.1     |
| 192.168.1.177 |
| ::1           |
| localhost     |
| raspberrypi   |
+---------------+
5 rows in set (0.00 sec)

I ran the following query :

mysql> SELECT SUBSTRING_INDEX(USER(), '@', -1) AS ip,  @@hostname as hostname, @@port as port, DATABASE() as current_database;

and got the below result !

+-----------+----------+------+------------------+
| ip        | hostname | port | current_database |
+-----------+----------+------+------------------+
| localhost | ceres    | 3306 | test_arduino     |
+-----------+----------+------+------------------+
1 row in set (0.00 sec)

however I am trying to access the test_arduino database from a different IP other than the one mentioned above, does that mean where it says localhost, it is supposed to have 192.168.1.177 as well ? if so How do I insert ip to database test_arduino ?

then what am I missing ? please help.

I finally figured out

By default it may proabbly have an IP address 127.0.0.1 bind to the 3306 port . This won't let your Arduino Ethernet shield connect to mysql server running on a different machine. In my case, I have mysql server running on raspberry pi 3, and it has IP 192.168.1.145. So for arduino to push directly to databse on remote mysql server, you should have mysql server IP 192.168.145 bind to 3306 port of mysql server running on it. So that MySQL server is visible to remote client on local network on which your arduino Ethernet shield is connected to via LAN.
Then you login to mysql server , and create a user :

CREATE USER 'myuser'@'192.168.156' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then you grant privileges as shown below.

GRANT ALL ON *.* TO 'myuser'@'192.168.156';
GRANT ALL ON *.* TO 'myuser'@'%';

Important Note:  the ip address shown in above mysql queries 192.168.156 is the ip address of my ethernet client establishing connection with database on mysql remote server.

Thats it.


Why I am connecting positive wire in the circuit? I have constructed a simple fade in and fade out circuit similar to given on this website https://roboindia.com/tutorials/arduino-analog-output-led-fade Now I am connecting a wire from 5V power pins to +ve side line, but i don't know why I am doing this because when I remove this wire or connect it to 3.5V pin the led is still running fine. Also as side lines are connected horizontally there is no other further connection given to the +ve wire. Can you tell me why I am joining the wire?

This is indeed not needed. As you can see in the diagram, the horizontal line which you connected the 5 V pin to.

The horizontal line of holes just above the red horizontal line) are connected. However, since it only connected to the 5V pin of the Arduino, the all pins on that horizontal line have 5 V, but since there is nothing connected to it (thus no closed circuit), the effect is zero.

The reason why the connection is made (the wire from Arduino to 5V), is that it is 'default' to connect both GND and 5V (or 3.3V) as a starting point. It is easy to forget later and than no current will flow when you connect something to the +5 V horizontal line of pins.

Btw, the 3.5 V pin you mention, is 3.3 V, not 3.5 V.


Sketch talks to Android via BLE on Serial2 but times out after 5 seconds when Serial cable disconnected or not present From an Android phone I am using the "Serial Bluetooth Terminal" app to communicate to an Arduino Mega 2560 with a Bluetooth Low Energy HM10 (Jaycar XC-4382) module connected via Serial2.

If the physical USB serial cable (Serial) is connected to Arduino the very simple sketch below works fine and runs continuously. When the cable is disconnected mid sketch or the power is cycle without the cable connected the sketch will run for about 5 seconds and then stop.

How can I prevent the sketch from timing out when the serial cable is disconnected?

int counter = 0;

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

void loop()
{
    Serial2.print(counter); Serial2.println();
    delay(1000);
    counter++;
}

The workaround is to switch to using SoftwareSerial, see code below. Data is continuously sent via Bluetooth from Arduino Mega to Android with or without the usb cable connected.

#include <SoftwareSerial.h>

// Connections
// Arduino HM10
// MEGA
// ----    ----
// 3.3v    VCC
// GND     GND
// 12      RX
// 13      TX

SoftwareSerial bte(12,13);    // RX, TX use (2,3) for UNO
int counter = 0;

void setup() {
  // set the data rate for the SoftwareSerial port
  bte.begin(9600);
  bte.println(counter);
}

void loop() { // run over and over
  bte.println(counter);
  counter++;
  delay(1000);
}


Arduino Yun - not enough i2c & interrupt pins? I'm trying to build a small personal weather station. The rain sensor, and wind speed sensor use interrupts. The barometric sensor uses i2c SDA and SCL.

Reading the Arduino Yun manual, it says there are 5 interrupt pins, but 2 of them are SCL/SDA (pins D2 and D3), and 2 of them are serial comms between Linio and the 32U4 (pins 0 and 1).

This leaves me with 1 interrupt pin left (pin 7).

Is there a work around to get my 2 digital sensors AND SDA SCL pins connected?

If I do use pins 0 and 1 (Linux serial), what do I risk? I will need to use the Bridge to relay information to the internet.

OR the interrupt lines together so that you only need 1 external interrupt. Then when an interrupt is triggered, poll the devices until you find the one that triggered the interrupt. If the interrupt outputs are open-drain then you can wired-OR them together, otherwise you will need something like the 74LVC32 to OR the push-pull outputs together.


Making profit from Arduino I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

The Arduino itself is open, and you can use it to make commercial products.

Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.

Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


Arduino Pro Mini RESET button suddenly stopped working I am powering my Pro Mini(3.3V version) using an external battery (~6.5V 700mA) . I used to connect it to the RAW and GND pins on my pro mini and everything ran fine.

Today when I powered up my Arduino again, it didn't light up. A quick glance told me that I had connected the battery to the RST and GND pins mistakenly. Quickly pulled them out and put them into place, the Arduino worked perfectly until I discovered that the RESET button is no longer working. Without the RESET button I can't upload anything to my board.

Tried connecting the RST and GND Pins, didn't work.

The board is working fine though, I discovered a new procedure to upload as follows-
NOTE: I use the USB-to-TTL adapter by DSUN (picked up at a local electronics store).

Connect the RX, TX and GND Pins from the adapter to the Pro Mini.
(The green LED on the Pro Mini lights up dimly)
Upload the sketch from the IDE.
As soon as the IDE shows "Uploading", connect the +5V pin from the adapter to RAW pin on Pro Mini. Upload goes fine.

The above procedure is working just fine, and the board as well. But I'd like to have my RESET button back.
So what do I do?

What do you do? You replace the chip on the board.

By pumping 6.5V through the RESET pin with no power attached you have irrevocably broken the reset pin inside the chip. Way too much current will have flowed through the internals of the pin leaking its way up to the VCC pin and then back down through the rest of the chip to ground, burning out vital parts of the internal logic of the pin.

It's dead, Jim.

Your "fix" basically relies on the fact that the bootloader runs for any kind of reset - be that a RESET pin reset or a POR (Power-On Reset).


Need Input: Wait for voltage input to begin script & when voltage maintains 0V for X amount of time Reset and wait for Voltage Input So I'm currently working on an automotive set up.

I'm using a 555 timer to emulate a turn-signal alternating voltage pulse (12V to 0V and repeat) for debugging purposes which is output to turnPin/A1.

Here's the goal: When voltage is greater than 1V arduino is to supply constant power to output pin (pin 13) until input voltage is returned to constant 0 (or end of turn signal input) for x-time or as I'll refer to as Timeout.

It seems I've gotten the constant power to apply when input is applied and then turn off constant output when voltage is back to 0V. However I'm having difficulty getting the timeout function to work properly as the LED still remains HIGH.

EDIT: I've reworked the code to use millis(); rather than purely using sensor inputs. I've also added comments to help walk you through what I believe is happened/what I want to happen.

// Constants won't change
const int ledPin = LED_BUILTIN; //using built in led + pin13
const int turnPin = A1;         // the input pin (turn signal alternating 5V/0V/5V/0V & so-forth)

// Variables will change
int ledState = LOW;             // the current state of the output pin
int prevLed = ledState;
int lastVoltage = 1;            // the previous reading from voltage source
int state = 1;                      // the current "state" (see below)
                                // State = 1++: LED OFF -- State = 0: LED ON

// The following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.

long previousMillis = 0;    //the last time the voltage reached 0
long waitTime = 100;    // the wait time

void setup()
{
  pinMode(ledState, OUTPUT);        //set output pin
  pinMode(turnPin, INPUT);          //set input pin NOTE: SIGNAL ALTERNATES
5V/0V/5V/0V & so forth to emulate a turn signal for this application
  Serial.begin(9600);               //begin serial
}

void loop()
{
  int sensorValue = analogRead(turnPin);        // Read voltage at input pin
  float voltage = sensorValue * (5.0/1023.0);   // Convert
  unsigned long currentMillis = millis();    // set currentMillis as current
 time

  if (voltage > 1)      //if Voltage greater than 1V
  {
    ledState = HIGH;    //turn led on
    state = 0;          //set state to 0
  }

  if (voltage < 1)      //if voltage less than 1V
  {
    currentMillis;      //set currentMillis as current time

    if ((millis() - currentMillis) > waitTime) // if (current time minus time voltage was less than 1) is greater than wait time
    {
        ledState = LOW;     //set LED to off
        Serial.print("OFF - TIMED OUT - WAITING FOR INPUT: ");  //output message for debug
        Serial.println(state);//current state
        state++;              //increment state (time passed)
    }
        else if ((millis() - currentMillis) < waitTime) // if (current time minus time voltage was less than 1) is less than wait time
        {
            ledState = HIGH;    //set LED to on
        }
  }
  digitalWrite(ledPin, ledState);   //send LED status to output
}

It's hard to know where to start here. :)

 if (currentMillis + 500)

OK, what is that doing? It is adding 500 to currentMillis so that will be true almost all the time.

if (status = 3)

That is assigning 3 to status and then checking if it is non-zero, which it will be (it will be 3).

int turnPin = A1;
...

  int sensorValue = analogRead(A1);

Why not write:

  int sensorValue = analogRead(turnPin);

float voltage = sensorValue * (5.0 / 1023.0);

You calculate voltage but never use it. Why bother?

  As for your question regarding if (currentMillis + 500) I wanted this statement to take the current time and add 500 to it and then check ...

OK, then this is the way to do that:

// see if 1/2 a second is up
if (currentMillis - previousMillis >= 500)
   {
   previousMillis = currentMillis;  // reset previousMillis
   ... do something ...
   }

BTW, previousMillis is also a variable you weren't using anywhere else.


Receive multiple data from arduino using String builder I am working on a small project where I have to read data from different hardware and display it on android app. I am using arduino Uno to get the values from a sensor and a motor and I use a bluetooth module to send the data to the android device. I know how to read data from motor only but not from motor AND sensor. The data displayed on the arduino can be assumed as follows:

Motor: 132

Sensor: 258

Motor: 259

Sensor: 992

So first, we will read the value of the motor then the sensor then the motor and so on. Here is part of the code where I used handler and string builder to read data from the motor. How to modify the code in order to read from BOTH the motor and sensor and keep the updating the values?

Code:

Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        motor.setText(sbprint);             // update TextView
                    }

                    break;
            }
        };
    };

You can convert each value to string before sending to bluetooth using string.contain("string"), like this:

if (sbprint.contains("C"){
    temptv.setText(sbprint);}
if (sbprint.contains("H")){
    humidtytv.setText(sbprint);}


Sketch stops working after ~40 minutes. Overflow? I have this simple sketch I use on Arduino Micro:

int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
unsigned long prevMicros = 0;        // will store last time LED was updated  +
unsigned long interval =  7000000;           // lunghezza della pausa in secondi
unsigned long intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
 pinMode(fan, OUTPUT);
 pinMode(led, OUTPUT);
 prevMicros = micros();
}

void loop() {
  unsigned long currMicros = micros();

  // manage overflow? BOH
   if (ledState == HIGH && (((unsigned long)(currMicros  - prevMicros)) >= intervalON)){
     prevMicros = currMicros;
      ledState = LOW;
    }
    else if (ledState == LOW && (((unsigned long)(currMicros - prevMicros)) >= interval)){
      ledState = HIGH;//riparte
      prevMicros = currMicros;
    }

    digitalWrite(led, ledState);
    digitalWrite(fan, ledState);
}

I could use millis() instead of micro(), but I decided to keep this to shorten the overflow rate (should be 72 minutes). I shall go back to millis() once my issue is fixed.

The sketch works as expected, turning on the LED for a second every 7, but the sketch hangs after 40 minutes. Can you tell me why, and how to manage overflow properly? Why is it hanging after 40 and not 72 minutes? Thanks

When comparing time intervals, use unsigned long instead of long.

if ( ... (((unsigned long)(currMicros - prevMicros)) >= intervalON) )

The time counter overflows at some point -- micros() overflows after 70 minutes, milis() overflows after nearly a month -- but these are unsigned values.

When an unsigned value is interpreted as a signed value -- (long) instead of (unsigned long) -- then half of the values are interpreted as negative numbers. So after 40 minutes, the micros() value looks like a negative number, and the (curr-prev) >= interval comparison returns false. After 70 minutes, the micros() overflows back to 0, and the signed comparisons work as expected.

The solution is to use unsigned long for all delta-time comparisons.

This is easier to see if you consider a smaller, 3-bit number: there are 8 values for a 3-bit number. If the 3-bit number is unsigned, then the values are 0, 1, 2, 3, 4, 5, 6, 7. But if the 3-bit number is signed, then those same binary code numbers are interpreted as 0, 1, 2, 3, -4, -3, -2, -1. Same principle for int and long values, just a larger range of values.

EDIT:

Based on your comment below, I did some testing on my own hardware (Sparkfun "red board" Arduino UNO R3 clone), and added some code to help make it more testable. Some highlights:

Added a diagnostic LED on Arduino pin 9, to indicate when the timer overflow has happened (i.e. new time is less than previous time).
Added a mask to force the timer overflow to happen sooner, so I don't have to wait an hour to verify whether the code had any effect.
Calculated timeSinceLastChange and applied mask, to handle overflow.
Added TIMER_DATATYPE based on jippie's comment

The complete code:

//--- based on comment from jippie about using C++ standard width integer types
// #define TIMER_DATATYPE unsigned long
#define TIMER_DATATYPE uint32_t

//--- MarkU: diagnostic LED to indicate that timer overflow happened.
// Comment out this line for normal operation.
#define DIAGNOSTIC_LED_TIME_OVERFLOW 9
//---

//--- MarkU: diagnostic: force timer overflow to happen sooner.
// This must be significantly longer than the intervals being measured.
// Must be a binary all-1's bitmask.
// 0x3FFFFFF overflow after approximately 1 minute
// 0xFFFFFFF overflow after approximately 5 minutes
// 0xFFFFFFFF overflow after approximately 70 minutes
#define DIAGNOSTIC_TIMER_OVERFLOW_MASK 0x3FFFFFF
//---

int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
TIMER_DATATYPE prevMicros = 0;        // will store last time LED was updated  +
TIMER_DATATYPE interval =  7000000;           // lunghezza della pausa in secondi
TIMER_DATATYPE intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);

  //--- MarkU: diagnostic LED indicate that timer overflow happened
#if DIAGNOSTIC_LED_TIME_OVERFLOW
  pinMode(DIAGNOSTIC_LED_TIME_OVERFLOW, OUTPUT);
  digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, LOW);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
  //---

  prevMicros = micros();
}

void loop() {
  TIMER_DATATYPE currMicros = micros();

  //--- MarkU: diagnostic: force timer overflow to happen sooner
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
  currMicros = (TIMER_DATATYPE)(currMicros & ((TIMER_DATATYPE)DIAGNOSTIC_TIMER_OVERFLOW_MASK));
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK

  //--- MarkU: consolidate time delta calculation
  TIMER_DATATYPE timeSinceLastChange;
  if (currMicros < prevMicros) {
    //--- MarkU: handle timer overflow
#if DIAGNOSTIC_LED_TIME_OVERFLOW
    digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, HIGH);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & DIAGNOSTIC_TIMER_OVERFLOW_MASK;
#else // DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & 0xFFFFFFFF;
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK
  } else {
    timeSinceLastChange = currMicros - prevMicros;
  }
  //---

  // manage overflow? BOH
  if (ledState == HIGH && (timeSinceLastChange >= intervalON)) {
    prevMicros = currMicros;
    ledState = LOW;
  }
  else if (ledState == LOW && (timeSinceLastChange >= interval)) {
    ledState = HIGH;//riparte
    prevMicros = currMicros;
  }

  digitalWrite(led, ledState);
  digitalWrite(fan, ledState);
}


SIM808 return the same AT command I am using atmega 2560 and SIM808. When I send an AT command to SIM808 it returns correctly. But sometimes I have seen that SIM808 returns the same AT command. Sometimes it occurs due to lack of power in SIM808 and due to Serial problem. But another time I have seen that, power and Serial are ok but it returns the same AT command.
Why this type of problem occurs ?

My default modems usually echo back whatever you send.  So if you send AT it will first respond with AT followed by the OK response:

>> AT
<< AT
<< OK

Echoing can be turned off with the command ATE0 and turned back on with ATE1:

>> ATE0
<< ATE0
<< OK
>> AT
<< OK
>> ATE1
<< OK
>> AT
<< AT
<< OK


How to code 4 relays to go off in intervals and not in sequence? Code :

//FOR AEROPONIC SYSTEM WITH ROOM TEMPERATURE AND HUMIDITY SENSOR
//AND 4 GROW CHAMBERS WITH DIFFERENT SPRAYING TIME

// RELAY CONTROL
#define RELAY1_PIN 2
#define RELAY2_PIN 3
#define RELAY3_PIN 4
#define RELAY4_PIN 5

//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 6
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

//Variables
int chk;
float hum;
float temp;

void setup()
{
    Serial.begin(9600);
    Serial.println("SENSOR RUNNING");
    dht.begin();

    pinMode(RELAY1_PIN, OUTPUT);
    pinMode(RELAY2_PIN, OUTPUT);
    pinMode(RELAY3_PIN, OUTPUT);
    pinMode(RELAY4_PIN, OUTPUT);
}

void loop()
{
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (isnan(h) || isnan(t))
    {
        Serial.println("CONNECTION ERROR");
        return;
    }
    Serial.print("Humidity: ");
    Serial.print(h);
    Serial.print(" %\t");
    Serial.print("Temperature: ");
    Serial.print(t);
    Serial.print(" *C ");
    Serial.println(" ");
    delay(2*1000);
    {
        // FOR RELAY
        digitalWrite(RELAY1_PIN, HIGH);
        delay(2*1000); // wait for 2 second ON
        digitalWrite(RELAY2_PIN, HIGH);
        delay(3*1000); // wait for 3 second ON
        digitalWrite(RELAY3_PIN, HIGH);
        delay(4*1000); // wait for 4 second ON
        digitalWrite(RELAY4_PIN, HIGH);
        delay(5*1000); // wait for 5 second ON

        digitalWrite(RELAY1_PIN, LOW);
        digitalWrite(RELAY2_PIN, LOW);
        digitalWrite(RELAY3_PIN, LOW);
        digitalWrite(RELAY4_PIN, LOW);
        delay(5*60*1000);
    }
}

This code doesn't do what I want. How do I make them independent?

Here is some code that might help you; leaving out the temperature and humidity stuff:

// constants
// number or relays
const int relays = 4;

// pins for the relays
const int relayPins[] = {2, 3, 4, 5};

// relay cycle times
const unsigned long relayTimes[] = {
     5*60*1000, // 5 min
     60*60*1000, // 1 Hour
     2*60*60*1000, // 2 hours
     12*60*60*1000 // 12 hours
  };

// relay on durations
const unsigned long relayOntimes[] = {
    1000, // 1 second
    10*1000, // 10 seconds
    60*1000, // 1 minute
    60*60*1000 // 1 hour
  };

// timing for the relays
// storing the last time
unsigned long relayElapsed[] = {0, 0, 0, 0};

// state of each relay
int relaystate[] = {0, 0, 0, 0};

// helper function to process each relay
void relay_helper(unsigned long t, unsigned long &elapsed, int pin, int &state, unsigned long delta, unsigned long ontime)
{
  // depending on the state we do different things
  switch (state)
  {
  case 0: // state 0 is off, wait until time has passed
    if ((t-elapsed) > delta)
    {  // then
       state = 1; // set the state to on
       elapsed = t; // reset the time
       digitalWrite(pin, HIGH); // turn on
    }
    break;
  case 1: // state 1 is on, wait until time has passed
    if ((t-elapsed) > ontime)
    {  // then
       state = 0; // set the state to off
       elapsed = t; // reset the time
       digitalWrite(pin, LOW); // turn off
    }
    break;
  }
}

void setup()
{
  unsigned long start = millis();
  for(int i = 0; i < relays; i++) // for each pin
  {
    pinMode(relayPins[i], OUTPUT); // set it to output
    digitalWrite(relayPins[i], LOW); // and turn it off
    relayElapsed[i] = start;
  }
}

void loop()
{
  unsigned long tm = millis();
  for(int i = 0; i < relays; i++)
  {
    relay_helper(tm, relayElapsed[i], relayPins[i], relaystate[i], relayTimes[i], relayOnTimes[i]);
  }
  // do other loop stuff
}

The basic idea is that the only way to do thing simultaneously is to do things in sequence really fast, we can't use delay() because it is a busy loop, nothing else can happen during delay(), so we keep track of the time and when it is time to turn on the relay we turn it on, and when it is time to turn it off we turn if off.

Another option would be to write a class per relay:

class Relay
{
public:
  Relay(int pin, unsigned long delta, unsigned long ontime);
  ~Relay();

  process(unsigned long t);

private:
  unsigned long delta;
  unsigned long ontime;
  unsigned long last; // elapsed
  int pin;
};

Then one can create an array of these:

Relay[] relays = {
    Relay(2, 5*60000, 1000),
    Relay(3, 60*60000, 10000),
    Relay(4, 2*60*60000, 60000),
    Relay(5, 12*60*60000, 60*60000)
  };

put the code from setup into the constuctor, and the code from the helper into process, and finally call it in a loop in loop.

The first way shown is how one would do it without C++ classes, and the second way is with them!


More speed from ATMEGA328 Internal Clock I have a board that is designed and produced. It was designed to use an Atmega328 with the internal clock. There is no space on the board to place an external clock. After completing these and testing them I have found that 8Mhz is too slow to complete my main loop actions seamlessly. The main loop involved shifting data out to 20 registers. Is there any way to speed this up without going back to the drawing board on the PCB design? Can another AVR be substituted as a drop in replacement with a faster internal clock? Can the internal clock be made to run faster or doubled to achieve 16Mhz?

The application is a matrix display that has 50 columns and 7 rows. The registers are the display buffers and represent the current state of the display. Because of the multiplexing in the matrix, only 1/5 of the pixels are illuminated at any given time. In order to trick the eyes into seeing all lit at the same time the speed needs to be faster. The display flickers with the interal clock. If I connect and UNO board instead of using the on board ATMEGA328 (QFP) it works good. So the difference between 8Mhz and 16Mhz is visible. If I can double the speed of the display loop than that is a solution. Below is the loop, for reference, latchPin = 8, clockPin = 12, dataPin = 11.

shiftOut() relies on digitalWrite(), which is dead slow by AVR
standards. You could probably get a factor 5, or even 10, by
reimplementing shiftOut() using direct port
access instead.
Using SPI (as suggested in the comments) would be even faster, but you
would need to clock out of pin 13.

Edit: here is an attempt at such implementation. Note that it is
completely untested. Note also the small delay meant to avoid the thing
being too fast. You may try to play with the delay value.

#include <util/delay.h>

/*
 * Especialized and faster shiftOut().
 * This assumes no one is touching PORTB at the same time.
 *
 * dataPin = 11 (PB3), clockPin = 12 (PB4), bitOrder = MSBFIRST.
 */
void myShiftOut(uint8_t val)
{
    for (uint8_t i = 0; i < 8; i++)  {
        // Send data bit.
        if (val & 0x80)
            PORTB |= _BV(PB3);
        else
            PORTB &= ~_BV(PB3);
        val <<= 1;

        // Toggle clock twice.
        PORTB |= _BV(PB4);
        _delay_us(0.5);
        PORTB &= ~_BV(PB4);
    }
}


Arduino Simple Task - sweeping a buzzer and led, not working as expected Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

UPDATE: IT seems that there is a problem using pin 11 and 13 together but if I use a different pwm pin like pin 5. It's okay. I'm guessing that the timers used at pin 11 is connected to tone() but not sure...
I’ve encountered a weird problem with an Arduino with this simple task. It involves just a buzzer and LED and a very simple custom library that I made.
I wanted the buzzer to sweep back and forth with a specified frequency range (f1, f2), the led will also display a specific brightness (0, 50) based on the frequency being played.
The buzzer works perfectly on its own, and also the LED, but when you put them together, it malfunctions.
A more detailed explanation can be found here: https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/
And i've included all the files i've used here: https://gist.github.com/mithi/09ae419a3c7eba285221
Using this code below, commenting out line 19 with line 18 uncommented-out will make the buzzer work, and commenting out line 19 with line 18 back in will make the led work as expected. But together, the code malfunctions. buzzer is attached to pin 13 and led is attached to pin 11.
#include "SimplestLibrary.h"

Sweeper sweeper;
Buzzer buzzer;
AnalogLED led;

int f1 = 3000;
int f2 = 4500;
int f = 0;

void setup() {
    sweeper.New(f1, f2, BACKANDFORTH);
    buzzer.New(13);
    led.New(11);
}

void loop() {
    f = sweeper.Update(1);
    buzzer.Play(f, 4, 2);
    led.NewBrightness(map(f, f1, f2, 0, 50));
    delay(1);
}

From Arduino.cc:

  Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

Simple solution is to use a PWM that isn't an output from Timer2 :

Timer      OCxA pin    OCxB pin
  0           6        5
  1           9        10
  2           11       3


How to run led and buzzer at the same time? I am making a police light and siren but the delay on light (); affects the buzzers  delay tone

This is the code:

//PIN 9 - Buzzers
int f,d;
int t =0;

void setup()
{
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
}

void loop()
{
    buzzer ();

}

void buzzer () {

  for(f=635;f<=912;f++)
    {
        tone(9, f);
        delay(d);
        d=10;

        light ();
    }

    for(f=911;f>=634;f--)
    {

        light ();
        tone(9, f);
        delay(d);
            d=9;

    }

}

void light() {
 digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  digitalWrite(6,HIGH);
  digitalWrite(7,HIGH);

  delay(t);

  digitalWrite(5,LOW);
  digitalWrite(6,LOW);
  digitalWrite(7,LOW);

  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

  digitalWrite(5,HIGH);
  delay(t);
  digitalWrite(5,LOW);
  digitalWrite(7,HIGH);
  delay(t);
  digitalWrite(7,LOW);
  delay(t);

}

The following Code is not tested. You can take it as an example. If you find errors, it would be nice to report them, so I can correct my prog.

// here I just guess (10msec), I think you don't want a delay
// of 0 as in your code.
int   blinkDelay        = 10;
long  lastBlinkTime     =  0;
int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

int   patternSize     = 17;
int   actPattern      =  0;
int   delActive       = -1;

int  frequency     = 635;
int deltaFreq      =   1;
int  toneDelay     =  10;
long lastBuzzTime  =   0;

void setup()
{
  pinMode( 5, OUTPUT ) ;
  pinMode( 6, OUTPUT ) ;
  pinMode( 7, OUTPUT ) ;

  ledsOff();
  buzzer( frequency );
}

void loop()
{
  int actTime = millis();

  if ( ( actTime - lastBlinkTime ) > blinkDelay )
  {
    if ( delActive > 0 )
    {
      ledsOff();
    }
    else
    {
      actPattern++;
      if( actPattern > ( patternSize - 1) ) actPattern = 0;
      pattern( patternSequence[ actPattern ] );
    }
    delActive *= -1;

    lastBlinkTime = actTime;
  }

  if ( ( actTime - lastBuzzTime ) > toneDelay )
  {
    frequency += deltaFreq;

    if ( frequency > 911 ) deltaFreq = -1;
    if ( frequency < 636 ) deltaFreq = 1;

    buzzer( frequency );
    lastBuzzTime = actTime;
  }

}

void buzzer( int freq )
{
  //PIN 9 - Buzzer
  tone(9, freq);
}

void ledsOff()
{
  digitalWrite( 5, LOW );
  digitalWrite( 6, LOW );
  digitalWrite( 7, LOW );
}

void pattern( int num )
{
   switch ( num )
   {
      case 0:
        ledsOff();
        break;

      case 1:
        digitalWrite( 5, HIGH );
        break;

      case 2:
        digitalWrite( 7, HIGH );
        break;

      case 3:
        digitalWrite( 5, HIGH );
        digitalWrite( 6, HIGH );
        digitalWrite( 7, HIGH );
        break;
   }
}

Update

I've tested the code at home on my esplora. It worked, but not for a long time. I had to change the timing logic, by using the method millis()directly. Now it works. Below is the new code; tested this time. I also introduced some constants on top, because the their names act as documentation ;-). And I experimented with the values. The actual values are my preferences, But I'm by far no Bethoven and can not say if this relly sounds like a police siren. At least, it sounds not like a german police siren which I know better. (No I'm meither a policement nor his/her customer ;-))

Because I tested the code on my Esplora, I had to change the Pin assignments  (now out commented). In this copy I changed back to the original ones.

int   blinkDelay        = 100;
long  lastBlinkTime     =  0;
int   patternSequence[] = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 2, 1, 2, 1, 2, 1, 2 };

int   patternSize     = 17;
int   actPattern      =  0;
int   clearActive       = -1;

int  lowerFreq       = 680;
int  higherFreq      = 840;
int  deltaFreq       =   2;
int  toneDelay       =  20;
int  toneDelayOffset =  -1;
long lastBuzzTime    =   0;

int  actFreqStep   = deltaFreq;
int  actFreq       = lowerFreq;

// orig pins
int col1Pin   =  5;
int col2Pin   =  6;
int col3Pin   =  7;
int buzzerPin =  9;

// esplora pins
// int col1Pin   =  5;
// int col2Pin   = 10;
// int col3Pin   =  9;
// int buzzerPin =  6;

void setup()
{
  pinMode( col1Pin, OUTPUT ) ;
  pinMode( col2Pin, OUTPUT ) ;
  pinMode( col3Pin, OUTPUT ) ;

  // initialize LEDs off
  ledsOff( );

  // and buzzer to the act frequency
  buzzer( actFreq );
}

void loop()
{
  if ( ( millis() - lastBlinkTime ) > blinkDelay )
  {
    if ( clearActive > 0 )
    {
      ledsOff();
    }
    else
    {
      actPattern++;
      if( actPattern > ( patternSize - 1) ) actPattern = 0;
      pattern( patternSequence[ actPattern ] );
    }

    clearActive     *= -1;
    lastBlinkTime  = millis();
  }

  if ( ( millis() - lastBuzzTime ) > ( toneDelay + toneDelayOffset ) )
  {
    actFreq += actFreqStep;

    if ( actFreq >= higherFreq )
    {
      actFreqStep   = -1 * deltaFreq;

      // down sweep is slower
      toneDelayOffset = -1;
    }

    if ( actFreq <= lowerFreq )
    {
      actFreqStep   =  deltaFreq;
      toneDelayOffset =  0;
    }

    buzzer( actFreq );
    lastBuzzTime = millis();
  }

}

void buzzer( int freq )
{
  tone( buzzerPin, freq );
}

void ledsOff()
{
  digitalWrite( col1Pin, LOW );
  digitalWrite( col2Pin, LOW );
  digitalWrite( col3Pin, LOW );
}

void pattern( int num )
{
   switch ( num )
   {
      case 0:
        ledsOff();
        break;

      case 1:
        // red
        digitalWrite( col1Pin, HIGH );
        break;

      case 2:
        // blue
        digitalWrite( col3Pin, HIGH );
        break;

      case 3:
        // white
        digitalWrite( col1Pin, HIGH );
        digitalWrite( col2Pin, HIGH );
        digitalWrite( col3Pin, HIGH );
        break;
   }
}


Arduino communicate between 2 different router in different location I am on my final year project in I.T. my project is that i want to create a helicopter or quadcopter with a camera attached to it. And i want to control the copter via wifi from an android phone in another location. e.g, the copter is at home and i am somewhere else (work, university etc..). so i wanted to know if i can connect both via 2 different routers and control it and get the live video the camera is actually recording (the idea is to monitor your house when you are away). if that is possible, which arduino hardware will enable me to do that.
Thank you.

It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.

I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...


Having a problem to control digital servo with HC-06 bluetooth module There are two problems to control digital servo(HD-1810MG) and HC-06 bluetooth module connection.

When I put a specific number to servo(in the video, I put 45), it shakes too much and shows useless movements before get to the right angle. I have no clue why this happens. Should I add more code to control it correctly?

This is my code.

#include SoftwareSerial.h
#include Servo.h

Servo myServo;
int TxD = 10;
int RxD = 11;
SoftwareSerial bluetooth(TxD, RxD);

void setup() {
  myServo.attach(9);
  Serial.begin(9600);       // start serial communication at 9600bps
  bluetooth.begin(9600);
}

void loop() {
  if (bluetooth.available()>0)
  {
    int servopos = bluetooth.read();
    Serial.println(servopos);
    myServo.write(servopos);
    delay(100);
  }
}

I used Nexus 5X and apk app to pair with HC-06. It pairs well at the first time of connection, but it loose connection after servo moved once. Application said it is connected with bluetooth, but HC-06's LED is blinking(which means disconnected). How can I maintain connection with HC-06?

This is my board.

And I made apk app using MIT App Inventor 2.

I'm so new to arduino and I'm not in major of engineering. Please give me an advice!

let have a look at following line of code:

int servopos = bluetooth.read();

I think that you are thinking that if you type in 1 in your
Bluetooth application. bluetooth.read() will pass that 1 to
sevopos. But, that's what not happens. What actually happens is that it will pass the ASCII value of whatever you type in you
app, to integer. So, if you have typed in 1, it will pass 49
to servopos.

  I put 45

Now, think about it. when you type in 4 of this 45,

bluetooth.available()>0

becomes true.

int servopos = bluetooth.read();

bluetooth.read() will pass 52 (ASCII of 4) to servopos. Next,

myServo.write(servopos);

myservo will move your servo to lets say 52 degrees. and then there will be a delay.

Now, when you type in 5 of this 45, the procedure will be
repeated and your servo will be moved again by 53 degrees.

Now, you might be wondering that why 4 and 5 sepratly? Well,
all these intructution are being executed in MHzs. and secondly,
you, yourself has programmed that if loop you read just once
character. Yes, it will read character by character.

  but it loose connection after servo moved once

I think your servo is drawing too much current from Arduino Board
which results in a drop in net voltage. And hence your HC-05 (kind
of) tuns off. This is what happens most of the time.


Is my Arduino fried? I am worried that my Arduino is fried from a previous attempt at connecting a servo to it. To test my concerns, I changed the circuit to see if Arduino could even power a simple LED:

Code:

int led = 13;

void setup() {
    pinMode(led, OUTPUT);
}

void loop() {
    digitalWrite(led, HIGH);
    delay(4000);
    digitalWrite(led, LOW);
    delay(4000);
}

Wiring:

In that pic, the Arduino is connected to a 9V battery. When I test the purple connections with my multimeter, the power bounces between ~5V and a weird 1.65V value every four seconds. I assume thats power being applied to the output pin in keeping with my code.

However, the LED does not light up. Any ideas as to what could be going wrong or how I could troubleshoot?

As noted in the previous answer, being able to upload a new sketch indicates an Arduino is ok in general – in particular has a functioning CPU – but of course that does not test all features.  For example, individual inputs and outputs can be damaged.

You can easily change your sketch so that it drives some range of outputs, as shown below.  Thereafter, try moving the red wire (that now connects on 13) to some other of the outputs in the selected range.

enum { LedLo=2, LedHi=20}; // Set lo and hi limits of range

void setup() {
  for (int led=LedLo; i <= LedHi; ++i)
    pinMode (led, OUTPUT);
}

void loop() {
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, HIGH);
  delay(4000);
  for (int led=LedLo; i <= LedHi; ++i)
    digitalWrite(led, LOW);
  delay(4000);
}


Any way a GSM sim 900 can still work (USA)? so I’m pretty new to arduino and have been working for weeks on a GPS tracker using a sim 900 and a knock off neo 6M. All my code seemed to be working but for some reason I could not get the sim900 to establish a connection. Took me long enough to find out 2G carriers have been pretty much shut down. This is for a project and I don’t have time to start over with a 4G shield. Are there any cell carriers that still support 2G? What are my options? I don’t know what to do
Edit: more detail, I’m using the sim 900 to send an sms with a gps location

Somehow I got a connection! I live in PA but when I went to Boston for school I got 2G service. Maybe carriers haven’t fully shut it down.


Bicycle Tail Light project For my college course we currently have to carry out a project of our own choice.
I chose to make a Tail light system, with strobing indicators, fog-light and brake-light.

The lighting uses Neopixel strips and rings, with the indicator sections consisting of 2 neopixel strip 6 (in parallel); the fog light using a neopixel jewel; and the brake light using a neopixel ring 16.

The indicators need to strobe outward from the centre of the device (in the desired direction, left/right) based on a button input. The fog-light should turn on when the device is activated by switch, and the brake-light will turn on when receiving an input from another button.

I've only ever coded using Python during GCSE and can't wrap my head around Arduino code. Currently using tinkercad for creating this as I don't have any arduino kit, and don't want to spend out the money on unneeded components.

Any help is appreciated, and if a link to the tinkercad circuit would be useful let me know.

Break down your project into steps, both hardware and software, and tackle a step at a time.

First do a block diagram of the system, showing the different components, the layout of the control buttons, etc.

Then map out the desired behavior, perhaps using a flowchart. What should it do when you first turn it on? How will it respond to different button inputs? Will it continue to flash in the current pattern indefinitely until there's another input? Will there be a cancel button?

Then read up on how to power and control NeoPixel LEDs. I believe they use I2C? Are there any NeoPixel libraries you can use?

You might then try using a circuit simulator to create a virtual prototype of your circuit. Figure out how big a battery & voltage regulator you're going to need. (If you're running off of batteries you should use a switching or "buck" type voltage regulator rather than a linear voltage regulator since they are much more efficient. Just make sure you pick a regulator that can provide enough current for all your LEDs plus your Arduino, with a little extra left over.))

Once you get a virtual circuit working, it's time to use real hardware.

For a bike tail-light, you should think about how to make it weather-proof. are there waterproof enclosures you can use? What about waterproof NeoPixels? If there are no waterproof NeoPixels, what about waterproof enclosures with clear covers?

Buy the Arduino you're going to use, and at least a few of your NeoPixels. Work out how to control and flash a single LED. Then gradually add complexity to your project until you get it working.


DHT11 Sensor : Stand-by or Shut down? I have an ATmega328P monitoring room temperature and humidity. It is enough for me to monitor every 8 seconds. In these 8 seconds, I am putting my Atmega to sleep.

Now , I want to know : Does shutting down the DHT11 for these 8 seconds affect the performance of the sensor in any way or is it advisable to keep it running (stand by) for these 8 seconds ?

[Shutting down means connecting the Vcc of the sensor to GND by means of digitalWrite(Sensor_pin,LOW);]

Also , (The below question is applicable only if your answer to the above question is to keep it in Stand-by) :-

I want to modify the above project such that Temp & Humidity is measured as and when only an input button is pressed.
In this case too, should I keep the DHT11 running?

Is a running DHT11 sensor more accurate than a instantly powered on DHT11 ?

[And in case you are speculating , yeah,I want to save the 50 micro-amps Standby current of the sensor.(but of course without sacrificing accuracy of the sensor)]

At times like this it is useful to refer to the datasheet.  You can, in that document, find this paragraph:

  4. Power and Pin

  DHT11’s power supply is 3-5.5V DC. When power is supplied to the sensor, do not send any instruction to the sensor in within one second in order to pass the unstable status. One capacitor valued 100nF can be added between VDD and GND for power filtering.

So you can see that if you power down the sensor completely you have to wait at least 1 second before you can do anything with it.

With it just in the low power mode it defaults to between readings you can immediately start reading as soon as your ATMega wakes up.

So you have to ask yourself: Does running the ATMega at full power for 1 second consume more or less power than running the DHT11 in low power mode for 8 seconds?

As a rough guestimate - if the ATMega is using 30mA (ballpark figure) for 1 second (that's 30mAs - milliamp-seconds), and the DHT11 uses 50uA for 8 seconds, then you have 0.05*8 = 0.4mAs.

That's 0.4mAs (sleeping) vs 30mAs (powered down). So I'd go for leaving it powered and avoid the one second delay at full power.

Another option that may save more power would be to:

Power off the DHT11
Sleep 8 seconds
Power on the DHT11
Sleep 1 second
Read DHT11
Go to 1

Of course, that means your loop then takes 9 seconds not 8. You could compensate by sleeping for multiple amounts to make 7 seconds:

Sleep 4 seconds
Sleep 2 seconds
Sleep 1 second
Power on the DHT11
Sleep 1 second
Read DHT11
Power off the DHT11
Go to 1

But of course that then makes your sleeping less efficient - so is it really worth it?


Amplify Piezo Sensor I am trying to amplify a piezo sensor per the instructions found at the link below.  I am not trying to trigger a buzzer only print to the serial monitor whether the vibration was detected or not.  I am a NOOB with respect to circuits and unable to understand why my circuit is not working.

The piezo is either giving a positive (sensing) reading or  giving a negative (not sensing) reading depending on where the poteniometer is set.  There is no state where-if all is quiet-the piezo is quite and if there is a vibration the piezo senses it and reports to the serial monitor.
I see from the blog that if the piezo get stuck on a state to lower the feedback resistor of the op-amp from 220k to 160k but again, there is never a case where it is working then get struck in state.  It is always stuck in a state!

The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor.  I am using the 10uf capacitor.  Will switching out the 10uf for a 0.1uf capacitor test potentially damage the Arduino? Is this the cause of the +-state of the piezo? Do I just have a wiring flaw?
Any advice is appreciated.

Here is a link to the post including the Fritzing diagram.
http://davidhoulding.blogspot.com/2014/02/high-sensitivity-vibration-sensor-using.html

Here is a picture of my circuit.

And the Sketch...

#define VIBRATION_DIGITAL_IN_PIN 8
int DurationMillis = 1000;

void setup()
{
  Serial.begin(9600);
  pinMode(VIBRATION_DIGITAL_IN_PIN,INPUT);
}
void loop()
{
  if(digitalRead(VIBRATION_DIGITAL_IN_PIN)==HIGH)
  {
    Serial.println("I felt that");
    delay(DurationMillis);
  }
  else
  {
  Serial.println("I don't feel anything...");
  delay(DurationMillis);
  }
}

You write,

  The blog post mentions a 0.1uf capacitor in the hand-drawn sketch but the Fritzing diagram shows a 10uf capacitor. I am using the 10uf capacitor.

The Fritzing diagram in the high-sensitivity-vibration-sensor at davidhoulding.blogspot.com shows a 10μf capacitor connected from +5V to ground on the breadboard.  This is a reasonable thing to do, to avoid power supply glitching on that board.  It is ok to add an 0.1 μf capacitor in parallel (that is, in addition to, and connected to the same busses) to the 10μf if you want to suppress some noise as well.

The last diagram in the blog, an “updated circuit diagram showing the refinements for reducing the gain to avoid op-amp output lockup, and DC decoupler on the input”, also shows an 0.1 μf capacitor connected between the piezo node and the first op amp input.  This will block any DC voltage coming out of the piezo from going into the op amp input.  It's likely that any capacitor from 0.05 μf up to 0.5 μf will work just as well there.  A smaller coupling capacitor is suitable for higher frequency inputs, and a larger one for lower frequencies.  The presence or absence of that capacitor probably isn't the problem with your circuit.  Looking at your circuit photo, the wiring looks ok[*].  Perhaps try substituting a different piezo element, or a signal generator if you have one, or a low voltage from a pot varied up and down, to generate a signal into your op amp and comparator stages to see if they are working.  If they aren't working, substitute for the LM358.

[*] Although I can't see if the 220KΩ resistor goes to +5 or to pin 1.  Also is your comparator output connected into digital pin 8 on the Uno?  It looks more like 9 or 10 in the photo.  Also, as a personal preference I'd attach the Arduino end of the ground wire to a pin next to the +5 instead of to the ground next to Aref.


How can I make a garage door laser sensor? I would like to make a sensor that detects when my car is clear of a certain point. So, when backing in my car to my garage, I would have a beam and sensor. When the beam is broken, an LED light would turn on and then when the beam gets through, the light turns off and I know that the car will clear the garage door.

I am pretty sure I have to use either an Arduino or Raspberry Pi, but I'm completely new to home automation. There are a few other things I'd like to do but this is a good starter.

I don't know where to start.

I would recommend using laser and LDR. This will be very efficient and will not cause any problem due to light or ultrasonic deflecting. It will be precise by mm if you do thing right way. I made a simple porject back in 2005 using laser, LDR and relay.

Here what you need to do.

Get a laser, any laser will work. www.ebay.com/itm/6mm-650nm-DC-5V-5mW-Mini-Laser-Dot-shaped-Diode-Module-WL-Red-Copper-Head-Tube-/291089398593?pt=LH_DefaultDomain_2&hash=item43c647bb41

Get a PhotoResgister www.ebay.com/itm/Reliable-Hot-New-20-PCS-Photoresistor-GL5528-LDR-Photo-Resistors-Light-Dependent-/161434780484?pt=LH_DefaultDomain_2&hash=item2596434344

Put ldr in the dark box and drill a hole in it so that no other light can enter 2mm diameter hole will work.

Connect the LRD to your board. Fire laser and change status of indicator led by the value of ldr.

Check this link for refrence www.instructables.com/id/Arduino-Laser-Tripwire/?ALLSTEPS


Arduino compiler uploading last saved version of sketch, not current Is this an issue or a defined behavior? I am using Arduino IDE 1.6.6

Sometimes I made changes in code, and immediately upload them to the Arduino board. And many times issues already fixed are persisting, leaving me that feeling of "the uploaded code has not the changes I have just made". Then I save my sketch, compile and upload again and the issue vanishes. As long as the issue get someway fixed, I tend to forgot about it.

As software engineer, most of the times I assume the code I am compiling and uploading / publishing to any platform is always the latest, not the latest saved. I believe this is not the behavior of the Arduino IDE. It uploads the last saved version of code, not the last modified.

In summary: I believe the Arduino IDE uploads to the board the last saved version of the sketch, not the current one being modified. Can anyone confirm this?

Thanks in advance.

I haven't tried it but it would be an easy experiment to make on some throw-away code.

However, do note that saving before compiling or uploading is optional in the Arduino IDE. That may very well be the key to what you observed. I keep mine enabled, i.e., to save before any compile or upload. The option is in the Preferences dialog accessed from the menus, not in the manually-edited preferences.txt file. That might be the key to what you observed.

Update:
In that case, including the pre-defined macros __DATE__ and __TIME__ (of the pre-processor run) and __TIMESTAMP__ (of the file's last modification) in a "Hello" string can help debug this.

These pages list the standard, and common predefined macros implemented in gcc's pre-processor.
Note also that most version control systems offer similar macros that get replaced at checkout to embed a revision number and other version-control information.


HC-05 TX,RX divider rule I'm using the HC-05 Bluetooth module but I'm confused about the TX,RX pins.
I want to know when should I connect the RX to a divider circuit to convert 5v to 3.3v.
Because while searching, I saw both of the following:

either RX is connected to TX of the UNO and TX is connected to RX of the UNO without a divider circuit.
or RX is connected to a divider circuit and then connected to any digital pin , TX is connected to any digital pin as well.

So can you give me a thought about both the situations?
my thought is that only digital pins needs a divider rule, but the TX,RX pins can be connected directly and operates without any problems but if so, then what's the difference between both??
Note that I'm using HC-05 to turn on a LED.
Hope to see some good explanation that suits a new Arduino learner.
Thank you..

While you should use a voltage divider on the Arduino TX --> BT RX signal, you honestly don't need to. Many people, including myself, have used HC-05s without voltage dividers and haven't let "the magic smoke" out of the device. Adding a voltage divider may, though, may increase the lifespan of the HC-05.


help with 7- segment display I'm playing with a 7 segment display.

The following works on my breadboard:

5V -> 330 Ohm Resistor (same row, row 9)
330 Ohm Resistor -> Com Port (row 9 to row 15)
h led (the dot/row 17) -> ground rail

I get the dot to light up.

However, the following does not light up:

5V -> h led (the dot/row 17)
Com Port -> 330 Ohm Resistor (Row 15 -> row 38).
330 Ohm Resistor to negative rail (row 38 -> negative rail)

I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.

So basically, if the circuit goes:

5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.

If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part.

I'm not sure why given that all the stuff is in serial?

Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.


how to make transmitter and receiver for quad copter? I want to make a transmitter and receiver for quad copter for that I am using two arduinos(UNO and nano).I am using 4 pots for controlling the brushless motors.For that I am sending 4 integer values of the pots and with that integer value PWM signals are generated at receiver by the arduino.Now I want to know how to send that 4 integer values of the pots serially using arduino.

The APC220 radio module provides a simple and economic solution to wireless data communications. Integrates an embedded high speed microprocessor and high performance IC that creates a transparent UART/TTL interface, and elminates any need for packetizing and data encoding. Use this module as this works as a pair and more intriguing part is that "it" can transmit over a km away.

link ~http://www.dfrobot.com/index.php?route=product/product&filter_name=apc&product_id=57#.VWeKIVWqqko


bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site:
https://github.com/halleysfifthinc/Toyota-AVC-LAN

In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.

In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of

while ( bit_is_clear( ACSR, ACO ) );

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?

I attempted to create something similar using

while( digitalRead( 2 ) );

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).

So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?

=========================EDIT=======================

Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:

#include <avr/wdt.h>

#define fwVer       "v0.1"
#define fwDt        __DATE__
#define DATAPIN     2

//====================================================================================COPYPASTED
#define DATAIN_PIN              ACSR
#define DATAIN                  ACO

#define INPUT_IS_SET            ( bit_is_set( DATAIN_PIN, DATAIN ) )
#define INPUT_IS_CLEAR          ( bit_is_clear( DATAIN_PIN, DATAIN ) )
//===================================================================================WHAT DOES THIS MEAN

byte data[255];

void setup() {
  LedOff();

  Serial.begin(9600);

  pinMode(3,OUTPUT);
  pinMode(2,OUTPUT);
  digitalWrite(3,HIGH); //"leave the pins tri-stated" according to Frigon
  digitalWrite(2,LOW);
  pinMode(LED_BUILTIN,OUTPUT);

  //two second watchdog
  wdt_enable( WDTO_2S );

  Serial.println("Firmware "+String(fwVer)+", compiled on "+fwDt);
  LedOff();
}

void LedOff() {
  digitalWrite(LED_BUILTIN, LOW);
}
void LedOn() {
  digitalWrite(LED_BUILTIN, HIGH);
}

void loop() {
  wdt_reset();
  if (INPUT_IS_CLEAR) LedOff();
  else LedOn();
}

Schematic: https://imgur.com/a/PIkad
(mistake on the schematic - I connected 5v to vcc and ground to ground)
If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.

My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit_is_clear(ACSR,ACO) that I don't understand?

Does [bit_is_clear(ACSR, ACO)] have something to do with something
  called in Internal Analog Comparator?

Exactly. ACSR is the “Analog Comparator Control and Status Register”.
ACO, the “Analog Comparator Output” is one bit of this register. The
ATmega328P has the same comparator, with the same register and bit names
as the ATmega8. C.f. the datasheet. You should be able to use this
part of the code as is.

  Frigon has wired his Atmega8 in a peculiar way. [...]

It seems to me that is termination is intended to ensure that, in the
“floating level”, the line AVC− is at a potential higher than AVC+. In
the “driving level”, the opposite should be true, with a difference of
at least 120 mV.

  I attempted to create something similar using while(digitalRead(2)) ;

It's not surprising that it doesn't work. This is a differential bus.
The information is carried by the potential difference between AVC+ and
AVC−, not by the potential of a single wire. A difference higher than
120 mV should be interpreted and a high state. Your digital input
instead reads a single wire and compares its potential to ground. The
thresholds to switch between LOW and HIGH are typically around 2.1
and 2.6 V, with some hysteresis. This is far from being compatible
with the signaling of the bus.

I recommend you follow Frigon's steps and use the analog comparator just
as he does. The comparator will tell you which of AVC+ or AVC− has a
higher potential, and it will not be bothered by the low level of the
differential signaling.


Prevent 5V output on Arduino Nano 5V pin I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.

I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.

Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V

EDIT:
There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?

A simple diode is all you need. The USB power already goes through a diode, so another diode the same will create a "highest voltage wins" situation.

That is, if the voltage provided by the USB port is higher than the voltage you provide on the +5V pin (after the diode's forward voltage drop) then the USB port will power the nano. If the voltage on the +5V pin is higher (after the diode's voltage drop) than the USB then the voltage on the +5V pin will power the nano.

No power will flow out of the 5V pin to your LED strip because the diode is in the way.

Connect the 5V external power to the anode of the diode, and the 5V pin of the Arduino to the cathode of the diode. The cathode is generally the end of the diode with the stripe.  Make sure the diode can pass enough current to power the Arduino when the USB is un-powered. The 1N4001 is a popular choice and very easy to get hold of.

That choice of diode also has a higher forward voltage drop than the on-board USB diode (0.7V as opposed to about 0.4V), so the USB will generally be chosen by default when connected and powered up, which is as it should be for a bus-powered device.


What are the FLASH_ARRAY/FLASH_TABLE macros in this code? In this code for heating monitor, there appears to be macros called FLASH_ARRAY and FLASH_TABLE. I can't find any reference to them either in this code, Arduino, or on the Internet. What do they do?

FLASH_ARRAY(byte, VARIABLE_DEVICE_TABLE,
    DEVICE_LADDNING_RETUR,
    DEVICE_LADDNING_UT,
    DEVICE_TANK1,
    DEVICE_TANK2,
    ...
    VARIABLE_ID_LOAD,
    VARIABLE_ID_TIME_EMPTY);

and

FLASH_TABLE(byte, NUMBER_TEMP_TABLE, 7,
  {DEVICE_LADDNING_RETUR, 99,  5, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  {DEVICE_LADDNING_UT,    99, 43, 10,  7, MAIN_TYPE_TEXT_CELCIUS, 2},
  ...
  {DEVICE_UTE,             0, 55, 15,  7, MAIN_TYPE_TEXT_CELCIUS_WITH_NEGATIVE, 103},
  {VARIABLE_ID_EFFECT,   114, 29, 10,  7, MAIN_TYPE_TEXT_VARIABLE, 2});

After further digging, this appears to be from Mikal Hart's Flash library.
The reason this library was developed is:

Storing static program data in flash/PROGMEM is a tricky part of
Arduino programming. To save precious RAM, a novice user already at
odds with unfamiliar C++ syntax must digest such daunting concepts as
prog_char, PSTR(), PROGMEM, pgm_read_word(), etc. Even seasoned users
get tripped up by the indirection and typecasting that are required to
retrieve valid PROGMEM data. Add to that a couple of apparent bugs in
the implementation, and it’s clear that PROGMEM is a complicated mess.
I have written a new library, Flash, which abstracts away most of this
complexity. It provides new String, Array, Table, and String Array
types that make ROM-based data collections as easy to use as “normal”
types. Each overrides the C++ [] operator, so to extract individual
elements one uses familiar array access syntax:

Specifically, these are macros and a simple helper class to make it easier to create arrays and tables of values in program memory.
The two macros are declared as so:
// Example: FLASH_ARRAY(float, temperatures, 98.1, 98.5, 99.1, 102.1);
#define FLASH_ARRAY(type, name, values...) \
  static const type name##_flash[] PROGMEM = { values }; \
  _FLASH_ARRAY<type> name(name##_flash, sizeof(name##_flash) / sizeof(type));

// Example: FLASH_TABLE(uint8_t, fonts, 7, {ON, OFF, ON, ON, OFF, ON, OFF}, {OFF, ON, OFF, ON, OFF, ON, OFF});
#define FLASH_TABLE(type, name, cols, values...) \
  static const type name##_flash[][cols] PROGMEM = { values }; \
  _FLASH_TABLE<type> name((const PROGMEM type *)name##_flash, sizeof(name##_flash) / sizeof(name##_flash[0]), cols);

The helper functions include size and override the operator [] so that they can easily be accessed like so
FLASH_ARRAY[0]

I disagree with zmo - this is more than boilerplate. The area of PROGMEM causes a lot of questions from Arduino users, and it is very easy to do things wrong when creating arrays in PROGMEM.


YL-38 output to NodeMCU v1.0 analog input Using a YL-38 and NodeMCU v1.0 I am trying to achieve what the first link is doing, take a soil moisture reading. I've done this on an arduino, but the conversion from an arduino nano to a nodemcu is proving difficult.

To my understanding, the nodemcu A0 pin operates from 0v-3.3v but the YL-38 analog output operates from 0-4.1v. So first off, is my understanding correct?

I struggle with hardware, so looking around I found these resources:

How to set up a simple level shifter: this setup seemed pretty much like what i wanted, but the 5v input was off

This thread was verbatim what I wanted but I am terrible with circuit math, so I couldn't solve or understand the provided formulas.

Attempt 0: Initially had sensor analog out connected to a0 on nodemcu. Saturated or dry the mcu read 1023. Thought this must be because the signal out is above the A0 mapping range.

Attempt 1: I figured I'd try out the level shifter. Wired it all up as indicated. Now my readings were 760 saturated and 765 dry.

runHygrometer(index);
delay(2000); //allow hygrometer to wake up
reading = (DEBUG) ? analogRead(HYGROMETER_READ_PIN) : 1023 - analogRead(HYGROMETER_READ_PIN);

As shown, my code does no scaling, It's a direct read (DEBUG is true here). So what gives? When using an arduino the range of readings was typically from 20 dry to 180 saturated (DEBUG false, so raw 1003 dry and 843 saturated)

To my understanding, the NodeMCU A0 pin operates from 0v-3.3v

Incorrect. The ESP8266's ADC can only measure between 0V and 1V.

You need to reduce your output voltage down to that range. How you do that very much depends on the output impedance of the YL-38.

The LM393 that the YL-38 is based around looks to have a maximum output current of 16mA. That should be enough to happily drive a simple voltage divider.  A 4.7kΩ and 1kΩ divider would give you 0 to 0.877v out from a 0-5V input.

simulate this circuit – Schematic created using CircuitLab

An alternative would be to attach an external ADC running at 5V to the NodeMCU. This would give you multiple channels of analogue input with a 0-5V range. I use the MCP3208 running over SPI (I actually bit-bang it on the ESP8266 rather than using SPI, since I haven't yet got SPI to work properly with it).  Ideally, you want a proper logic level translator for the SCK and MOSI signals to boost them to 5V. It all gets a little complex, though.

It has come to light that the NodeMCU includes a voltage divider already. For some reason they chose to use massive resistors, which give far too high an impedance for any reasonable ADC input to accurately work with.  I would suggest, if you can, removing those resistors from the board and replacing them with 4.7k and 1k resistors to form your own voltage divider. Otherwise you're going to have to use a pair of op-amps in inverting mode, one with a fractional gain, and one with unity gain (the second is to "undo" the inverting of the first one) to reduce the signal to 0-3.3V.

TBH I'd be inclined to use an external ADC anyway for this.


How do I make a stepper motor compass cross 360° to 0°? I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.

My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?

The simulator feeds a float val that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the AccelStepper library.

void ProgOut(byte id, float val) {
switch (1) {
case 1:

if (val)
        { stepper1.moveTo(val * 11.3222222);         }

        stepper1.run();

break; }}

I have tried something like this:

void ProgOut(byte id, float val) {
switch (1) {
case 1:
if ( stepper1.distanceToGo () >= 4064){
          stepper1.moveTo(4076);
          stepper1.setCurrentPosition(0);
}
    else if (val)
        {

                stepper1.moveTo(val * 11.3222222);
        }

        stepper1.run();

break; }}

Two options (for starters):

Use the move() class rather than the moveTo() class. This will allow you to do relative moves rather than absolute.
Use setCurrentPosition() (which sets the current position to zero) followed by moveTo() with a destination which is newPos - prevPos.

For either to work you will need to keep track of the current position of the needle.

To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.

// delta is the angular adjustment required.
delta = (currHeading + 180 - prevHeading) % 360 - 180;
setCurrentPosition();        // Zero the motor.
moveTo(delta);               // Move absolute from the new zero.
prevHeading = currHeading;   // Keep track.

The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.


3-wire strain gauge - HX711 Issue I have two, three-wire load sensors (https://cdn.sparkfun.com//assets/parts/4/5/9/5/10245-01.jpg) hooked up in a half wheatstone bridge (I think), with two 1K resistors.  Using a multimeter, I am reading small voltage changes when applying pressure to either strain gauge, when measured on between the pins A+ and A- on the HX711 ADC amp, however my Arduino serial output shows all 0's when using a variety of code examples (for example, this one:  http://www.dfrobot.com/wiki/index.php/Weight_Sensor_Module_V1#Sample_code).

My concern is that my circuit is not setup correctly as I am fairly novice, however everything I have researched about wheatstone bridges, and half wheatstone bridges seems fairly straightforward, and seems to match my circuit.  Any guidance/advice on the attached breadboard circuit diagram would be extremely helpful.

In your diagram, the fixed 1KΩ resistors both tie to +5V at one set of ends, and their other ends tie to A+ and A-.  The strain gauges are from A+ to ground and A- to ground.

In a typical scale, where several strain gauges are similarly loaded, that topology will produce about zero volts between A+ and A-.  By contrast, the following  topology (from: blog.l3l4.com) produces higher voltages for higher loading.  (Diagram uses S+, S- rather than A+, A-)

(I realize your question shows some voltage changes when sensors are separately loaded, so this answer might not be relevant to your current problem.)


Dynamicly sized array as a class member I want to create a dynamic sized array of chars as a member in a class.
This is being done inside a library that I've created.
I have the .h and the .cpp files created. I'm not sure how to declare the array in the .h file. I've tried a few things so far:
char* content;
char content[];
But these don't seem to work.

Here's what I have in my .h file:

class bufr{
    public:
    //constructor and deconstructor
    bufr(char* _chars, uint8_t _len);
    ~bufr();

    //variables
    uint8_t len;
    char content[];

};

Here's what I have in my .cpp file (this is the constructor):

bufr::bufr(char* _chars, uint8_t _len){
    char* content = new char[_len];
    content = _chars;
    len = _len;
}

I've also tried replacing the line content = _chars with:

for (int i = 0; i < _len; i++){
    content[i] = _chars[i];
}

But this also doesn't work.  When I print the content member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.

Here's my main loop:

void loop(){
    char chars[] = "1234";
    bufr buf(chars, 4);
}

Have I explained myself well enough?  Can anyone give me a hand?
Much appreciated!

Oh, and yes, I know - in my deconstructor that's not shown, I have delete [] content

I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation.  I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use new and delete.

Thanks!

Many programmers have a disjoint between a pointer and an array. Here's an explanation.

Here is a variable of type char, initialised with the value 'A':

char c = 'A';

'A' has the ASCII value of 65, so that means that there's a byte in memory that holds the value 65. Let's say that byte in memory is at address 0x2000. If you were to add 1 to that byte, it would become 66, and if you were to print it as a character, it would print B (ASCII 66).

Here is a pointer to a char, initialised with the address in memory of c:

char *p_c = &c; // Get the address of c into p_c

  [Note that char *p_c = c; would be invalid: you can't initialise a pointer with a char! That'd give p_c the value 65 - not what you want!]

In Arduino, p_c represents two successive bytes of memory that together store the address of a char: in this case the value 0x2000. Where those two bytes are doesn't matter for this explanation - but trust that they too have an address...

If you were to change c into a 'Z', that would change c's contents, but not p_c's (it would still be 0x2000). But if you were to use p_c to look at the byte it was pointing to (c), then you'd see the 'Z'.

If you were to do a printf("%c", c); you'd get a 'Z'.

  %c means "I've got a character as the next variable in the printf() list".

If you were to do a printf("%c", *p_c); you'd also get a 'Z'.
If you were to do a printf("%c", p_c); you'd get horrible results.

  You lied to printf() - you didn't give it a one-byte character, you gave it a two-byte pointer!

Now let's move on to arrays.

Here is a variable of type char [], initialised with the value "John".

char s[] = "John";

'J' has the ASCII value 74, 'o' 112, 'h' 104, and 'n' 111. That means that in memory there are four sequential bytes with the values 74, 112, 104, 111. Let's say that those bytes are at addresses 0x3000 through 0x3003.

And here is another pointer to char, this time initialised with the address in memory of s.

char *p_s = s; // Point to s with p_s

  I hate that the C language allows the above. It is one of the roots of the whole array/pointer confusion. It kind-of implies that p_s somehow gets all of "John" assigned to it. Nope!

A better statement would have been:

char *p_s = &s; // Initialise p_s with the address of s // ILLEGAL!

That gives a MUCH better idea of what's happening - alas, it's not how it's done...

But also note that neither of the above could possibly store 0x3000-0x3003 (the addresses for all of s), so they have to be satisfied with only storing the start of the string: p_s will get the value 0x3000.

Note that s does NOT have the value 0x3000 in it. That is its address, like 0x2000 was c's address (it too doesn't have 0x2000 in it). But p_s does have 0x3000 in it - and don’t forget that p_s also has its own address (I won't bother with that here).

And this is where the "equivalency" (they're not) between a pointer and an array starts to get people confused:

s[2] = 'h'; and p_s[2] = 'h'; do the same thing - but in different ways!

The first accesses 0x3002 directly.
The second needs to find out that p_s is 0x3000 and add 2 to it before it can access 0x3002.

*(p_s + 2) = 'h'; is yet a third way to do the same thing.

So now let's printf() these new variables:

printf("%c", *s); wouldn’t compile.

  s is not a pointer, so you can’t dereference it with *.

printf("%c", *p_s); would print the character at where p_s was pointing.

  This would print out J.

printf("%c", s[0]); would print the character at s[0].

  This would print out J.

printf("%c", s); would give horrible results.

  Again, you lied to printf()!

printf("%s", s); would work (but see below).

  %s means "I've got a sequence of characters that I'd like you to print. I've provided the address of the first character."

printf("%s", p_s); would be identical to the previous one.

  After all, the same address value was passed!

printf("%s", *p_s); would give horrible results.

  Again, you lied to printf()!

But note something: you've given printf() the beginning of the string, so it can start printing. How does printf() know where the end of the string is? You didn't provide the number 4; it's not stored anywhere; how can it know when to stop?

That's where a C convention for strings steps in. By convention, when the compiler sees a string "between quotes", it stores the ASCII values of the characters, and then follows them with a 0. Not an ASCII '0' (with value 48), but an ASCII NUL (with value 0). Thus if you looked at address 0x3004 (the byte directly after John), you'd see a 0 in that memory byte. That's how printf() knows to stop printing - and yes, many a bug has resulted from forgetting to maintain a NUL at the end of a sequence of chars!

That then leads me to the sizeof() function

sizeof() always returns a constant at compile time using information that the compiler then knows about:

sizeof(c) would return 1.
sizeof(p_c) would return 2.
sizeof(p_s) would also return 2.

  It is after all merely a pointer too.

sizeof(*p_c) would return 1.
sizeof(*p_s) would also return 1.

  It's only pointing to a single char...

sizeof(s) would return 5.

  The compiler knows what s is: an array of 5 bytes (including the final NUL).

Given a pointer, there is no (native) way to find out how large the buffer it is pointing to can be.

OK: so if you've got a char [] you can find out its size. Note that that is its maximum size - the string inside it could be a lot shorter! If you did the following:

s[3] = 0; // Overwrite the fourth character (arrays start at 0)
printf("%s", s);

  [Note a better version of the first line would be s[3] = '\0'; which means "store the ASCII character 0 (NOT '0')" instead of "store the number 0".]

you'd get Joh printed out. Note:

sizeof(s) remains 5;
You can't get the length with sizeof(*p_s);
The string inside it is only 3 characters long.

So... if you've got a string buffer, or a pointer to one, how do you know how long it is? Count the number of characters until you reach a NUL - and there's already a function to do that for you: strlen().

Which now leads to the final point about pointers: dynamic allocation of memory.

The array s above was sized by the compiler at compile time: it could count the characters, add one for the NUL, and reserve the right number of bytes. You could also have written:

char s[10] = "John";

which would have reserved 10 bytes and only initialised the first 5 of them. The following would be an error:

char s[3] = "John"; // Buffer too small!

  Scarily, char s[4] = "John"; works... (The compiler says to itself "No room for the NUL?! Ah well...”) Better never pass that string to strlen() or printf() then!

What if you don't know at compile time how big a string is going to be? If you know at runtime, you can ask the system for a lump of memory from the heap - a reserved area that can have chunks taken from it and returned as required. There are two ways to do this:

char *p_b = (char *)malloc(size); // Where size is a variable
char *buffer = new char[size];    // Grab 'size' new chars

The first calls malloc(), passing in the number of desired bytes. If malloc() can give those bytes it will reserve them and return a pointer to them. If it can't it will return 0. You should always test the return value! If not, you'll corrupt things horribly...

The second uses the more sophisticated new[] syntax, which is more object oriented. Notice how malloc()'s return value needed to be turned into a (char *)? That's because it doesn't know what type of pointer it's returning, so it just picks void *. new does know, so it returns the correct type - but it still may return 0 if there's no room!

Once you've got either pointer, you use them just like p_s before. There is nothing stopping you from accessing outside the boundaries of the buffer - just like there isn't for p_s! Be careful!

Oh, and once you've finished with the lump of memory, you need to return it to the heap:

free(p_b);
delete [] buffer;

If you used malloc(), return it with free(). If you used new[], return it with delete[].

And all of the above is why they invented the String object.

It manages the memory; keeps track of the string's length; lets you access and modify individual characters; lets you resize the string as needed; and gets rid of the used memory once you're finished with it. No wonder people start to use String syntax when they see string pointers...

But Strings are only useful for chars. Arrays and pointers can be of and to anything - including Strings and (GASP!) pointers! Uh oh - here we go again...


Arduino Uno CTC mode interrupt is not tiggering I am trying to generate LED blink after 4 second using Interrupt  but Interrupt is not triggering not even once .
Request: if you have arduino uno r3 please check at your end and let me know result.
I have read Timer counter section multiple times and applied everything i can for example :-

Enabled Global Interrupt
Select CTC Mode
Enable Interrupt for OCIE0A
Prescaling to clk/1024
Initializing OCR0A
When OCR0A equal TCNT0 ,interrupt will generate

int var;
void setup() {
  // put your setup code here, to run once:
    SREG = SREG | (1<<7);          // Gloval interrupt enable
    TCCR0A = TCCR0A | (1<<WGM01); // Clear counter on compare match mode
    OCR0A = 255; // when TCNT equal OCR0 interrupt will generate
    TIMSK0 = TIMSK0 | (1<<OCIE0A); //  Output Compare Match A Interrupt Enable
    TCCR0B = TCCR0B | (1<<CS01) | (1<<CS02);  // Prescaling by 1024
    DDRB = DDRB | (1<<5);
    Serial.begin(9600);      // Testing
    Serial.println("Start");   // Testing
}

void loop() {
  // put your main code here, to run repeatedly:

}

ISR(TIMER0_COMPA_vect){
    var++;
    Serial.print(var); // Testing
    volatile long unsigned i;
    if(var == 246){
        PORTB = PORTB | (1<<5);
        for(i=0; i<30000; i++);
        PORTB = PORTB & ~(1<<5);
        for(i=0; i<30000; i++);
        var=0;
    }
}

clock is 16 00 00 00 Hz
Prescaling by 1024 = 15625
1 Tick = 1/15625 = 0.00 00 64 sec
OCR0 is initialized by 255
TCNT0 Ticks to 255
Total time taken to generate one interrupt = 255 * 0.00 00 64 =
0.01632 sec that means after every  0.01632 sec Interrupt supposed to generate
How many interrupt is required to generate LED after 4 sec =>
4/0.01632 = 246

Update working code

int var;
void setup() {
  // put your setup code here, to run once:
  SREG = SREG | (1<<7);          // Gloval interrupt enable
  TCCR0A =(1<<WGM01); // Clear counter on compare match mode
  OCR0A = 255; // when TCNT equal OCR0 interrupt will generate
  TIMSK0 = (1<<OCIE0A); //  Output Compare Match A Interrupt Enable
  TCCR0B = (1<<CS00) | (1<<CS02);  // Prescaling by 1024

  DDRB = DDRB | (1<<5);

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

}

void loop() {
  // put your main code here, to run repeatedly:

}

ISR(TIMER0_COMPA_vect){
  var++;
 // Serial.print(var);
  volatile long unsigned i;
  if(var == 246){
        PORTB = PORTB | (1<<5);
        for(i=0; i<300000; i++);
        PORTB = PORTB & ~(1<<5);
        var=0;
  }
}

There are a few issues with your code:

First, you should completely overwrite the timer control registers
rather than changing single bits. For example, when you write

TCCR0A = TCCR0A | (1<<WGM01); // Clear counter on compare match mode

You end up with a timer mode that results from the combination of the
bits that were already set there and the ones you are setting. Judging
from the comment, you assume that this will be CTC mode, but this is not
granted, because the Arduino initialization routine has already set some
bits in this register. Since you are taking the timer for your own
usage, just overwrite all the control registers:

TCCR0A = (1<<WGM01); // Clear counter on compare match mode

and same for TCCR0B and TIMSK0.

The second problem is that you misread the “Clock Select Bit
Description” table from the datasheet. Your timer is being clocked from
an external clock source on T0 pin. Presumably you have nothing
connected there, so the timer does not increment. You probably meant

TCCR0B = (1<<CS00) | (1<<CS02);  // Prescaling by 1024

A smaller issue is your delay loop. The program would be easier to
understand if you instead use a proper delay function. The Arduino
delay() will not work, as you have reconfigured Timer 0, but you can
use _delay_ms() from the avr-libc if you #include <util/delay.h>.


UECIDE: linker error with U8g2 library This sketch:

#include <SPI.h>
#include <Wire.h>
#include <U8g2lib.h>

//  OLED display.
U8G2_SSD1306_128X64_NONAME_1_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
void setup() {
  u8g2.begin();
}
void loop() {
}

Compile OK with Arduino 1.8.3, but under UECIDE 0.8.9-pre15 fails to link, with this message:

Compiling...
• Preprocessing...
• Compiling sketch...
• Compiling core...
‣ arduino
• Compiling libraries...
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ SPI [/home/look/.uecide/libraries/Communications/arduino/SPI]
‣ U8g2 [/home/look/Documents/UECIDE/libraries/U8g2]
‣ Wire [/home/look/.uecide/libraries/Communications/arduino/Wire]
• Linking sketch...
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::write(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:248: undefined reference to `u8g2_DrawGlyph'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::initDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:101: undefined reference to `u8x8_InitDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::clearDisplay()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:104: undefined reference to `u8g2_ClearDisplay'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::setPowerSave(unsigned char)':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:107: undefined reference to `u8x8_SetPowerSave'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:62: undefined reference to `u8x8_ascii_next'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2::home()':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:278: undefined reference to `u8x8_utf8_init'
/tmp/build-47290781-bacc-48e0-bc90-833910b26209/borrar.cpp.o: In function `U8G2_SSD1306_128X64_NONAME_1_HW_I2C':
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_cb_r0'
/home/look/Documents/UECIDE/libraries/U8g2/src/U8g2lib.h:679: undefined reference to `u8g2_Setup_ssd1306_i2c_128x64_noname_1'
collect2: error: ld returned 1 exit status
Compiling Fail

Both IDEs are set for Arduino Pro Mini 3.3V 8Mhz. In UECIDE I'm using GCC 4.9.2 for AVR. I copied the same U8g2 source code to both Arduino and UECIDE own libraries directory.

U8g2 library is version 2.15.2 by Oliver, installed via Arduino IDE and copied to the UECIDE libraries directory,

The problem, so far, only happens with U8g2 and not other libraries.

How do I solve this problem?

The layout of that library is in a non-standard format with folders that UECIDE doesn't know to look for or how to deal with.

The main culpret is the inclusion of big chunks of code in a "clib" directory (why on earth?!?!) which doesn't get included in the compilation. Then on top of that you have header files in there that are referenced both from inside it and outside it.

The simplest fix is just to copy and move the files to better locations:

$ cd ~/Documents/UECIDE/libraries/U8g2/src
$ mv clib/*.c .
$ cp clib/*.h .

Note you move the source, but copy the headers. That's to get around the problem of the headers being referenced from two locations with relative paths.

The problem stems from UECIDE having (by necessity) much stricter rules than the Arduino IDE over the layout of a library. This is to facilitate better identification and categorization of the libraries so that recursive dependency detection can take place.