How to make a 5-volt relay work with NodeMCU? I have hooked up 2 channel 5-volt relays with NodeMCU v1.0 as shown in the fritzing below.

Relay are powered with a different power source than NodeMCU.

As of now, I am powering the NodeMCU from my laptop and the relay board from a 5-volt battery.

Below is the code I have written:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, HIGH); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, HIGH); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}

When I execute the URL: 192.168.1.8/relay1 the outputLed blinks as per the logic in turnOnRelayOne.

But neither of the relays turns on. Please help.

I have several of these modules. They have an optional opto-isolator built-in, but you have to remove the jumper to use it.

Connect your GPIO trigger as you have it
Run the relay's Vcc and Gnd pins to the MCU, not the power plug.
connect the power plug's +5v to the left-most pin, where the jumper once stood: JDVcc
connect the power plug ground to the MCU or the open common Gnd on the left-group of pins.

Now your relay coil(s) will be powered by the 5v plug, but the relay's logic and control are handled by the MCU.

This relay module works differently.
It is on when the signal is LOW and it turns off when the signal is HIGH (3v3V on the NodeMCU)
So you only need to modify the code in the two functions to be LOW instead of HIGH
Also make sure the NodeMCU and the relay module have a common ground.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

const char* ssid = "said.";
const char* password = "secret";
ESP8266WebServer server ( 80 );
const int led = 13;
const int outputLed = 12;

void turnOnRelayOne(){
  digitalWrite (outputLed, 1);
  digitalWrite (5, LOW); //GPIO 5 // Relay 1
  server.send (200, "text/html", "Relay 1 turned on.");
  digitalWrite (outputLed, 0);
}

void turnOnRelayTwo(){
  digitalWrite (outputLed, 1);
  digitalWrite (4, LOW); //GPIO 4 // Relay 2
  server.send (200, "text/html", "Relay 2 turned on.");
  digitalWrite (outputLed, 0);
}

void handleRoot() {
  digitalWrite ( led, 1 );

  char temp[400];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  snprintf ( temp, 400,

             "\
  \
    <meta http-equiv='refresh' content='5'/>\
    <title>NodeMCU hooked to Relay Board</title>\
    \
  \
  \

Hello from NodeMCU!
\

Uptime: %02d:%02d:%02d
\
  \
",

          hr, min % 60, sec % 60
           );
  server.send ( 200, "text/html", temp );
  digitalWrite ( led, 0 );
}

void handleNotFound() {
  digitalWrite ( led, 1 );
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }

  server.send ( 404, "text/plain", message );
  digitalWrite ( led, 0 );
}

void setup ( void ) {
  pinMode ( led, OUTPUT );
  pinMode(10, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(outputLed, OUTPUT);
  digitalWrite ( led, 0 );
  Serial.begin ( 9600 );
  WiFi.begin ( ssid, password );
  Serial.println ( "" );

  // Wait for connection
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  Serial.println ( "" );
  Serial.print ( "Connected to " );
  Serial.println ( ssid );
  Serial.print ( "IP address: " );
  Serial.println ( WiFi.localIP() );

  if ( MDNS.begin ( "esp8266" ) ) {
    Serial.println ( "MDNS responder started" );
  }

  server.on ( "/", handleRoot );

  server.on ( "/inline", []() {
    server.send ( 200, "text/plain", "this works as well" );
  } );

  server.on("/relay1", turnOnRelayOne);
  server.on("/relay2", turnOnRelayTwo);
  server.onNotFound ( handleNotFound );
  server.begin();
  Serial.println ( "HTTP server started" );
}

void loop (void) {
  server.handleClient();
}


ESP8266 TCP connection WiFiClient issue I am using ESP8266 01 board to send some data via TCP to server on local network. My code is:

#include <ESP8266WiFi.h>

const char* ssid     = "ssid";
const char* password = "pas";

const char* host = "192.168.1.103";

void setup() {
  Serial.begin(115200);
  delay(10);

  // Wifi connection

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

   delay(5000);

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int port = 8888;
  if (!client.connect(host, port))
  {
    Serial.println("connection failed");
    return;
  }

}

void loop() {

  while(Serial.available() == 0)
  {
    //wait for arduino serial data
  }

   while(Serial.available())
  {
    // send data to server
    client.print(Serial.read());
  }
}

After chacking code in Arduino IDE I am getting error message:

In function 'void loop()':
espwifitcp1:57: error: 'client' was not declared in this scope
     client.print(Serial.read());
     ^
exit status 1
'client' was not declared in this scope

It appears that if I declare WiFiClient client; inside setup() function it can't be accessed outside it. Do I correctly understand the problem? I have tried to declare object outside setup() and loop() functions but it got even more errors. Any suggestions?

You have declared WiFiClient client; in the scope of setup() only. Move it's declaration to the global scope by placing it above the declaration of void setup()


Arduino IDE unable to see serial connection on OS X El Capitan For some reason the Arduino IDE is unable to see my Arduino Uno even though it is connected. I have reinstalled the Arduino software, but no luck come of it. I connected the Arduino to my friends mac, who's could see it.. I am very confused and greatly appreciate any help.

Thanks,
Shaun

I ran into a similar problem years ago on an ATMega128 (before Arduino) and you just have to be aware of alternative functions for the port. In this case PD0 is Hardware Serial RX which is a receive pin.

Here's some relatively older code based around the same idea:

  Yes, you can use the RX/TX pins as regular IO. Just don't call the Serial.begin() in your code, and make sure you call a pinMode() for them.

from: http://www.societyofrobots.com/robotforum/index.php?PHPSESSID=b928292f91c78b57b5683484af0f635e&topic=12396.msg93239#msg93239

Another interesting post, fourth post: http://www.nerdkits.com/forum/thread/536/
where they disable the serial functionality once the code begins, downside (a above) you will lose serial comms, so it depends on how much you need them.

UCSR0B = 0;

I'm not sure how successful that would be in today's arduino, I know a lot (if not all) of the prior functionality is maintained, but I haven't used them in a long while.

The pin should become active again as the bootloader will automatically reenable it upon reset (although I haven't personally tested it). It will just make debugging that little bit harder if you need to.

As I mentioned in my comment, if you have another pin available to you, use that instead.

In case someone else has this problem..

Turns out, you can't be connect to pin D0 whilst using serial.


Can't make ultrasonic sensor work with motor controller I just started using Arduino Uno, I can't get the ultrasonic to work ,with motor controller board, the output value is always zero.

Just to make sure I'm talking about the correct stuff:
I used this guide to try to make it work (look at the picture how did I connect the parts).

And this is my code:

#define trigPin A4//Attach Trig to port 8
#define echoPin A5//Attach Echo to port 7
#include <AFMotor.h>
//SMARS Demo 2 with Line sensor

AF_DCMotor R_motor(2); // defines Right motor pin
AF_DCMotor L_motor(1); // defines Left motor pin

int lmotorpin1 = 3;
int lmotorpin2 = 5;
int rmotorpin1 = 6;
int rmotorpin2 = 9;
int distancecm = 0;
//const int trigPin = 18;
//const int echoPin = 19;

// defines variables
long duration;
int distance;
void setup() {

  Serial.begin(9600); // sets up Serial library at 9600 bps

  //changes the following values to make the robot drive as straight as possible
  L_motor.setSpeed(200); // sets L motor speed
  R_motor.setSpeed(140); // sets R motor speed

  R_motor.run(RELEASE); //turns L motor on
  L_motor.run(RELEASE); //turns R motor on

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
      Serial.println(trigPin);
    Serial.println(echoPin);
  distancecm = mdistance();
  if (distance < 5) {
    L_motor.run(BACKWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
//    L_motor.run(FORWARD); //moves motor L Forward
//    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
  }
  else {
    L_motor.run(FORWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
  }
}

int mdistance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  Serial.print("Duration: ");
  Serial.println(duration);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

As you can see I tried different pin numbers but it always 0 ....

what do you think can be wrong?

The motors work.
Motor Controller: KEYES L293D Motor Control Shield
Sensor: Ultrasonic Ranger V2.0

Pin numbers 0 and 1 are reserved for the Serial monitor which you're using on the board.
The function int mdistance() should return an integer.
You also didn't seem to set the motor pins as OUTPUT.


Wake up ESP8266 from deepSleep with a button I have a button with two isolated tracks. I want to be able to wake up esp from deepSleep with this button, and also detect that it was clicked. So i can't connect it to reset, because esp won't work if i don't release a button. And if it's not at deepSleep, it will reset, and i don't want it. How to do this?

Use some other pin to hold RESET HIGH or to disconnect the button from RESET while the esp8266 is not running.

simulate this circuit – Schematic created using CircuitLab

I asked on EE SE for the missing part of the circuit.

You can't stop deepSleep, all you can do is reset the board so connect the button to the reset pin and make the appropiate set-up:

Connect a pullup resistor (10k) in RST
Connect the button from RST
to GND

When you push, RST has GND so the ESP gets reseted.

Remember that deepsleep only works for about an hour so you have to contemplate this situation, too, maybe with a static variable...

EDIT Thanks Juraj for the comment: "from SDK API "system_deep_sleep(0): there is no wakeup timer; in order to wake up, connect a GPIO to pin RST; the chip will wake up by a falling-edge on pin RST."


Writing and reading an ID to/from an Arduino reliably I need a way to both ID (a sketch/compiled hex) and later on, identify based on this ID the project that got uploaded to my Arduino microcontroller. As of right now, I have explored multiple options for storing the ID and reading the ID from the Arduino. The ID would be a custom string or later on multiple strings. Here are the 3 options I have been thinking about with their pros and cons:

Option 1:

Writing: A custom function that would be added to every sketch before compilation, containing the ID information and a serial connection setup

Reading: The function would dump the ID over the serial connection using a fixed baud, after this, the projects original serial and baud would be initialized. The microcontroller would need to be rebooted in order for the user to be able to read the ID from it.

Pros: Easy to implement.

Cons: Would require manual or software restart of the microcontroller in order to read the ID

Option 2:

Writing: writing the ID to the EEPROM

Reading: reading the ID from the EEPROM over the serial connection.

Pros: Would probably not interference with the original code

Cons: it wears the EEPROM, it might need its own function in the sketch to read the ID from the EEPROM thus making it a complicated Option1.

Option 3: Editing the HEX file to include a signature

Writing: add the ID to the hex file itself (hex editing), after compiling it.

Reading: dumping the hex file and decoding the string.

Pros: No baud or serial needed to be set?

Cons: Probably slow, can end up producing a bad hex file, hard to implement properly with larger ID-s and structures

Example data:

project="marlin2.1",
config="prusa",
version="8.80",
env1="pin2"

As said, the basic idea is storing an ID but I would late want to expand this and store more information like a struct.  This solution should be able to Target as many Arduino models as possible. I am looking for the best way that I might have missed to achieve this task or any recommendations.

I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 write cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM.
Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.


Explain what is meant by "Arduino core" What is an "Arduino core"?

Are there many different "Arduino cores"? such as a core that applies to LCD
displays, another core that applies to servos, etc.?

The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the hardware/arduino/avr/cores/arduino folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.

what is an "arduino core" ;

Doing takes such terms seriously. They are invented soo people can sound more sophisticated than they really are..

In the context you mentioned, thy sound like a set of software routines that simplify interfacing with certain hardware.. others may call them libraries, or API, or anything else.

Basically code.


Suggest me a power source for my Arduino UNO project I am working on a Project with:

1 Arduino UNO
5 micro 9g servos (Only one Working at a time)
2 small LED bulbs
1 MicroSD reader module
1 Speaker

Can I power my Arduino UNO with a common 9v Battery?

I also have in mind to use an external power supply for servos... but what to use?

Please suggest me a perfect power supply system

Unfortunately, the perfect power supply system doesn't exist yet. However, powering an Arduino is simple.  You have to main options 9V for standard "full size" Arduinos (such as the UNO that you mention), although you could go for the low voltage 3.3V options.
Covering just the 9V option, from the Power section of Arduino Uno:

Power
The Arduino Uno can be powered via the USB connection or with an
external power supply. The power source is selected automatically.
External (non-USB) power can come either from an AC-to-DC adapter
(wall-wart) or battery. The adapter can be connected by plugging a
2.1mm center-positive plug into the board's power jack. Leads from a battery can be inserted in the Gnd and Vin pin headers of the POWER
connector.
The board can operate on an external supply of 6 to 20 volts. If
supplied with less than 7V, however, the 5V pin may supply less than
five volts and the board may be unstable. If using more than 12V, the
voltage regulator may overheat and damage the board. The recommended
range is 7 to 12 volts.

You should probably also take a look at Power Supplies, in particular the section on Batteries and cells, also from the following section Voltage conversion and regulation, it states:

In a very simple scenario, you connect a disposable 9v battery
(probably one of the (approx) 4cm x 2.5cm x 1.5cm units with two snap
connectors on one end) to your Arduino, and the Arduino's built in
voltage regulator takes care of reducing the voltage to a consistent
5v or 3.3v, depending on the sort of Arduino you have.

So you have a couple of choices regarding 9V, either the P9 cell

or a pack that holds six 1.5V AA or AAA batteries.
You may find this link, How to run an Arduino (clone) on (AA) batteries for over a year – part 2, an interesting read. Here the chap uses four AA batteries, which only gives 6V, to power an UNO:

I have just highlighted some information, you should take the time to read the links fully, and google for more information.

Regarding the servo motors, more current may be required. You can use the same four AA battery pack, thusly:

but the capacity of the batteries may leave something to be desired, especially if you use rechargeable batteries (which in today's eco-concious world, you should), so you may require something more hefty. A quick google will show you the options available.
Addendum
The video Flite Test : RC Planes for Beginners: Batteries and Safety - Beginner Series - Ep. 7 is an extremely useful video tutorial about LiPO batteries for RC projects.

You can use 9v battery and use separate one for servos. Due to voltage being "relative," you still need to connect the grounds.

You can connect the + of the battery to the VIN of the Arduino.


MKR ZERO is not detected in IDE / MKR ZERO not showing up in windows 8.1/ I m connect it with my IDE software and its work perfectly yesterday, but today morning I'm connected it to software to upload another sketch but its didn't detect the port and the charge led is not on yesterday but today is on. I tried every resolution which is given on website but its didn't work. please help me through this I'm new to this board.

A few possibilities come to mind:

Your USB cable is bad.  Try a known good one.
Your USB port has failed.  Try a different port or try plugging something else into this one to verify that it's still OK.
Your MKR ZERO has become damaged somehow.


Can't Upload Sketch, Atmel SDM Chip Overheating I have a chinese CH340 clone arduino. It was working fine until now. The L light stays always on. The sdm Atmel chip is overheating to the point that I can't even touch it. The card is listed under com ports however I can't upload anything due to:

avrdude: stk500_recv(): programmer is not responding

Should I just throw it away or is there a way to save it?

u need to cool down the chip for a few minutes and it will work the uploads use a heatsink or something small enough to cover it


CO2 sensor for arduino I want to add CO2 measuring feature to my room weather station. Can someone please recommend a CO2 sensor easy to integrate with Arduino?

You could try the K30 CO2 sensor. There is also a guide using it to make an arduino CO2 detector here.

I've also seen people use the MG-811 module, you can buy them from dfrobot.com . There is also good documentation for how to use the MG-811 with arduino here.

I can recommend these sensors. They are small and offer great value for the money.


Efficiently using a serial inteface So at my school we are preapering for a competition. They asked me to do the technical side of it. And I accepted... I was thinking of using an arduino as a usb device for the buttons. I am going to use the serial port for this. But I can't think of a way to do it in the way I want. I want to recieve the button presses fair and well. But I also want to control the lights for the buttons, from my computer. I am using Serial.printLn() to send the serial data to the computer. But how can I send serial data to the arduino without delaying other things (What happens when someone presses a button while I am sending a command?)? Thanks in advance!

The nastiest part in what you describe is likely to be the debouncing on the button, rather than the serial communication.

One easy way out is to use some form of bounceless implementation, like an optical coupler. Another is to use HW debouncing, like the MAX 6816 family.

Then you can use a loop where you alternate between serial communications and checks for the status of the buttons.

Or you can rely on interrupts for the buttons, but it's more complex and might be overkill.


Can someone recommend a complete guide for learning Arduino? Am trying to learn Arduino so that I can teach my children.
Understand the basics of the coding and can do some simple projects like the ultrasonic reading etc. But I need a more complete, structure guide.

Any recommendations for books, video lessons, and projects would be appreciated.

Arduino Cookbook (I have 2nd edition) is worth its price in paperback. PDF/etc formats are available. Children like to dig in without deep theoretical preparations. IIRC it covers classes briefly, as well as bitmath. A nice book.

Boxall’s book is better still. A link: https://m.barnesandnoble.com/w/arduino-workshop-john-boxall/1114672111?ean=9781593274481

You don’t really need to do much except give the kids a laptop with no games on it, and a few arduino clones. Just lock the door to their room with a default-closed solenoid connected to an H-bridge. They’ll learn quickly.

Grab an arduino, some jumper wires, some cheap modules which make you excited at first sight. Then get your hands dirty. That's the best tutorial that worked for me. SE is always here and you can ask any reasonable question.


Timer function without the use of a library Trying to do my own timer function. I was wondering if there is any other ways to make my code more efficient without the use of a library. I noticed if I only use one timer function, I wont have multiple instances of the timer. My current code works though.

unsigned long previousMillis1 = 0;
unsigned long currentMillis1 = millis();
unsigned long previousMillis2 = 0;
unsigned long currentMillis2 = millis();
unsigned long previousMillis3 = 0;
unsigned long currentMillis3 = millis();

bool timer1(int preset){
  unsigned long currentMillis1 = millis();

  if(currentMillis1 - previousMillis1 >= preset ){
    previousMillis1 = currentMillis1;
    return true;
  }
  else{
    return false;
  }
}

bool timer2(int preset){
  unsigned long currentMillis2 = millis();

  if(currentMillis2 - previousMillis2 >= preset ){
    previousMillis2 = currentMillis2;
    return true;
  }
  else{
    return false;
  }
}

bool timer3(int preset){
  unsigned long currentMillis3 = millis();

  if(currentMillis3 - previousMillis3 >= preset ){
    previousMillis3 = currentMillis3;
    return true;
  }
  else{
    return false;
  }
}

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

void loop() {
  if(timer1(1000)){Serial.println(1);}
  if(timer2(2000)){Serial.println(2);}
  if(timer3(3000)){Serial.println(3);}
}

Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.

Here it is easy: the only difference between your timer functions is
that they use a different previousMillis variable. Also, the name of
the currentMillis variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a reference to
the relevant PreviousMillis.

bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

And you use it like this:

void loop() {
  static unsigned long previousMillis1;
  static unsigned long previousMillis2;
  static unsigned long previousMillis3;

  if (timer(previousMillis1, 1000)) Serial.println(1);
  if (timer(previousMillis2, 2000)) Serial.println(2);
  if (timer(previousMillis3, 3000)) Serial.println(3);
}

I took the liberty of making all the previousMillis local to loop(),
since they are only used there. Making them static means their values
are remembered between call to loop(), much like global variables.

In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are explicitly manipulating
addresses, while this is implicit with references:

bool timer(unsigned long *last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - *last_time >= period) {
    *last_time = now;
    return true;
  }
  return false;
}

void loop() {
  /* [...] */
  if (timer(&previousMillis1, 1000)) Serial.println(1);
  /* [...] */
}

The next step in code modularity would be to wrap this timer function,
together with the associated data (last_time and period), inside a
class:

class Timer
{
public:

  Timer(unsigned long _period)
  : period(_period), last_time(millis()) {}

  bool shouldRun() {
    unsigned long now = millis();
    if (now - last_time >= period) {
      last_time = now;
      return true;
    }
    return false;
  }

private:
  unsigned long period;
  unsigned long last_time;
};

Then, you would use it like this:

Timer timer1(1000);    // period = 1000 ms
Timer timer2(2000);    // period = 2000 ms
Timer timer3(3000);    // period = 3000 ms

void loop() {
  if (timer1.shouldRun()) Serial.println(1);
  if (timer2.shouldRun()) Serial.println(2);
  if (timer3.shouldRun()) Serial.println(3);
}

Those lines like

currentMillis1;

are completely useless
You do not really have "timers", especially if your goal is to be more efficient. What you have done is to create some convoluted way to perform a test that could be done as:

int PERIOD = something;
for (int target = millis() + PERIOD; millis() < target;);
If you really care about efficiency and timed actions, check some library that deals with timer interrupts.
Start reading the code of existing libraries and try to understand it.
Chances are that who wrote them knew a great deal more than you know. You will learn much more from first reading the code than trying to accomplish something that is clearly too much beyond your current knowledge (the fact you think what you did is an optimization proves it).


Debouncing Multiple Buttons I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

Fixed Code: See accepted answer below.

       #include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

Your first problem is here:

char ReadKeypad(){
  if(button1.isPressed() && !button2.isPressed()){
    return 'D';
  }
  else if(button2.isPressed() && !button1.isPressed()){
    return 'U';
  }
  else if (!button1.isPressed() && !button2.isPressed()){
    return 'N';
  }
  else if (button1.isPressed() && button2.isPressed()){
    return 'S';
  }
}

The compiler gives a warning, which you should pay attention to:

In function 'char ReadKeypad()':
warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

The warning basically is that if no button is pressed you are returning an undefined value. It would be better to add to the end:

return 0;  // no button pressed

Then later on in page1 function:

  for (int i; i<16; i++){
    lcd.print(binary[i]);
  }

Another compiler warning:

In function 'void page1()':
warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
       for (int i; i<16; i++){

You haven't initialized i so it could have any value. That should read:

  for (int i = 0; i<16; i++){
    lcd.print(binary[i]);
  }

Ditto further down.

If I add some debugging here:

void MainmenuBtn(){
  btn_push = ReadKeypad();
  Serial.print ("btn_push = ");
  Serial.println (btn_push);
 // WaitBtnRelease();
}

And then press a button, I see:

btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D

So that is registering as many presses, not just one. You should test for "has the button state changed?". That is:

Is the button closed now?
Was it closed before?
If the two are different, then the button has just been pressed.

Adding debugging prints is very helpful in general when things aren't going to plan.

If you had added those extra prints to your MainmenuBtn function you would immediately have seen that it looked like the button was pressed hundreds of times (until you let go) rather than once.

  the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button

Exactly. Since it is treating a button press as a multiple press you would expect exactly that to happen. Effectively you have built in a very fast auto-repeat (unintentionally).

Edited to add:

Your code is so confusing I've rewritten the state change stuff.

#include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

I made the buttons INPUT_PULLUP so that they normally read HIGH if not pressed, thus LOW means pressed (therefore the switches should be wired from the digital pin on one side to Gnd on the other side).

It still isn't perfect but that should give you something to play with. Add some more debugging prints to see what is going on in the other functions.

As an alternative to using two inputs, consider using a single analogue input with several momentary buttons - each with differing resistor values in series - this will let you avoid debouncing altogether. Just 5/3V3->resistor->btn->analogInput.

At worst, you will need to smoothe out jitter on analog reads. Have a look at https://www.codeproject.com/Tips/709109/ADKeyboard-Library-for-Arduino


Recording and playback sound I'm working in an art project, is some kind of loop between contact microphones and walkie talkies. I want to create some kind of noisy feedback.

I'm putting one walkie-talkie inside of a bottle, and in front of the speaker/microphone from the walkie I want to put another contact microphone attached to an Arduino, and record the sounds of the walkie talkie and played with some delay in some buzzer in front of another contact microphone attached to an amp with three speakers. To sum up, I have like 3 parts linked between them, the first one the walkie, the second one with an Arduino and the third one a simple mic whith an amp and three speakers.

Only the second part will be working with the Arduino and I want it to record sound and play it simultaneously with some delay.
I worked with a friend with some servo motors and music shields and I've been doing some research. I found 3 very interesting projects one is this, that it's practically what I want to do Space Replaybut there's so little information about it, and the other two are Arduino Audio Input and Arduino Audio Output
So, my questions are:

If I use a music shield I don't need a DAC or/and an amp? or only an amp if my speakers are too loud?
In the project Space Replay they only use this music shield so with only one music shield I can record and play music simultaneously? or I need two music shields?
That Adafruit Wave Shield is only for Arduino uno, but it will be better or easier to work with DUE or Arduino Mega and another music shields or making my own circuits like in the instructables Arduino Audio Input and Output?

I don't care too much about the quality of the audio, as I said the purpose is make some noise. The only thing is I want to create some kind of echo, or some kind of cannon, between the first sound of the walkie and the others pick up sounds.

Any other comment or advice will be much appreciated and welcomed.
Thanks

Try using this shield from Adafruit. I believe it can record and play audio, and they have versions with and without amps.

I do not know about near-simultaneous playback, so read up a bit before buying.


ESP8266, prints ready at start but no response to AT command I have been using ESP8266 wifi module with Arduino as FTDI. The power for ESP8266 comes from LM317 5V - 3.3v regulated supply(I am sure 5V is powerful enough to give upto 1A of current).

The RX of ESP8266 is connected to RX of Arduino via a voltage divider to ensure 3.3V logic level. But still, I am not getting any response to AT command, though my laptop and phone wifi have successfully connected to AI-Thinker... SSID(which is an open hotspot from ESP8266).

I am also having some garbage values on the serial port immediately after I turn on the power supply to ESP8266. I have tested all baud rates available in Arduino IDE v1.0.5 with no results.

The resistor values for lm317 are R1 = 125 Ohm, R2 = 225 Ohm with which I am getting around 3.2 Volts.

The connections are as follows:-

-----Arduino UNO-----

RESET ------------ GND

Arduino UNO ----- ESP8266

TX ------------------- TX

RX ---5V to 3.3v--- RX

GND ----------------- GND

ESP8266 --------- LM317(5V to 3.3V)

VCC --------------- 3.3V

GND --------------- GND

CH_PD ------------ 3.3V

EDIT - 1: I have bought a new ESP8266, and even it doesn't responds to any AT commands, thought there is some difference in the previous ESP8266 output and this new ESP8266 output.

The difference is a sort of good news to me, it sends ready after sending some garbage at 115200 baud on boot which never happened with previous one(ESP8266).

Is anyone having some clue why there is no response to AT commands?
May it be a issue with TX line?

EDIT - 2: I have also used another Arduino with same connections doubting the TX pin on Arduino, but with same luck, bad luck. Still, nothing got changed.

EDIT - 3: I am shifting 5v to 3.3v by using three 100 ohm resistors.

Connect TX of arduino to esp8266 RX, and arduino RX to esp8266 TX.

See this link for more info.

First of all do not use any resistors(try it) for RX pin. Connect it directly.

Second connect RST pin of ESP8266 to 3.3V power supply.

And also try to use arduino directly with esp8266 once. Do not use lm317 or any other separate power supply. Use 3.3 volt power supply of arduino.

And i dont know why you have connected RESET pin of Arduino to GND. Please answer me that.


Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux) I use the Arduino IDE to upload sketches to my Arduino Uno. My OS is Linux Ubuntu 14.04 LTS. The Arduino IDE has two ports by default for communication with the Arduino Uno:

/dev/ttyACM0
/dev/ttyS0

What is the difference between these two ports ?
What does "ACM0" and "S0" mean ?
Are there configuration files somewhere in the OS folder structure that describe the parameters of these ports ?

I know that when I select /dev/ttyACM0, I am able to send data to my Arduino Uno. However it does not work when I select /dev/ttyS0.

I just want to better understand what these ports are exactly.

/dev/ttyACM0 is a USB communication device (CDC) of sub-type "abstract control model" (ACM). That is what the Arduino is.

/dev/ttyS0 is a hardware serial port - the (typically) 9-pin D connector on the back of your computer.

If you want to use /dev/ttyS0 (why would you?!) you will require a special cable that converts the RS-232 voltage signals from the 9-pin D connector into the right TTL level signals for the Ardiuno and wire it in to the right pins on the board.

Some high-level languages (e.g. matlab) treat all serial ports as the  /dev/ttyS# selecter.  To interface with an Arduino with MATLAB you have to rename /dev/ttyACM0 as /dev/ttyS#.

This may also be an option in the Arduino IDE, and that is why those options exist.


Using multiple laptop battery packs to power everything I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.

I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.

Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?

Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?

(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)

I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.

I'd be cautious about hooking them in parallel. According to ADAfruit power leakage between batteries is a problem.

  [multipack parallel] ... batteries are assembled by a company that is experienced and certified to test and assemble battery packs. The individual batteries are tested and sorted by machine so that each pack has matching batteries with the same capacity and internal resistance. Individuals do not have this equipment, which is why you should not try to make your own packs.

Are you certain all your batteries are the same age and have the same usage history? A brand-spanking new one will try to charge an old worn battery to its own fresh voltage.

I would use the elements of the batteries and build a big big one, ranging 12v and a lot of amperes, of course after reading at least 100 or 500 articles about that specific kind of battery so I can better understand it at low level, i.e not molecular level but close to. I might be wrong but having all of them around the same voltage (close to full discharge level) would allow you to connect them together without risks, then being them all interconnected in quasi-parallel mode would prohibit any of them from overheating the others, of course, a kill switch a brown-out protection for such current levels and a few temperature sensors embedded would be wise. Also remember, the ideal way to interconnect them is laton or copper strips, not copper cables or common soldering, spot welding is the word here. Good luck.


How do I set a continuous servo to turn on until a switch is flicked? I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

Here is my code:

#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

Any help would be appreciated.

Your are not debouncing your input buttons, which means that digitalRead(Closed) (and Open) will be HIGH in one execution of loop and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add Serial.print to know what is working and what not, and then correct the problem.

I seem to have got this working just by doing the following code:

#include <Servo.h>
Servo servo1;

int green = 12;       //Assinging the green and red LED to pin 12 and pin 13
int red = 13;

int Closed = 8;       //Assinging the Inputs of the toggle switch to 8 and 7

void setup()
{
  servo1.attach(4);    //Assigning the data pin for the servo
  servo1.write(86);     // Giving a starting speed to the servo

  pinMode(Closed, INPUT);        //Setting up the inputs for the two states of the toggle switch

  pinMode(green, OUTPUT);        //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);

  digitalWrite(Closed, HIGH);    //Turning on pull up resistors for the two inputs from the toggle switch

  delay(50);
  servo1.write(65); // start the motor opening
}

void loop() {
  if (digitalRead(Closed) == HIGH) { //If the toggle switch is changed then turn the servo in the oppisite direction
    servo1.write(100);
    if (digitalRead(Closed) == LOW) { // If the toggle switch is changed again then turn the servo off
      servo1.write(86);
    }
  }
}

Instead of using an external button I have had to use the reset button.


Problems recycling c++ lib with templated class for Arduino I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch->include library->MyLibrary shows in the dropdown menu and #includes properly).

Problem: Arduino IDE gives undefined reference to MyClass . . . error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code not work for Arduino IDE.

tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?

/e

Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

Queue.cpp

#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

.ino

. . .
Queue<float> avgQueue;
. . .

error

. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

SOLVED:

Combining the .cpp contents in the .h and removing the .cpp worked.

SOLVED:

Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.


Pause running program using a pushbutton I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?

Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?

Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.

Here's my code at the moment (sorry, it's not very clean):

int ledpins[]   = {4, 5, 6};
int buttonpin   = 3;
int buttonstate = 0;

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

  for (int pin = 6; pin > 3; pin--) {
    pinMode(ledpins[pin], OUTPUT);
  }
  pinMode(buttonpin, INPUT);
}

void loop() {
  buttonstate = digitalRead(buttonpin);
  if (buttonstate == HIGH) {
    digitalWrite(ledpins, HIGH);
  }
  if (buttonstate == LOW) {
    for (int pin = 4; pin < 7; pin++) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
    for (int pin = 6; pin > 3; pin--) {
      digitalWrite(pin, HIGH);
      delay(200);
      digitalWrite(pin, LOW);
    }
  }
}

The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.

I think you can use an interrupt for the button. In the handler you can set a state variable somethink like buttonPressed.

It could look like this in the handler:

....
if(buttonPressed != true){
buttonPressed = true;   //This only for the first time
}
else if(buttonPressed){
buttonPressed = false; //Delete the first flag
speedTime = xxx;       //This only for the second press
}
....

It could look like this in loop (you can set it to the top or bottom of your code):

....

while(buttonPressed){
//Do nothing (pause the programm)
}

....

Before setup write this and replace the 200 in loop with speedTime:

....
int speedTime = 200;
....

To pause your code you will need to wait until you are at the point with
while(buttonPressed). For example at the top or bottom. When you push a second time before you are at this point you will only change the time.

If you do not want to wait a time to pause than you will replace this delay(200) functions with something better.


Uploading a simple sketch takes forever I am trying to upload this simple sketch into my arduino with a shield I made. It takes forever (note I have the right COM port on)

  int sensorValue = 0;

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

  void loop(){
     sensorValue = analogRead(A4);
     delay(10000000);
     Serial.println(sensorValue);
     delay(10000000);
  }

Are you sure the problem is in the upload time? delay() takes the number of milliseconds you want to wait. In your code, it should take about 3 hours before the Arduino sends some data through the serial port.

If you are taking too much time for uploading means there is communication between another device is happening, please remove all TX and RX pins.


PC Cannot Access HC-06 Bluetooth COM Port I have an HC-06 Bluetooth module connected to an Arduino UNO board to allow for the data received by the Ultrasonic sensor to be transferred to my PC via bluetooth and serial communication. I am using the Putty program to view the data. The thing is, my PC says that it has paired with the bluetooth and I was able to see the COM number but when I opened Putty and entered the COM number while choosing the option 'serial' an error box appears saying: Unable to open serial port.

The way I am currently connecting my bluetooth to the arduino board is:

RX->pin 10

TX->pin 11

GND->GND pin

VCC-> 5V VCC

I am sure that the sketch in the arduino for serial communication via bluetooth is right as I have tested the system yesterday and it worked. Only after a time (say like 5-10 min) the connection breaks and I cant seem to figure out the problem. Oh and the Arduino is being powered by USB if that matters.

If you have powered the BT module from 5v you may have fried it, I recall that the hc-06 module is 3.3v and 3.3v signal too.


How do I run a bipolar motor with an arduino uno? At the risk of looking like a complete idiot on the internet, I'll preface with this; I'm incredibly new to this. I'm new even to coding, and not sure what questions I should be asking.

I'm trying to run a bipolar motor with an Arduino Uno. I'm fairly sure it should be as simple as set a pin to high, plug the motor into that pin and a ground and it should run. I did this a week ago, and it worked then.

Now I'm trying to essentially run a modified version of blink with this motor running instead of the LED. Running the code with pin 13 as my positive does still flash the LED. If I set my pin to high with the motor, the motor no longer runs. However, It does run when plugged into the 5V and ground. The motor also runs straight off of the two poles of a 9V battery.

I'm unsure what I'm doing wrong. Do I need to step up the voltage of my pins somehow?

Thanks in advance.
-Alec Rosso

Edit 1:Here's the code:

int motorPin1 = 13;
int interval= 5000;

void setup() {
pinMode(motorPin1, OUTPUT);
digitalWrite(motorPin1, HIGH);
}

void loop() {
digitalWrite(motorPin1, HIGH);
delay(interval);
digitalWrite(motorPin1, LOW);
delay(interval);
}

As far as voltage or current specifications, it says DC 12V.

Edit 2: it is not a stepper motor. The serial number is TS-32GZ370-950. It's apparently a "DC geared motor."

Final Edit: I've got it working using an L298. I used a 9-volt battery in addition to my arduino's 5 volts, and everything works like a dream. Thank you for your help.

Just for your knowledge and future reference - Arduino digital pins can deliver maximum of 40mA each. If you power Arduino by USB, Arduino UNO can draw maximum of 1A, and Nano maximum of 500mA. That is, the 5V pin can deliver that current, not a digital pin. Therefore pin 13(digital pin) can deliver 40mA at 5V, which is 200mW power.

Now, looking at your motor, TS-32GZ370-950,from datasheet at maximum efficiency the current needed is 140mA. Stall current is 480mA, therefore you should be able to deliver close to 480mA @ 12V for the motor to work under all possible loads. Now, that is 5.6W or so. Your 5V pin making the motor work simply meant that the load is low to medium. But you are unable to use the motor's full potential anyway.

Your driver choice is ok, because L298 can deliver up to 2 A, which is fine.
The 9V battery(Alkaline I suppose?) will work, but the lifespan will be very very short. You can look at discharge graphs here : https://www.powerstream.com/9V-Alkaline-tests.htm

It will last about 1 hour at moderate load. Consider using other types of batteries. Your motor accepts voltage up until 24V, so feel free to experiment.

Best of luck!

"At the risk of looking like a complete idiot on the internet,"

Without getting personal - you cannot put 10 pounds of potatoes in 5 pounds bag.

AKA you cannot run 12V device with (5V output) Arduino   BECAUSE 12V device / motor requires far more current than Arduino can safely provide.

That is the short version - you probably moved the motor at very slow speed and lucked out before you let the smoke out from the Arduino chip.


Arduino uploading to the wrong port I purchased a half dozen fake Arduinos hoping to build a bunch of projects without paying a fortune. I have all the drivers installed, and the port shows up in the Arduino IDE. The problem is when I try and upload the code I get the following error:

  can't open device "/dev/cu.wch": No such file or directory

I played around a little and tried running:

sudo ln -s cu.wch\ ch341\ USB\=\>RS232\ 1a1220  cu.wch

After running this a new port shows up called cu.wch, and if I select that it works.

The issue is the Arduino's port is cu.wch ch341 USB=>RS232 1a1220, but for some reason the IDE is trying to write to cu.wch. By linking the folders I can fix this but since it is a hack every time I restart my computer I have to rerun the command. Is there a way I can either rename the Arduino port or permanently link the folder?

I am using OSX 10.10 and Arduino IDE v1.6.3

I would guess the problem is the IDE not properly handling device names containing spaces. Consider your symlink a workaround rather than a hack - unless you want to repair the IDE itself.

I am not familiar with OS X but in the Arduino IDE you can select the port by going to Tools-->Port and select the appropriate port. To find the appropriate port you would have to go into the Windows equivalent of the Device Manager.

EDIT

The documentation from the official site might help.


Cannot drive DC motor with Arduino PWM I've programmed the Arduino Uno to generate PWM corresponding to the serial input values. And it works fine with an LED. I took the connection from PWM pin 3 (where I set the output) to the base of a BC548 transistor and connected the motor in series with an external motor power supply (Vcc) and the collector and the emmitter is grounded (to both Arduino's GND pin and the external supply's). The motor had a fly wheel diode, 4N4007, and a capacitor of 1 µF for protection.

But when I connect the motor and provide it with the PWM input, it works for a few seconds and then I see a few flashes in the rx and tx LEDs, and it stops working even with a serial input or reset. I need to turn it off and then on to make it work again. The same thing repeats when I connect the motor, but it works fine with an LED.

How can I fix that??

I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.

You might also want to consider purchasing a simple and popular L293D motor driver chip.  I teach basic Arduino classes and learning to use this chip is much easier than using transistors and diodes.  The other advantage is the motors can go both forward and backward!

On the following link you can purchase one chip for under $1.00 USD and each chip will driver two motors both forward and backward.

http://www.ebay.com/itm/New-L293D-L293-L293B-DIP-SOP-Push-Pull-4-CH-Four-Channel-Motor-Driver-IC-/371198300958


Controlling an RC car using Arduino I'm trying to replicate this: https://zhengludwig.wordpress.com/projects/self-driving-rc-car/ using pretty much the exact same controller and car.

I've soldered 4 wires to the controller, 1 for each direction. If I let the wires touch the ground on the controller everything works perfect. However, when I connect the wires to the Arduino nothing works. Sometimes left/right works for about 0.5 seconds then it goes back to doing nothing. Any idea on what the problem might be? Do I need to connect the controllers ground to the Arduino ground?

I've tried removing the batteries from the controller and connecting 3.3V and ground from the Arduino, which sorta works but I feel like it shouldn't be needed.

If I use the buttons on the controller while it's connected to the Arduino it goes either forward, right or forward+right.

The code I'm using to test everything looks like this:

void setup() {
  //Initialize the pins and serial
  pinMode(reversePin, OUTPUT);
  pinMode(forwardPin, OUTPUT);
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
}

void reset() {
  digitalWrite(forwardPin, HIGH);
  digitalWrite(reversePin, HIGH);
  digitalWrite(leftPin, HIGH);
  digitalWrite(rightPin, HIGH);
}

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

  digitalWrite(forwardPin, LOW);
  delay(4000);
  reset();
  digitalWrite(reversePin, LOW);
  delay(4000);
  reset();
  digitalWrite(leftPin, LOW);
  delay(4000);
  reset();
  digitalWrite(rightPin, LOW);
  delay(4000);
}

Images: http://imgur.com/a/rgpOY

Can you measure how much current goes through the wire when grounded (A: 2 mA from measurements in comments) ? And the open circuit voltage between the controller's ground and the control wire?  (A: 3.1V, from 2xAA)

If the current isn't more than the 40mA per pin/100mA per port, 200mA total, and the open circuit voltage of the controller pins is less than 5V, then you should be able to connect the Arduino's output pins and ground to your controller's wires and ground.

If the voltages and currents are higher, then you would need protection to prevent damaging your Arduino.

The controller and the Arduino should share a common ground, but without a circuit and without the controller's voltages and currents, it is hard to tell exactly what is wrong.

Edit: Since the controller's open circuit voltage and short-circuit currents (3.1 V, 2mA max) fit within the Arduino's capabilities, you can wire them directly to the pin outputs, and make sure the controller and the arduino share a common ground.

You need a fifth wire between the controller ground to the Arduino ground to make the logic levels actually communicate between the two devices.

You likely also need some 5V->3V level shifting to isolate the Arduino's output levels from the controller's inputs.   Top of the line would be MOSFETS, but you could possibly use a voltage dividing resistor pair.  See the hints in https://arduino.stackexchange.com/a/419/6628

We have to add 1k resistors and 2k resistors as 330 ohms instead and follow the link below..!


ESP8266: Client Server Based Home Automation System I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.

Connections isn't a problem so I am keeping those things aside. So far

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char *ssid = "AndroidAP";
const char *password = "qvdo2440";

ESP8266WebServer server(80);
String webPage = "";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void setup() {
  webPage += "
ESP8266 Web Server
";
  webPage += "
Socket #2 <button>ON</button>
&nbsp;<button>OFF</button>
";

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("Configuring access point...");
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.

And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.

I agree with most of 'Look Alterno's comment.  So here it is explained in more detail.

Each ESP runs a web server.
Each ESP will handle

GET /root/status
POST /root/change?device=x,state=y

When a client requests /root/status information on each relay managed by the device will be displayed.  For satellite ESPs this will mean displaying live data and for the central on it will mean displaying the last known state (it could also request an update at this time).  If you use an array then presenting this information will be quite simple.

When a client posts a change to a device then the satellite ESPs will change the relay state and the central ESP will forward the message onto the satellite.  It should probably also request a status update to check that the change has occurred.

If you steer clear of hardcoding things and use arrays rather than variable1, variable2, variable3 you should be able to make this expandable.  The biggest problem you will have is registering the satellites with the central device, but you could get around that for now by adding a configure page which had a HTML form that allowed you to enter the IP address of the central device and enter the name of the satellite and the name of the things connected to the relay.

Personally I wouldn't use a PC web server, yes it gives you more processing power, but I don't think you really need it for this, I was surprised how good they were.  If you have issues look at using an ESP32 instead of a ESP8266 for the central node.

I hope that helps

#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
String i;
long newvar;
String httpurl;
String TheHiddenAnswerOfClient;
HTTPClient http;
String SendWithAnswer(String IPcache, String monmessagecache)
{
  httpurl = "http://";
  httpurl += IPcache;
  httpurl += monmessagecache;
  http.begin(httpurl);
  http.GET();
  TheHiddenAnswerOfClient = (http.getString());
  http.end();
  return TheHiddenAnswerOfClient;
}

void setup() {
  // put your setup code here, to run once:
  i = "";
  newvar = 0;
  Serial.begin(9600);
  WiFi.disconnect();
  delay(3000);
  Serial.println("START");
  WiFi.begin("electromodule", "electromodule@456");
  while ((!(WiFi.status() == WL_CONNECTED)))
  {
    delay(300);
    Serial.print("..");
  }
  Serial.println("Connected");
}

void loop() {
  // put your main code here, to run repeatedly:
  i = (SendWithAnswer("192.168.0.2", "YES"));
  Serial.println("Before Clear");
  Serial.println(i);
  i.remove(0, 25);
  i.remove(i.length() - 11, 11);
  Serial.println("After clear");
  Serial.println(i);
  newvar = i.toInt();
  Serial.println((2000 + newvar));
}


How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor? Hi we are using Arduino Leonardo with some electric paint and Capacitive Sensor Libraries. We have a lot of variance in our Serial output from our sensors, we believe if we grounded the Arduino we would have more concrete values.

On the Capacitive Sensor doc, it reveals to use a small capacitor to put on one of the pins. More details!
Another guide somewhere says to wrap the Arduino in plastic and tin foil. These are vague, and we have not landed success when we tried.

Has anyone had success grounding Arduino Leo? Thank you.

The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.

However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.

One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.

Another could be to run two parallel traces in a spiral filling a large area

Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline.  Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.

It might help if you follow the diagram for connecting a button, that way the value of the capacitor sensor wont fluctuate...

Photo from http://arduino.cc/en/tutorial/button


why are there odd spikes in the USB serial data transfer rates? I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.

I looked into the serial communication using the simplest program I could, but it produces odd results.

void setup() { Serial.begin(9600); }
void loop() { Serial.println("00000"); }

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.

Using the seconds as a marker, I then count the number of data lines for each second.  for example:

44 00000  // recorded at time 44 seconds
44 00000
44 00000
45 00000  // recorded at time 45 seconds, etc

I was expecting that there would be a somewhat stable value for this.  Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second.  When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.

Collecting the zeros for 5000 seconds produced the following results:
most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000.  This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.

What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.

Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created.  That isn't too bad and could be due to timing.

But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.

The percent breakdown is as follows:

137 sets of 00000:  79.15%
138 sets of 00000:  13.8%
139 sets of 00000:  0.39%
140 sets of 00000:  0.51%
141 sets of 00000:  2.05%
142 sets of 00000:  4.11%

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain.  with 137 sets of 00000 there are 685 characters sent serially in one second.

with 142 sets of 00000 there are 710 characters sent serially in one second.

What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

Is there any explanation for the variability?

Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.

I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.

Using a delay of 8ms produced another interesting result:
with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters.  this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.

After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.

This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets.  The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.

I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second.  What could be causing this? and what can be done to make the transfer rates more constant?

While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.

As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its origin just by looking at the timing of its arrival.  That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.

A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino.  That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.

If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.

This could be largely to do with how USB serial works.

USB has a number of different methods of transferring data between the device and the host. Both CDC/ACM use FT232 use a method called bulk transfer. This is a very low priority transfer method and data is moved across the bus as and when it can - that is, when the bus isn't doing anything else. If there is anything else happening on the bus (and there will be) the transfers get delayed until the bus is doing nothing else.

If timing is critical for a protocol, such as USB audio or video where you have to have the data transferred to the host absolutely right now a different method is used. This is called isochronous. It is the highest priority of data transfer, even higher than interrupt data.

However there is no way on the Arduino to use any form of isochronous transfers so you will have to come up with some other method of managing your timing.

As Chris has mentioned the most common method is to include a timestamp with each packet of data. That packet may contain just one sample, or it may contain a block of samples. The important thing is to know when the block starts and from that infer the time of each sample within the block.

It is also important to ensure that your communication with the host isn't running at 100% saturation. You should be running at the highest baud rate that is reliable and only send data at regular intervals giving you time to get the data in between each transfer. Keeping your data packets as small and efficient as possible is also good for keeping you transfer rate sustained properly.


Run 'Serial.begin(9600)' before loop() My sketch looks somehow like this:

ClassA classA;

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

    classA = ClassA();
    Serial.println("Bar")

    ...
}

void loop() {
    classA.functionFoo();
}

The constructor of ClassA however calls some internal methods that perform a Serial.println().

My problem is, that the first (implicit) call of the constructor of ClassA comes in the first line of the sketch with

ClassA classA;

This is before the Serial interface has been initialized (with Serial.begin(9600)). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.

How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

In order to be sure that your classA object doesn't use the Serial.println() function before the baudrate is defined, it is necessary to add functions in your class ClassA and to inform from setup() your classA object.

The simplest way is to add:

a boolean bool bSerialReadyto keep the status of the Serial object,
in all ClassA constructors, initialize that bSerialReady = false;,
add a function void SetSerialReady() to switch the status bSerialReady = true;. The function should be called in the setup()function just after Serial.begin(9600);,
and in all functions of ClassA, add a if-condition if (bSerialReady) before calling the Serial.println().

Your class ClassA will become:

class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

Your setup() function becomes:

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

And in functions of ClassA, it looks like:

if (bSerialReady) {
    Serial.println("Bar");
}

Try something like this

void setup() {
      // nothing here
    }

void loop() {

    Serial.begin(9600);
    ClassA classA;
    while(1){

    }
}

Move everything inside setup to the loop just before while(1).


Arduino 3.3V Conversion I am fairly new to Arduino. As far I know all official Arduinos run on 5 volts. Or there is Arduino versions that run from 3.3V? I need use Arduino with devices which chipsets all use 3.3V logic level. Do I need modify Arduino to make it  3.3V powered, like described in this Tips, or there is another way? I plan get Arduino UNO R3 ATmega328P board (comes with bootloader for Arduino UNO ZT).

Arduino Pro Mini comes in 3.3v and 5v versions.

What about just getting the bare chip so you can run it at whatever rail you want? Seems like the simplest and easiest solution.


Arduino based SPI programming of LT1257 not working I am trying to talk to an LT1257 using an Arduino Nano Atmega328. I am not using the default slave select pin. I am using pin 5 as chip select for the DAC. The LT1257 data sheet shows this timing diagram. What I inferred from this diagram is that SCLK can be used to clock in the data and it remains in the shift register and is loaded into the DAC register only when Load is pulled low.

I wrote this snippet to load a 0x0000 to the DAC. However, when I probe the output voltage it is ~1.02V. The DAC uses an internal reference of 2.048V. So I think this must be the default 1/2*FS output when the DAC powers on.
Please review my code and point the errors. (At the DAC output I have a 1k resistor connected to ground).

#include<SPI.h>
#define SCLK 13
#define MISO 12
#define MOSI 11
#define DAC_LOAD 5

#define DAC_SPI_CLOCK_SPEED 1000000 //Upto 1.4MHz

void setup()
{
Serial.begin(9600);
init();
SPI.begin();
dac_write();
}

void init()
{
pinMode(SCLK, OUTPUT);
pinMode(MOSI, OUTPUT);
pinMode(MISO, INPUT);
pinMode(DAC_LOAD, OUTPUT);
digitalWrite(SCLK, HIGH);
digitalWrite(MOSI, HIGH);
digitalWrite(DAC_LOAD, HIGH);
}

void dac_write()
{
SPI.beginTransaction(SPISettings(DAC_SPI_CLOCK_SPEED, MSBFIRST, SPI_MODE0));
delay(10);
SPI.transfer(0x0000);
delay(10);
digitalWrite(DAC_LOAD, LOW);
delay(10);
digitalWrite(DAC_LOAD, HIGH);
delay(10);
SPI.endTransaction();
}

void loop()
{
while(1)
{
Serial.println("Ping!");
delay(1000);
}
}

I read the LT1257 data-sheet more carefully. There is a pull down nmos at the output of the DAC. So when uninitialized, the output of LT1257 should be ~0V. So the output I was measuring (~1.02V) is spurious. I suspect I damaged the IC. I tried the same code on a different LT1257 and it worked. I can confirm now that this code is working.

For a master to select an SPI slave to transmit data to it [the slave], the Slave Select pin is held low.


Arduino diy wireless Is it possible to do simple wireless on an Arduino, digital, or analog (SDR)? I would like to hook one pin to an antenna (or piece of wire) and generate signals with simple modulations (analog or digital).

here there's a nice tutorial on how to obtain it.

Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.

If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.

In this link they guys have ogn further and they even implemented a morse code library.

Now I am trying to figure out a way to do the same for a receiver.

Based off of what you have said, the simplest way to achieve what you want to do with your Arduino would be to use a WiFi shield, and setup the Arduino to function as a web server. I have included two links: the first link shows you Arduino's sponsored WiFi shield and explains the basics of how to use it. The second link addresses your question of using the Arduino+WiFi shield to generate WiFi signals, by setting it up as a web server. Both links contain sample codes from Arduino that you can copy and paste. Assuming that you are using the native Arduino software, you can also go to: File > Examples > WiFi > WiFiWebServer, and the same code from the Arduino websites that I listed will be there for you to use.

http://arduino.cc/en/Tutorial/WiFiWebServer

http://arduino.cc/en/Guide/ArduinoWiFiShield

Personally, I would always recommend that whenever you want to accomplish a certain task, such as WiFi signal generation, displaying characters on a LCD, or anything else, you search for a shield to use for that application. Shields always make life extremely easier. I hope this helps. :)


Why isn't ESP8266 connecting to wifi when calling yield()? I'm experimenting with ESP8266 and I want it to cycle through various states: LED on/off, WiFi on/off and measure the connection time, deep sleep.

I wrote the following script, using millis() to define the time intervals. I cut away the previous parts of the code to have a minimum test case.

I read that ESP8266 has the watchdog automatically on, so I used yield() when spending time waiting, instead of using an empty while loop. I didn't use delay() because it block further execution of the code, and I tend to avoid it. I know it would reset the watchdog too.

#include <ESP8266WiFi.h>

const char* ssid = "wifi";
const char* password = "pass";

const int led = 2;

void setup(void){
  unsigned long refTime;

  pinMode(led, OUTPUT);
  Serial.begin(115200);
  digitalWrite(led, 1);

  refTime = millis();
// isssue from here
  while ((millis() - refTime) < 3000) { yield(); }
// to here

  Serial.println("Connecting...");
  refTime = millis();
  WiFi.begin(ssid, password);
  Serial.println("");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // never gets here when "issue" code enabled
  Serial.println(millis() - refTime);
  digitalWrite(led, 0);
}

void loop(void){

}

If I use the yield(), then I never get a WiFi connection (well, it happened only once, actually).

Why is yield causing issues?

Insert refTime = millis(); inside while loop.


Can I power ESP8266 with more than 3.5 V? I am concerned whether I need to use a voltage divider to power my ESP8266 module. My concerns stem from the warnings that I have heard in multiple tutorials. Everyone seems to regard the ESP8266 as being very sensitive to supply voltage.

Has anyone use the ESP8266 with an supply voltage greater than 3.5 V? What were the effects? Is it even necessary to make a voltage divider?

I am asking because my application has limited real estate.

The datasheet usually is definitive on the allowable range of voltages.

Look in Section 5.1: Electrical Characteristics.

Working Voltage Value:

Min: 2.5 V
Typical: 3.3 V
Max: 3.6 V

If you have to feed in signals that could go higher than 3.3 V in normal operation, you need to either clamp it with Zener diodes, or use a voltage divider.

If you are asking about powering the chip with more than 3.3 V, don't. You can get away with a 3.3 V linear regulator and 2 capacitors so that you are powering it with no more than designed supply voltage.

The result to apply more voltage to a circuit is that the components will be burn. The same if you apply for a long time the maximum voltage. So the board works at 3.3v, your source maybe fluct between that but you will burn it if you apply 3.6 or more as a regular voltage.


Trying to move a stepper motor back and forth So, I am trying to move a stepper motor through a halfway revolution (1024 steps), and once that is completed, have it move back and forth by about 100 steps in either direction.

I am having some trouble with this though, because while it will move in one direction, it will not move in the other.

void setup()
{
    stepper1.setMaxSpeed(1000);
    stepper1.moveTo(1024);
    stepper1.setAcceleration(100);
    Serial.begin(19200);
    while(!Serial);
}

void loop()
{
    stepper1.run();
    static int ctr = 0; //counter value to store how many times the back and forth motion has occured
    if(stepper1.currentPosition() == 1024){
      backMotion(stepper1.currentPosition());
      forthMotion(stepper1.currentPosition());
      ctr++;
    }
//    if(stepper1.currentPosition() == 824 && ctr > 0 && ctr < 30){
//      forthMotion(stepper1.currentPosition());
//    }
}

void backMotion(int value){
    int current = value;
    int back_distance = current - 200; //distance to move back by
    stepper1.moveTo(back_distance);
}

void forthMotion(int value) {
  int current = value;
  int forth_distance = current+200;
  stepper1.moveTo(forth_distance);
}

So, when I call the forthMotion function right after the backMotion function, it will just move forward. Which makes no sense to me. Shouldn't it be moving backwards, and then forwards in an infinite loop?
Because it will hit 1024, go back to 824, hit 1024 again, and so on and on...

Also, when I call the backMotion function, isn't the Arduino code supposed to be blocking in that, nothing else gets executed while that is running?

Edit: The code seems to work when I uncomment the if statement in the loop function.

Steppers don't typically have feedback about their position (as opposed to servos). Normally you're just telling a stepper how much and how quickly to rotate. As opposed to servos, which you tell which position to rotate to.

Are you sure you're using a stepper?


How to program a CAN-BUS Arduino shield to control car windows? My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.

Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?

CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039

Arduino Mega: https://www.sparkfun.com/products/11061

What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.

Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v

Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.

In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.

I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.

Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.

I hope this helps.

the central lock system will close the car doors and close the windows, i think you should build your system with the same idea, dealing with windows motors as normal motor without special commands for the window


First Serial.print voltage is wrong, way too low. Ruins average calculation The first Serial.print voltage reading is so far off it really screws up the moving average calculation. For example, the first reading is like 0.00014981, which is wrong. From the second line on it prints the correct voltage, like 0.00475721. I don't know where this first line is coming from. How can I keep that first line from being used in the average calculation? Here are links to the sketch and adc.

https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

For the average calculation I added:

count = count + 1;

volt_mV = ((count-1)/count)*volt_mV + (1/count)*volt_V;

The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.

Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.

Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply exponential smoothing or some other form of smoothing to the readings.

Note, the formula you show for averaging – ((count-1)/count)*volt_mV + (1/count)*volt_V – has a number of problems.  First, if count is an integer, both of ((count-1)/count) and (1/count) will compute to zero values.  Secondly, as count becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a running average, it does not compute a moving average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like movingAverage = (15*movingAverage + newReading)/16.

The first Serial.print voltage is CORRECT with all others afterwards being wrong so the thing to do is USE the first one and ignore all other!