Esp8266 Arduino smart connect Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.

#include
#include
#include
#define ONE_WIRE_BUS 8
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

#define SSID "[YOUR_SSID]"
#define PASS "[YOUR_PASSWORD]"
#define IP "184.106.153.149" // thingspeak.com
String GET = "GET /update?key=[THINGSPEAK_KEY]&field1=";

void setup()
{
  Serial.begin(9600);
  sensors.begin();
  Serial.println("AT");
  delay(5000);
  if(Serial.find("OK")){
    connectWiFi();
  }
}

void loop(){
  sensors.requestTemperatures();
  float tempC = sensors.getTempCByIndex(0);
  tempC = DallasTemperature::toFahrenheit(tempC);
  char buffer[10];
  String tempF = dtostrf(tempC, 4, 1, buffer);
  updateTemp(tempF);
  delay(60000);
}

void updateTemp(String tenmpF){
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += IP;
  cmd += "\",80";
  Serial.println(cmd);
  delay(2000);
  if(Serial.find("Error")){
    return;
  }
  cmd = GET;
  cmd += tenmpF;
  cmd += "\r\n";
  Serial.print("AT+CIPSEND=");
  Serial.println(cmd.length());
  if(Serial.find(">")){
    Serial.print(cmd);
  }else{
    Serial.println("AT+CIPCLOSE");
  }
}

boolean connectWiFi(){
  Serial.println("AT+CWMODE=1");
  delay(2000);
  String cmd="AT+CWJAP=\"";
  cmd+=SSID;
  cmd+="\",\"";
  cmd+=PASS;
  cmd+="\"";
  Serial.println(cmd);
  delay(5000);
  if(Serial.find("OK")){
    return true;
  }else{
    return false;
  }
}

The following code can do what you want (source), all that is needed is to combine it with the sensor code. The default behaviour is to create an access point when it can't connect to the eeprom stored WiFi station but you can modify it to trigger with a button/jumper or any other way you prefer.

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

ESP8266WebServer server(80);

const char* ssid = "test";
const char* passphrase = "test";
String st;
String content;
int statusCode;

void setup() {
  Serial.begin(115200);
  EEPROM.begin(512);
  delay(10);
  Serial.println();
  Serial.println();
  Serial.println("Startup");
  // read eeprom for ssid and pass
  Serial.println("Reading EEPROM ssid");
  String esid;
  for (int i = 0; i < 32; ++i)
    {
      esid += char(EEPROM.read(i));
    }
  Serial.print("SSID: ");
  Serial.println(esid);
  Serial.println("Reading EEPROM pass");
  String epass = "";
  for (int i = 32; i < 96; ++i)
    {
      epass += char(EEPROM.read(i));
    }
  Serial.print("PASS: ");
  Serial.println(epass);
  if ( esid.length() > 1 ) {
      WiFi.begin(esid.c_str(), epass.c_str());
      if (testWifi()) {
        launchWeb(0);
        return;
      }
  }
  setupAP();
}

bool testWifi(void) {
  int c = 0;
  Serial.println("Waiting for Wifi to connect");
  while ( c < 20 ) {
    if (WiFi.status() == WL_CONNECTED) { return true; }
    delay(500);
    Serial.print(WiFi.status());
    c++;
  }
  Serial.println("");
  Serial.println("Connect timed out, opening AP");
  return false;
}

void launchWeb(int webtype) {
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("Local IP: ");
  Serial.println(WiFi.localIP());
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());
  createWebServer(webtype);
  // Start the server
  server.begin();
  Serial.println("Server started");
}

void setupAP(void) {
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
     {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
      delay(10);
     }
  }
  Serial.println("");
  st = "
";
  for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      st += "
";
      st += WiFi.SSID(i);
      st += " (";
      st += WiFi.RSSI(i);
      st += ")";
      st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
      st += "
";
    }
  st += "
";
  delay(100);
  WiFi.softAP(ssid, passphrase, 6);
  Serial.println("softap");
  launchWeb(1);
  Serial.println("over");
}

void createWebServer(int webtype)
{
  if ( webtype == 1 ) {
    server.on("/", []() {
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
        content = "<!DOCTYPE HTML>\r\nHello from ESP8266 at ";
        content += ipStr;
        content += "
";
        content += st;
        content += "
<form method='get' action='setting'>SSID: <input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
        content += "";
        server.send(200, "text/html", content);
    });
    server.on("/setting", []() {
        String qsid = server.arg("ssid");
        String qpass = server.arg("pass");
        if (qsid.length() > 0 && qpass.length() > 0) {
          Serial.println("clearing eeprom");
          for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
          Serial.println(qsid);
          Serial.println("");
          Serial.println(qpass);
          Serial.println("");

          Serial.println("writing eeprom ssid:");
          for (int i = 0; i < qsid.length(); ++i)
            {
              EEPROM.write(i, qsid[i]);
              Serial.print("Wrote: ");
              Serial.println(qsid[i]);
            }
          Serial.println("writing eeprom pass:");
          for (int i = 0; i < qpass.length(); ++i)
            {
              EEPROM.write(32+i, qpass[i]);
              Serial.print("Wrote: ");
              Serial.println(qpass[i]);
            }
          EEPROM.commit();
          content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
          statusCode = 200;
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          Serial.println("Sending 404");
        }
        server.send(statusCode, "application/json", content);
    });
  } else if (webtype == 0) {
    server.on("/", []() {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
    });
    server.on("/cleareeprom", []() {
      content = "<!DOCTYPE HTML>\r\n";
      content += "
Clearing the EEPROM
";
      server.send(200, "text/html", content);
      Serial.println("clearing eeprom");
      for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
      EEPROM.commit();
      WiFi.disconnect();
    });
  }
}

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

The configuration access point ssid and password are set in

const char* ssid = "test";
const char* passphrase = "test";

The default IP is 192.168.4.1. When you open it from a browser you see a screen which lists the available WiFi stations (ESP8266 scan result), the signal strength and an asterisk on locked stations. There are also two text boxes where you enter the ssid and password of the station you want to connect to and submit:

Note that there is a link to a similar library in the comments of the source link, that didn't work for me but you can try it.


How do I make the HC-05 bluetooth module take data from the HC-SRO4, and then send it to my Android app? Currently, I have an Arduino Uno set up, with a HC-SRO4 ultrasonic sensor printing distances of objects in front of it on a scale from 1-15 to the serial monitor. I want to attach the HC-05 bluetooth module and do the following:
First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

I understand the Android part may be out of scope of this forum, but please try to help me with taking data from the serial monitor and have it transmit the data.

Here is the code I have for the ultrasonic sensor:

const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  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);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

First, it will read the values from the serial monitor. Then, I would like the HC-05 module to take these numbers and continuously send it to my Android app, which will then process what to do with the numbers.

No. What you do is you connect your Bluetooth module to two digital pins, which you'll use, along with the SoftwareSerial library, just the way you are using currently the Serial object. Look at the SoftwareSerial examples in the IDE.

Before you use the HC-05 module, and transmit data, you'll have to make sure it is set up properly (baud rate, name, PIN code, etc). Plenty of code and tutorials on Google about that.


Cannot directly connect Arduino Ethernet to PC I have been following various tutorials (especially: this) to connect an Arduino Ethernet board to my Ubuntu PC via Ethernet directly.

The IP address of the computer was found to be 10.100.31.128, and so I tried addresses in this range (10.100.31.67, 10.100.31.121, ...) without success. DHCP also doesnt seem to work. For the MAC address I used the sticker on the back of the board. I am using a patch cable, maybe that's the problem?

Network problems can be complex.  If these suggestions are not right I can change the answer later if other solutions present themselves.

If you are connecting two Ethernet devices directly you may need a cross over cable.

To test your connection with out using IP addresses, try to follow what is discussed in this answer where the MAC address is used on a Ubuntu system instead of the IP address.

You also might try using wireshark to monitor the Ubuntu box's Ethernet port.


Cannot pass objects of non-trivially-copyable type 'class String' through '...' I'm attempting to send data from a serial connection to a GSM modem, but having problems.
The string from rx looks like this:

1.0 2.0 3.0 4.0

Here's my code to replace the spaces and then I just want to pass the whole string on, regardless of what's inside (there could be negative values too).

                data_current[data_index++] = ',';
                char received = bike_port.read(); //bike
                char test[32];
                inData += received;
                  if (received == '\n')
                  {
                      String nospace = inData;
                      nospace.replace("\t",",");
                      debug_println("Data: ");
                      debug_println(nospace);
                      inData = ""; // Clear recieved buffer
                      delay(1000);
                  }
                  sprintf(test,32,"%d,%d,%d,%d",(String) nospace);
                //strtok(received, tmp);
                for (int i=0; i<strlen(test); i++) {
                  data_current[data_index++] = test[i];
                }

I have also tried

sprintf(test,32,"%ld,(String) nospace);

What I get now is this error

cannot pass objects of non-trivially-copyable type 'class String' through '...'

Without the sprintf line I can successfully echo the string to debug_println (Serial Monitor).
What am I doing wrong?

The basic problem here is that you're trying to pass a String object to sprintf(). That isn't possible because String is a C++ class, and sprintf() is a C variadic function. The only way to pass a string to it is as a char *.

The rest of your call to sprintf() doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use sprintf() if you want to format several values into a string.

As you've suggested in the comments, adding the contents of nospace to data_current character-at-a-time would be the sensible approach. You could do it something like this:

for (int i = 0; i < nospace.length(); ++i) {
    data_current[data_index++] = nospace[i];
}

Note that strlen() won't work on nospace because it's a String object not a char array.

This is all assuming that there's enough space in data_current though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

Update:
As an alternative, you could use memcpy() to do a block transfer:

memcpy(data_current + data_index, nospace.c_str(), nospace.length());
data_index += nospace.length();

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)


Is there a Serial write buffer limit and does the Arduino reset if it is hit? I have an Arduino Mega 2560 that is resetting every 32 seconds if the serial monitor is not attached. Just before it resets, there is a flash of TX, then it goes. If ther serial monitor is attached it runs forever. Clearly I can't use the serial monitor to debug this so am clutching at straws as to what is happening.

Update:

Having eliminated all code and uploaded an empty sketch, no includes etc., the board still exhibits the reset. However, I have an Adafruit Ultimate GPS attached to the GND, 5V, TX1 and RX1 pins. When I remove it the resets stop. But with it attached and the serial monitor attached to the board, the resets also stop, even with an empty sketch. Spooky.

So, is it possible the GPS unit is filling a receive buffer, even if the serial port isn't set up to receive? I still have a problem that while I'm clearing and logging the GPS data, the resets are still at a regular 32 seconds, thus the reason I'm working on it still.

Note: The flash of TX no longer shows up with the empty sketch.

It turns out this problem had a very different cause, once I was able to eliminate the other variables. Having disconnected literally every component from the board and uploaded an empty sketch:

void setup() {}

void loop() {}

the board would still periodically reset itself.

I eliminated:

flushing the receive buffers,
eliminating all receives by disconnecting pins,
speeding up/slowing down the serial port/s,
speeding up/slowing down the GPS reporting rate,
auxiliary hardware,
code,
includes,
defines,
laptop power supply noise,
board revision in Arduino IDE,
Arduino IDE version,
USB port on laptop,
trying this hack to prevent the RESET pin from going low,
another Mega 2560 and a Due

None of the above influenced the issue.

The thing I did not think to check was whether the board would work with another power supply alone. This was a result of hunting for another power fault in service and with the laptop plugged in, finding a periodic, random reset.

Ultimately, I plugged the board into a monitor USB output, then a car charger power supply and finally found the issue was eliminated. Even plugging into another computer solved the issue. It appears that either the Arduino driver in Windows or the Arduino IDE software itself, would periodically poll the port, causing the board to reset. While the serial monitor was running, I assume the driver or IDE felt no need to poll the port, thereby leaving the board un-reset.


SSD1306Ascii Library Is there any way to add Inverse Text color function into SSD1306Ascii library like which is available in ssd1306 adafruit library ?

Yes, you can edit the library yourself, or copy its functions to your sketch and modify them.

You can also use another library, like u8g2.


Not able to receive the operation results from the slave after the command being sent by Master - SPI Brief - I am using two arduino Uno's. One acts as a master and the other as slave using Arduino IDE.  Below is the Master Code:

// Taken from Nick Gammon's Forum//

#include "SPI.h"
#include"pin_arduino.h"
int ss = 10;
void setup()
  {
    pinMode(ss,OUTPUT);
    Serial.begin(9600);
    Serial.println();
    digitalWrite(ss,HIGH);
    SPI.begin();
    SPI.setClockDivider(SPI_CLOCK_DIV8);
   }
byte transferAndWait(const byte what)
 {
   byte a = SPI.transfer(what);
   delayMicroseconds(20);
   return a;
 }
void loop()
 {
   byte a,b,c;
   digitalWrite(ss,LOW);
   transferAndWait('a');
a = transferAndWait(17);
b =  transferAndWait(33);
c = transferAndWait(0);
digitalWrite(ss,HIGH);
Serial.println(a,DEC);
Serial.println(b,DEC);
Serial.println(c,DEC);
delay(1000);
 }

Before I go into the details of the results I obtained and the problem, below is the Slave code:

//Taken from Nick Gammon's Forum//

#include "SPI.h"
#include "pins_arduino.h"
int slave = 10;
int miso = 11;
byte c = 0;
void setup()
  {
    pinMode(miso,OUTPUT);
    pinMode(slave,INPUT);
    Serial.begin(9600);
    SPR|= BV_(SPE);
    SPR|= BV_(SPIE);
 }
ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }
  void loop(void)
   {
     if(digitalRead(slave)==HIGH)
     c = 0;
   }

My Results : After dumping the master and slave codes into their respective arduino uno's, then when I open the serial monitor of the master code, It displays the number 17, 33, 0 and the same goes with the slave, meaning that the data is being sent to the slave and received back successfully, and hence I presume the SPI bus is working properly!. But why isn't the add operation happening?

Problem: Now the problem is, when the command 'a' is sent from the master to the slave, the slave has to interpret this 'a' command as Addition command and perform the addition of a number 15 to the incoming byte from the master as shown in the slave code, and return the results to the master, which should display the addition results in the  masters serial monitor. I am having problem performing this task and looking forward to suggestions on how to test or where I am doing wrong or make changes to the code or methods in order to get this working. I am expecting answers relevant to the below codes and method.

Since I wrote that example, I'll try to answer this. First I tested with the code from my page about SPI.

SPI Master

This is the master:

#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ();

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (20);
  return a;
} // end of transferAndWait

void loop (void)
{

  byte a, b, c, d;

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('a');  // add command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Adding results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  // enable Slave Select
  digitalWrite(SS, LOW);

  transferAndWait ('s');  // subtract command
  transferAndWait (10);
  a = transferAndWait (17);
  b = transferAndWait (33);
  c = transferAndWait (42);
  d = transferAndWait (0);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.println ("Subtracting results:");
  Serial.println (a, DEC);
  Serial.println (b, DEC);
  Serial.println (c, DEC);
  Serial.println (d, DEC);

  delay (1000);  // 1 second delay
}  // end of loop

SPI Slave

And this is the slave:

// what to do with incoming data
volatile byte command = 0;

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}  // end of loop

Test results

Testing gave the expected results:

Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

So, what is different in your code?

Your slave ISR:

ISR(SPI_STC_vect)
 {
   c = SPDR;
  switch(c)
    {
      case 0:
      SPDR = 0;
      break;

     case 'a':
     SPDR = c + 15;
     break;
   }
  }

This isn't quite the same, is it? In my code you get the command in one session (one interrupt) and what to use it for in another one.

Hence I had this:

  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

Sending a "command" of zero clears the current command. So the sequence being sent is like this:

0    <-- start a new command
command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55

Perhaps confusingly, I didn't send in that order, because I knew that the command would be zero initially(1), so I actually sent:

command  (ie. 'a' or 's')
22   <-- what to add to
33   <-- what to add to
44
55
0    <-- start a new command

There would be other ways of achieving this, but the fact is you changed the way the slave interpreted the incoming data.

I knew it would be zero because the slave sets the command to zero in the main loop if SS is not asserted.


ATmega328P and other chip sharing clock I am moving my Arduino project to another platform, operating at 3.3V. (5V from USB not useable due to some 3.3V-only chips in the design) Having read about this it seems that 12MHz is a good speed to use, and my stock USB to UART converter, CH340G does call for a 12MHz crystal.

Now what is the best way to share this 12MHz clock between CH340 and ATmega328P, eliminating an extra crystal? Can I tap off XO pin from CH340 with crystal attached, and carry it to the XTAL1 pin of the ATmega?

EDIT

If sharing clock requires some fine tuning, what about building a reference clock out of 74LVC1G04 and 74LVC1G06 chips and clock both chips from this?

Sharing a crystal between multiple devices is a very bad idea. The crystal is only a piece of the oscillator, the rest of it being a small bit of circuitry within the IC itself. Having multiple ICs connected to the same crystal will cause them to fight over who is driving it.

The datasheet for the CH340T/R, which I was able to find in English, says the following:

  When CH340 chip is working normally, the outside must supply 12MHz clock signal to XI pin.

This seems to imply that you can feed an external 12MHz clock into the chip and it will work. So we take the clock from the '328P and pass it to the '340G.

Programming the CKOUT fuse on the '328P will cause the internal clock to be output on CLKO, which we then connect to XI of the '340G. This means that that you will lose PB0/D8, but no longer need a second crystal. This also means that you will be unable to use the prescaler since doing so will affect the clock output.


arduino EM408 GPS problem I have written this little snippet of code to interface with EM408 GPS.

#include <SoftwareSerial.h>
SoftwareSerial GPS = SoftwareSerial(2,3);  //rx,tx
void setup()
{
  GPS.begin(4800);
  Serial.begin(9600);
}

void loop()
{
  //Serial.print(GPS.read(), BYTE);
  Serial.write(byte(GPS.read()));  //as of Arduino 1.0
}

Hardware side i have these connections:
ENABLE: 3.3V
Vcc   : 3.3V
Ground: Ground
Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial

However, the values i get are just junk data

ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

I get these without ending...
I experimenting with changing the baud rate, still the same thing goes on.
Any ideas?

EDIT:
I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...

The problem you get is that read() does not wait for a byte to be available, it just returns -1 if there is no byte available; converted as an unsigned byte that becomes 255.

In ISO-8859-1, which I guess is the encoding that your serial monitor is using, 255 translates to ÿ, so this is exactly what you observe.

Fixing this problem is straightforward, just check that a byte is available on SoftwareSerial before reading it:

void loop()
{
    if (GPS.available()) {
        Serial.write(byte(GPS.read()));  //as of Arduino 1.0
    }
}


RadioHead Library custom configuration for RFM96 LoRa I have a pair of Adafruit RFM96W LoRa Transceiver Breakouts and want to use them with the RadioHead library.

My pair of radios works if I use the example sketches from the adafruit tutorial, but I want to change their default configuration.

From the Datasheet of RFM96:

  For maximum flexibility the user may
  decide on the spread spectrum modulation bandwidth (BW),
  spreading factor (SF) and error correction rate (CR).

I want to configure the BF, SF and CR. I also want to be sure that the radios are working with the LoRa Modulation and that CRC is enabled.
And how to set Header-Settings?

I did find the method rf.setModemConfig() which gives the capability to change the configuration to library-pre-defined ones, which is not what I want. I want to try different combinations of settings.

I did find the method rf.setModemRegisters() but I did not understand how to use it.

Any solution is welcome.

Parameter in RH_RF95.h

const RH_RF95::ModemConfig myProfile =  {
  RH_RF95_BW_62_5KHZ | RH_RF95_CODING_RATE_4_5,
  RH_RF95_SPREADING_FACTOR_1024CPS};

rf95.setModemRegisters(&myProfile);


Can a Arduino Uno handle all these components? Its my first project with an Arduino, so please bear with the dumb questions.

For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.

Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).

Edit: a GSM sim800 as well lol

I think you're fine depends on the gyroscope model and lcd.
-For ultrasonic sensor thats 2 pins
-the lcd needs at least 6pins but with an i2c adapter you only need 2 pins
-3 push buttons 3 pins
-one pin for the buzzer
Plenty of room left on the uno


Cannot convert Serial String into char I am trying to write a program to control 4 motors through the Serial port. I planned on achieving this by sending the motors' speed and direction instructions as a string, which is then converted into numerical values that represent speed and direction. Unfortunately, the conversion process is not working and my motors will not spin.

int motorGroup1_Direction = 13;
int motorGroup1_Speed = 12;

int motorGroup2_Direction = 11;
int motorGroup2_Speed = 10;

int motorGroup3_Direction = 9;
int motorGroup3_Speed = 8;

int motorGroup4_Direction = 7;
int motorGroup4_Speed = 6;

String command; //First digit is for direction, the next 3 digits are for speed. A space acts a delimiter, repeat for the
//For the next three motors
char hold;
char letter;
char send[8];

void setup() {
  Serial.begin(9600);
  pinMode(motorGroup1_Direction, OUTPUT);

  pinMode(motorGroup1_Speed, OUTPUT);

  pinMode(motorGroup2_Direction, OUTPUT);
  pinMode(motorGroup2_Speed, OUTPUT);

  pinMode(motorGroup3_Direction, OUTPUT);
  pinMode(motorGroup3_Speed, OUTPUT);

  pinMode(motorGroup4_Direction, OUTPUT);
  pinMode(motorGroup4_Speed, OUTPUT);
}

void loop() {
  int trackParse = 0;
  int trackString = 0;

  while (Serial.available() > 0) {
    hold = Serial.read();

    if (hold == ' ') {

      send[trackParse] = (char)command.toInt();
      Serial.write(send[trackParse]);
      trackParse++;
      delay(2);
    }
    else {
      command[trackString] = hold;
      trackString++;
      delay(2);
    }
  }

  digitalWrite(motorGroup1_Direction, send[0]);
  Serial.println(send[0]);

  analogWrite(motorGroup1_Speed, send[1]);
  Serial.println(send[1]);

  digitalWrite(motorGroup2_Direction, send[2]);
  Serial.println(send[2]);

  analogWrite(motorGroup2_Speed, send[3]);
  Serial.println(send[3]);

  digitalWrite(motorGroup3_Direction, send[4]);
  Serial.println(send[4]);

  analogWrite(motorGroup3_Speed, send[5]);
  Serial.println(send[5]);

  digitalWrite(motorGroup4_Direction, send[6]);
  Serial.println(send[6]);

  analogWrite(motorGroup4_Speed, send[7]);
  Serial.println(send[7]);

}

You try to convert the whole command string everytime a space character appears. This works good for the first occurence, but then the string will become longer and longer and the converted integer will be garbage. You should reset the string with command = "" everytime you have processed a number, or just using the current part of it with the substring member function.
Currently you echo the converted integer with Serial.write(). With this, the pure byte code is send over the serial. Your terminal program will interpret the bytes as characters, so you may get human readable numbers. Try the function Serial.println(), which converts the number to a human readable form and prints a newline after it as a delimiter.
You don't need to write to your outputs on every loop cycle. Especially the Serial prints will make the debugging more difficult. I think you should only write a new value to your outputs, when you received new values over Serial.
Am I right, that your protocol looks something like this: "0 255 1 100 1 150 0 80" ?
In your current code, if not the whole string is received in one loop cycle (maybe if there was some delay when sending from the computer) the rest of the string is than written to the first motor values. You can use a packet delimiter character like "\n" after a full packet. Then you can collect all received characters in your command string until you receive the "\n", which marks the end of the current package. Then you would process the packet as a whole.


'readPulsioximeter' was not declared in this scope I am new to Arduino. I am trying to use Pulsioximeter sensor with e-health Platform (http://www.cooking-hacks.com/documentation/tutorials/ehealth-biometric-sensor-platform-arduino-raspberry-pi-medical) on Arduino Uno. Line number 13 is working fine in the example code given in the library and works just fine. But when I try to upload my custom code (setup function definition is given below), I get an error stating 'readPulsioximeter' not defined in this scope. The error doesn't seem obvious to me. Please guide.

Here is the custom code upto setup() function:

#include < eHealth.h >
#include < PinChangeInt.h >
bool configuration = false;
//bool in_it=true;
byte val; // variable to receive data from the serial port
int ledpin = 13; // LED connected to pin 48 (on-board LED)
int A=1;
void setup() {
           pinMode(ledpin, OUTPUT);
           Serial.begin(115200);
           eHealth.initPulsioximeter();
           //Attach the interruptions for using the pulsioximeter.
           PCintPort::attachInterrupt(6, readPulsioximeter, RISING);
           delay(500);
}

 EDIT1:
readPulsioximeter is declared in eHealth.h library which has been included in program. The function has been defined as below in eHealth.cpp file:

    //!******************************************************************************
    //!     Name:   readPulsioximeter()                                             *
    //!     Description: It reads a value from pulsioximeter sensor.                *
    //!     Param : void                                                            *
    //!     Returns: void                                                           *
    //!     Example: readPulsioximeter();                                           *
    //!******************************************************************************
    void eHealthClass::readPulsioximeter(void)
    {
        uint8_t digito[] = {0,0,0,0,0,0};
        uint8_t A = 0;
        uint8_t B = 0;
        uint8_t C = 0;
        uint8_t D = 0;
        uint8_t E = 0;
        uint8_t F = 0;
        uint8_t G = 0;
        for (int i = 0; i<6 ; i++) { // read all the led's of the module
            A = !digitalRead(13);
            B = !digitalRead(12);
            C = !digitalRead(11);
            D = !digitalRead(10);
            E = !digitalRead(9);
            F = !digitalRead(8);
            G = !digitalRead(7);
            digito[i] = segToNumber(A, B, C ,D ,E, F,G);
            delayMicroseconds(2800); //2800 microseconds
        }
            SPO2 = 10 * digito[5] + digito[4];
            BPM  = 100 * digito[2] + 10 * digito[1] + digito[0];
    }

The problem is that you have no function called "readPulsioximeter" in your code. Either define it, pick a different function, or remove that line of code.


Powering my Arduino Mega project What power source should I use for my Arduino Mega project (involves 2 steppers, 2 servos and 2 dc motors)?

I tried to run two stepper motors with 9V battery. But the battery dried out. I am thinking of 8 AAA batteries. Is there a better option? How about powering through Arduino with the help of a DC adapter?

To properly answer this, you first have to determine how long you want your application to be able to run on a full charge. Clearly, it'll run on a 9V battery, but not for very long.

To determine the appropriate power supply, you need to calculate the overall voltage and current requirements for the various components.

The Mega needs a pretty minimal power supply, just 5V @ 200mA.

You don't specify the ratings for your motors. Servos are typically 5-6V @ 500mA, but I'm only guessing. Steppers and DC motors vary quite a lot.

The first step would be to find the specifications for all your motors, and find the maximum values, specifically the operating voltage and stall current. Hypothetically, say the maximum voltage for all the motors is 5V, and the stall currents for the steppers, servos and DC motors are 1A, 1A, 500mA, 500mA, 3A, and 3A respectfully. (Again, this is just an example. Find the true values yourself). That means you'll need a supply that can safely deliver 1+1+0.5+0.5+3+3+0.1 = 9.1A @ 5V or 45.5 watts.

If you want to use a battery (instead of a stationary supply like a DC adapter), you'll need to chose a battery with adequate mAh rating, which is the total number of amps it can deliver in 1 hour.

Perfectly predicting battery life greatly depends on the battery chemistry and your application's average current draw, both of which great very complicated, so I won't go into that here. A battery is considered effectively "dead" when it's depleted to around 80% of it's fully charged voltage. You can lookup the formulas and do the math yourself, or you can use some online calculators to help you estimate discharge times for different battery and load configurations.

However, as a general rule of thumb, you want to select a battery with a voltage greater than the minimum voltage required by any of your components. For your application to run for 1 hour, it's mAh rating should also be greater than your application's total current consumption. To run longer, you'll need to find a battery with a higher mAh rating, or higher voltage that a switching regulator can use to convert that extra voltage into current.

The other important factor, which complicates these calculations, is the type of voltage regulators you use. If you want to power everything from a single battery, you'll definitely need some voltage regulators. Preferably, you should use high-efficiency switching regulators. For this purpose, you can find cheap UBECs used for RC applications on Amazon or Ebay. You should have one for the Arduino and each motor (or pair of motors if you want to save on cost or complexity). Just make sure the regulator's voltage and current requirements are greater than what's consumed by your components.

I find using 2 or 3 Lipo batteries in series, especially 18650 cells, are the cheapest and easiest way to provide power for mobile applications that have high spikes due to motors. For stationary applications, a 12V DC wall adapter with a high current rating would be simpler.

If you want to use akalines, I'd recommend using separate batteries for the Arduino and motors. Akalines aren't well known for being able to deliver high current. Motors can demand a lot of current, and if the battery can't deliver enough, it'll cause the voltage to drop, resulting in the Arduino browning-out. However, lipo batteries, or non-rechargeable lithium batteries are better suited for this.


ESP8266 send number in IP address I want to easily send a number from a phone to my esp8266.
I have an app that sends the number in the format IP/number.
How can I modify the code to give my the number behind the IP address as an integer?

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

MDNSResponder mdns;

// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

ESP8266WebServer server(80);

String webPage = "";

void setup(void){

  delay(1000);
  Serial.begin(115200);
  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", WiFi.localIP())) {
    Serial.println("MDNS responder started");
  }

  server.on("/", [](){
    Serial.println("device connected");
  });
  server.begin();
  Serial.println("HTTP server started");
}

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

So it would do something like this for and should be looking through every i between 0 and 200. :

server.on("/"+String(i), [](){
    Serial.println("i");
  });

First of all use the event function server.on with a path that corresponds to your function and use a url like this:

192.0.2.2/recordnumber?num=100

With a url parmeter for your number. Your code might look like this:

At the top:

int nums_size = 0;
const int nums_max = 128;
int nums[nums_max];

In setup:

server.on("/recordnumber", [](){
    int num;
    if(server.hasArg("num")) {
      String num_str = server.arg("num");
      if(num_str.charAt(0) == '0') {
        num = 0;
      } else {
        num = num_str.toInt();
        if(num == 0) {
          server.send(400, "text/plain", "not a number");
          return;
        }
      }
      if(nums_size < nums_max) {
        nums[nums_size++] = num;
        server.send(200, "text/plain", "saved");
      } else {
        server.send(500, "text/plain", "full");
      }
    } else {
      server.send(400, "text/plain", "bad params");
    }
});


Arduino Clock Speed effect on Stepper Speed I am running a Pololu A4988 Stepper driver with two (soon to be three) steppers using the AccelStepper library. I have wired 1/8th microstepping on both as smooth running is important.

The motors run fine however, when running simultaneously, if Stepper 1 finishes its move before the Stepper 2, there is a marked increase in speed in the Stepper 2 (evident audibly and visually).

The code I use to run the motors is:

void MoveAccelXY(int Xm, int Ym) // function 6
{
  X_Axis.moveTo(Xm);
  Y_Axis.moveTo(Ym);
  while(X_Axis.distanceToGo() !=0 || Y_Axis.distanceToGo() !=0)
  {
    X_Axis.run();
    Y_Axis.run();
  }
  Xpos = X_Axis.currentPosition();
  Ypos = Y_Axis.currentPosition();
  Serial.print("X" + Xpos);
  delay(50);
  Serial.print("Y" + Ypos);
  delay(50);
  Serial.print("C");
}

I would like there to be no speed drop on any steppers. Increasing the input voltage does not have an effect.

Is the Arduino clock speed the culprit?

Without seeing the rest of your code, the best guess - and I think it is quite likely - is the use of delay() and printing within the stepper function. With 2 motors running, and even ignoring the printing time, there will be a total of 200ms taken up by the delays. That means each motor gets serviced a maximum of 5x/sec. Stop one motor, and the other one can double that to 10x/sec.

Look at the Blink Without Delay example for one way of managing timed events without calling delay(). The SimpleTimer library provides another.

Update:

  ...run() events are triggered within a while() loop ...

Ah, yes, I see that. So it looks like only one motor could run at a time - the while() loop runs until this motor reaches its target. But you said you run two at a time. So yes, I think understanding the rest of the code will help.


How to send command from coordinator to router in Xbee? I am using an XBee-PRO S2b module. I have sent data from the router Xbee to the coordinator Xbee.

Now I want to send a command packet from the coordinator to the router Xbee to set a pin high.

My coordinator is in API mode and the router is in AT mode.

Can anyone say how to do that?

In order to change the router from the coordinator, you have to create a function that run in a microcontroller that is connected to the coordinator.You can refer to this link , https://www.youtube.com/watch?v=CzH146rR-7I&t=236s


LM335Z temperature sensor gives very varying values I'm trying to get consistent values from the LM335Z temperature sensor. But it behaves very strange.
I'm using an arduino nano and it's powered via USB from a Raspberry Pi. The circuit also has two little reed relays (SIP-1A05), a button and a potentiometer.
It's connected like this:

Additionally I'm using analogReference(EXTERNAL) in an attempt to get consistent values, so I've connected the Arduinos 5V output to the reference voltage pin.
Here's the code for reading the thermometer:
int getTemperature() {
  int rawvoltage = analogRead(0);
  float millivolts = (rawvoltage / 1024.0) * 5000;
  float kelvin = (millivolts / 10);
  float celsius = kelvin - 273.15;
  return round(celsius);
}

Then it just waits for me to say "get" in the serial monitor and it replies with:
void sendData(){
  String data = (String)getTemperature();
  data += ',';
  data += (String)map(getTablePos(), 0, 1023, 0, 100); //Potentiometer
  data += ',';
  data += (String)getTableActive(); //1 or 0
  Serial.println(data);
}

I also read somewhere that the first couple of readings are unreliable, and that you should read a couple of times in startup, which I do:
for(int i = 0; i < 10; i++){
    analogRead(0);
    delay(1);
  }

Yesterday the termometer reported 37 degrees. Today it started by reporting 49 degrees. After asking for the temperature a couple of times it said 56. Then now, about an hour later it says 52. And if one of they relays is active it says 77 degrees.
My two other (non Arduino) thermometers have ben on a steady 25 all this time.
What should I do to get reliable values from the LM335z?

Edit
Added dots to the intersections of the circuit diagram for better readability.
I've also found a way to get the thermometer to work, kind of. I removed the external analog reference and only have one 1kOhm resistor for the LM335Z.
Then I have this code instead:
const float cal = 4.62; //Voltage between 5V and GND, measured with multimeter

float getTemperature() {
    float input = (float) analogRead(0);
    input = (input*cal)/1024.0;
    return (input/0.01)-273.15;
}

It worked perfectly standalone on an Arduino Uno powered via USB3.0. When I moved it over into my project with the Nano it gave a few degrees off, but that can be combated by just subtracting the difference I guess.
Then I tried switching to a USB2.0-port on my keyboard, and the values started jumping all over the place.
Here's a comparison using Arduinos rather spartan plotter:

Left: USB2.0 via keyboard hub. Right: Front panel USB3.0.
Also, the temperature dubbels when a relay is on.
How do I tackle this? I'd like keep powering it from my Raspberry pi 3, if possible.

According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.

You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).

In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.

Update:
I based my connections description on this diagram

, from this datasheet. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.

I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.


Remote temperature and humidity sensor with long battery life I want to build a remote sensor which will measure temperature (range 5-30°C) and humidity (range 20-90%) and provide regularly (in the range of one measurement every minute or tenth of minutes) the measurement via wireless. This sensor will be used indoor, mostly in dark areas.

Note: measurement could be done every minutes and sending them could be done immediately or in batch of 10 measurements or more).

I was looking to build this solution using an Arduino, DHT22 sensor and a radio transmitter using ZigBee or Z-Wave protocol, and power it via AA rechargeable batteries. But after studying this solution, I found that it would be challenging to even get a week of battery life, this would require using the radio sparingly and to try to use as much as possible the power modes of the Arduino ATmel controller.

That's not enough, I want a battery life in the range of several months, 1 month would be "acceptable", 6 months would be the target, breakthrough would be > 1 year.

Note: I don't want wifi, this seems to suck even more power than the other mentioned radio protocol

Questions

Is there another more power efficient way to wireless-ly transmit the data?

Or shall I reconsider Arduino all together and look for another more power efficient controller?

Or is there another way?

I made a Temperature and humidity sensor - battery powered in 2013. It is powered from 3 x AA batteries, and lasted, as I recall, until a couple of months ago before I changed the batteries. That is, almost two years.

It logs to an SD card every 15 minutes. You could change that interval of course, it would probably not last as long logging every minute.

I certainly wouldn't attempt it with a pre-made board, because of the drain by the power LEDs, the USB chip, the voltage regulator, etc.

I measured 6 µA consumption when asleep.

Schematic

(RH-click and "View Image" to see a larger version)

The schematic is deliberately presented as "blocks" of parts of the circuit. To understand it from scratch, make up individual parts, test them and get the code working to your satisfaction. For example, the clock or the temperature sensor.

Some of the parts (like the clock) are already available as pre-assembled boards, if you prefer to reduce soldering.

You could manage without the 7-segment LED readout, however I found it useful for confirming it is working "in the field". The readout LEDs can be purchased cheaply from eBay for around $US 3. Search for MAX7219 8-Digit LED Display Module 7-Segment or similar.

Example output

Example of measuring temperature and humidity every minute:

You can see from the graph that I left the room at 9:30 pm, and the temperature slowly dropped until 6:30 am the next morning. The zig-zag effect is the central heating turning on and off.

Construction details

See the linked page for construction notes, schematic, and code.

Power saving details at Power saving techniques for microprocessors.

Estimated life at logging once a minute

If my calculations are correct, logging every minute might reduce battery life to 7 months (these things are best tested of course), but that is because the consumption is much higher when you power up the SD card. It would probably be best to take 15 readings, and then write to the card every 15 minutes. The extra time writing would be minimal, and that would keep the need to power up the card low.

The 7-segment LEDs

To clarify, those 8 LEDs are not normally on. The battery wouldn't last long if they were! If you press the switch it gives an immediate reading through the LEDs, and also tells you how many writes to disk it has done, and how many write errors it has had. This confirms all is operating properly.

The "busy" LED is there to warn you to not remove the SD card while it is writing to it.

Radio communication

To transmit information you could use a NRF24L01 transceiver module. You get those for a couple of dollars on eBay. Example:

Underneath:

You would need another one at the other end to receive (you would need two of whatever radio you chose).

I did a solar powered project using a couple of those. The NRF24L01 uses about 0.9 µA in power-down mode, so that is pretty minimal.

It also uses SPI, so the connections would be very similar to the SD card connector.

I suggest if you are going to attempt this to first get confident with a normal Uno, get the code tested, make sure you have the sleeping/waking going OK, then move it to a low-power board. There are places like Evil Mad Scientist that make "bare" boards, with a prototyping area, which you can use to put things like your temperature sensor on.


Rotate a brush less motor using arduino only I connected a brushless motor to 5V and GND pin of Arduino Uno connected to my laptop via USB. I ran the servo motor code in the examples list but the motor did not work. Is it possible to rotate motor using Arduino only without ESC or h-bridge and how?
Thanks in advance..

By brushless motor, do you mean a BLDC (brushless DC) motor? If so, no this is unfortunately not possible. You need to synchronize your phases to actually rotate the motor. Hence the ESC or an h-bridge with your own code. On top of that your Arduino doesn't have the power, nor the safety circuits in place to prevent the energy in the motor from not killing the board when you turn it off.

The servo library is used for, lack of a better term, the hobby servo motors.

http://www.instructables.com/id/BLDC-Motor-Control-with-Arduino-salvaged-HD-motor/

Here's an example. You're looking to do the same. Good luck!


How to read a higher voltage digital input? Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.

I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.

How can I do this?

As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.

This EE.SE post has some good info about this, related to ADC, but still the same.

First off, a voltage divider circuit is easily found on the internet,

Google
Wikipedia

This circuit from Hyperphysics shows the basics:

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the Vout.
That would give you something like this(Olins):

This will give you the desired range to give legitimate High and Low on an I/O.

If you wanted to forgo the voltage divider and zener you can use clamping diodes to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

simulate this circuit – Schematic created using CircuitLab

The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

The logic is that, when the input IN is > Vcc(5V) the signal on the I/O _IN will be the voltage of the pull_up resistor R2, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.

Edit: Changed the image to proper logic flow.


Arduino Mega: which Digital pins are already used for something? I got an Ethermega, and learned that Pin 13 already has a LED.

Are there other digital pins with special circuitry or already allocated to a specific function? (like usb,serial,ethernet,sd, etc)

I need about 30 inputs so I can skip some if that would avoid headaches.

Don't worry about the led on pin 13, it just sits there but doesn't block anything.

You can still use the pin as a normal IO pin.

You didn't mention whether your 30 inputs are digital or analog, so let's have a look at digital input first.

I have never used the MCP23017 mentioned by Martynas, but the linked article looks very interesting and I'll definitely order one of these amazing chips!

Another option might be using 8 bit PISO (parallel in - serial out shift registers, such as the 74HC165. Consider this as the complement to the 75HC595 for output. These shift registers are dirt cheap (around 0.3 €), are available as DIP (important for breadboarding) and can be run via SPI.

Advantages:

it's fast to read in 8 digital lines into a byte (why would one want to use more than a bit for the state of a digital input?)
the shift registers can be daisychained, subsequent calls of ShiftIn allows to read all (digital) input states into a corresponding data structure (array of bytes, etc.) using just three pins on your Arduino.


Arduino wire question I am a complete newbie to Arduino and I just received an ARDX arduino starter kit (the one that comes in the transparent green case)
I have been following the instructions for Circ-01 for the blinking led light but I am curious about the wires. In the breadboard instructional picture it shows a purple wire that is supposed to connect to pin 13 on the arduino. But the kit did not come with a purple wire, it only came with black, red, white, yellow, and green wires.

I also tried following a tutorial on YouTube and the guy in the video used a purple wire that he said was the led "cathode"

Can i substitute another wire for the purple and? Or did I receive an incomplete kit? I am very confused and the breadboard instruction picture is not very clear.

Thanks for any help!

Personally I like to try to use red wires for +5V, black or blue for ground, and yellow for data. However as Majenko said in a comment, the colour is irrelevant to the operation.

The usefulness of colour is just that if you stick to a system (like red for +5V and black for ground) then there is a visual check you make when connecting up a circuit, so you don't accidentally put things in backwards, like you might if every wire is yellow.

Also, if you run half-a-dozen wires from one place to another, using different colours is another way of making it easier to see you have connected the correct things together.

Having said all that, the colour does not otherwise affect things.


Using an Arduino for a Diorama Controller Kind of new to the whole DIY electronics scene.

I'm building a diorama for my son.  It will include a length of track, a station, some other buildings, and scenery.  It will be HO scale.  The buildings came with these cool little LED lights and I've bought additional ones as well.  I want it to be of the period of the late 1800s to early 1900s.  So the additional LEDs I bought give off a more "yellow" light to simulate candle/lantern light.  The track is not a circuit and is not powered.  It is just "static" to sit a train so it appears to be at the station.

I have the following questions:

Could I hook up the LEDs to a Arduino and have the different buildings (or floors within a building) be controlled separately?
Could I make the LEDs "flicker" to simulate candle/lantern light?
Could I maybe hook up a little speaker inside the train station to give off train noises, whistles, conductor calls, etc?
Could this setup (Arduino with LEDs/speaker) be run off of batter power (not a custom battery, just off the shelf AAs, AAAs, or Cs, etc.)?
Is an Arduino instead the appropriate controller for this kind of project?

I think this is a great opportunity to teach my kids not only modeling but also electronics (myself as well on the electronics).

Thanks in advance for any help/suggestions.

EDIT:

A little more about the setup.  The LEDs are made specifically for this type of application (model buildings/railroads).  Hence, they already have an 1800 ohm resistor attached to the input side of the LED.  There will indeed be multiple LEDs per building (even per floor).  I would like to at least isolate the circuits by building and even better if I could isolate them by floor.  I think it would be cool to have the software cycle the buildings/floors on and off at different times.

A smaller form factor for the Arduino would be ideal as it will have to fit into one of the scale buildings.  I've never really worked with the Arduino so I don't know all my options.  I've done a little with the Raspberry Pi and originally posted this question there and was told the Raspberry Pi would be overkill for this type of application.

First, since you didn't mention any kind of Arduino, my answer is based on using Arduino Uno/Nano (I think its the most common)
 1. Yes you can. You use 1 transistor per building as switch (if there are many LEDs in the building) to gives optimal current and prevent your Arduino pin. The value of R2 -- Rx is depend the LED colour. You can control each group with one Arduino pin.

simulate this circuit – Schematic created using CircuitLab

Yes you can, one in my mind is using PWM feature, like this project
Yes you can. But maybe the generated sound is not up to your expectation. Here is one of the simple example and this maybe a bit challenging.
The battery is up to your setup. More output (such as led and speaker) requires power source that can provide greater current. Arduino Uno voltage limit is 6v-20v
In my opinion, yes.

As for the form factor, I think Arduino Nano is small enough to hide in the building, while Arduino Uno size is just slightly less than a Raspberry Pi.

Good luck for your project :)


6 wire 3 digits 7 segment display and arduino question Here's a brain teaser for you:

I have the following 3 digit 7 segment display that has only 6 wires

Experimentally I found out how it works, even though I don't understand it, but anyways every segment is lit by a combination of HIGH and LOW of certain two pins, the combinations are below:

So I tried to make it work, but encountered the following problem (as you can see in the first picture): if, for example, I want to activate the segment that requires pin 5 high and pin 6 low, it also activates the other segments that require 5 to high, because apparently if a digital output is not high, it's automatically pulled to ground, and that's a problem.
I tried by setting the other pins I don't use in a segment to high, but then the segments that require 6 low are being activated, so that didn't work.

Other option I have would be transistors or a tri-state buffer, but for that I need all 12 digital inputs of arduino for the two states of each pin of the display.

Hope you understand what my problem is and maybe you have some advice on how to solve it.

Thanks in advance!

Edit: I managed to drive every segment individually using a small delay, and it works if the sketch has only the code for the display, but as soon as I add more code (for the temperature sensor I want to use) it starts to malfunction. You can find the code below.

LE: I managed to make it work by leaving only the display function in the loop and calling every 5 seconds the function for the temperature sensor. It still refreshes the display when it is called, but that doesn't bother me.

Here's the code: http://www.mediafire.com/file/2bs5r8u5rkzpu8g/6w_3D_7S_display.rar

What you have is a Charlie-Plexed display like the one in the picture below.  You need one more wire than this example because your display also includes the decimal point.  If you go through the electrical paths where for each pair one line is driven high, the other is driven low and all other lines are set to input, only one LED at a time will be forward biased.


NodeMCU powered with battery and use WiFi I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.

I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.

When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!

Any idea what can be happening?

It seem to be a problem with onboard regulator such as AMS1117.
ESP are really sensitive to power instability.
For every of my project i need to put capacitor on alimentation to prevent bugs.
I think you dont have enougth voltage to work properly with your regulated input.
To correct this issue you should put two battery to get 7.5 volt on the regulated input.
Another solution is using 3.3v input to pass trought the regulator.


Arduino Nano Fried on Music Reactive Led Strip I'm doing a project that involves an Arduino Nano, a sound detection microphone module and a RGB Led strip (individually adressable leds). I also bought an accumulator so I can connect everything straight to the outlet.

The problem is that on 12V this accumulator cannot power the led strip at all and when I connected it to the laptop the Nano micro USB fried after I did about 4 tests.

My question is why can't the accumulator power everything and why the Nano got fried from the laptop which should have even less power? Would an Arduino Mega solve the problem or is it something about the wiring? (the wiring was checked by someone with experience)

I assume you are powering the Nano through VIN or USB, and you are then powering the LED strip from the Nano's 5V pin.

From the 12V battery the current flows through an LM1117 linear voltage regulator. Draw too much current (>800mA) and it will overheat and either shut down (if it's a good one) or melt (if it's an inferior Chinese clone).
From USB the current flows through an SS1P3L diode with a maximum rating of 1.5A. If you draw more than that you will blow the diode and the board will appear dead.

So basically you're drawing too much current.

The proper way of powering a setup like this is:

USB connection to power the Arduino only
12V into a 5V switching ("buck") regulator rated for at least the maximum current the LED strip needs
5V switching regulator into the LED strip directly
Connect the ground of the 5V to the ground of the Arduino

or

12V into a 5V switching ("buck") regulator rated for at least the maximum current the LED strip needs
5V switching regulator into the LED strip directly
5V switching regulator also to the 5V (and ground) pin of the Arduino to power the Arduino

or

As above but with a 5V power supply instead of the 12V and switching regulator

Note that it is important that your supply can provide you with at least as much current as the peak current your system will need.  If that is a problem then you can split the LED strip into chunks and power each chunk separately from a lower current supply.


Setting pinMode(pin,input/output) as per user requirement I am working on arduino IDE and esp8266 nodemcu.
As i am going through the IDE I saw that there is a structure of void loop() and void setup() and all examples in the internet included defining the pinModes within the void setup() block.
I want to make a program where through mqtt or http the user will give input as to what type of device he/she wants to attach to the esp8266, so based on that i will have to set, INPUT/OUTPUT state on the following pins.

Now my initial idea was :

void setup()
{
    connectwifi();
}

void loop()
{
   call_some_function();
}

where call_some_function() will recieve the requirements from user over http. For example he wants a light on pin3, so pinMode(pin3,OUTPUT);

now what I wanted is that,
call the method - call_some_function() whenever the user needs to add an extra device to it, which means initally when we wanted to add 4 lights to esp8266, we will write

pinMode(pin1,OUTPUT);
pinMode(pin2,OUTPUT);
pinMode(pin3,OUTPUT);
pinMode(pin4,OUTPUT);

But now when I have a user defined input, my code will become something like this,

call_some_function()
{
     pin=(user gave me the pin no);
     state=(based on the device the server will send the state i.e IN/OUT);
     pinMode(pin,state);
}

Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate?
Also is this doable, like can i write like this?
I will be calling this function from void loop() instead if void setup(), since I continuously listen for user input,
Cause I cannot find any other way of making user specific input

Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate? Also is this doable, like can i write like this?

you can call pinMode anytime

And to add something more to pinMode. It is not just some preparation of the pin. It changes things for the connected circuit. Setting to INPUT lets the attached circuit rule. If there is a pull-up circuit the state will be HIGH, if pull-down LOW. INPUT_PULLUP holds the state HIGH but lets the attached circuit to pull it down. pinMode OUTPUT sets the pin LOW.

In two cases for now I use setting a pin to OUTPUT only for the time I want to control the attached circuit and the I set it back to INPUT. In first case I reset an esp8266 with EN pin connected by setting the pin LOW, then I let the external pull-up hold the EN pin HIGH. Second case is amplifier module for the tone() function. I set the pin to INPUT after tone() otherwise it catches noise.


Ethernet socket impedes adding shields I just bought a KEYESTUDIO W5500 Ethernet Arduino without realizing that the Ethernet socket on the board impedes adding any additional shields to the device because:

Horizontally the socket runs right up next to the shield connector sockets
Vertically the socket is a good 1/4 inch higher that the shield connector
sockets

Is there a good solution for extending the shield connector sockets vertically so that they clear this Ethernet socket?

Plug some of these into the Arduino headers to add extra space.

They come in different lengths and can be cut to the required number of pins.

They also come in different pin lengths.

Google long tailed pin headers.


Servo motor swinging back to 0° I just got my arduino and servo. But my servo may be acting strangely.

Whenever I tell the servo to go somewhere it keeps going to 0 than to that position and stops after 10-15 seconds or more.

This is the code used in this video

#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);
      myservo.write(50);
    }

    void loop()
    {
    }

https://www.youtube.com/watch?v=rsikknT7z6g

It is connected like this:

Ground from Arduino to breadboard row 3

Ground from external power supply to breadboard row 3

Ground from SERVO to breadboard row 3

Power supply positive to servo VCC

Servo signal to pin 11

Try with something like:

#include <Servo.h>

    Servo myservo;

    void setup()
    {
      myservo.attach(11);

    }

    void loop()
    {
        delay(2000);
        myservo.write(50);
        while(1);
    }

and let us know.
But more important: disconnect the servo +5V wire from Arduino and use another power supplier!!!


Lily Pad mp3, nested loops with timing and play randomly choosen mp3, coding problem The best way to explain my problem is in form of code...

    const int ringerPin = A0;
    const int offhook = A4;
    const int onhook = A5;

    void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0));

  }

  int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH)

void loop(){
delay(randCall);

      //i dont know how to let this loop below here run for 30 seconds.
 void loop()
    {
      //turn audio off - i dont know how to.
    for(int x = 0; x < 15; x++){
      digitalWrite(ringerPin, HIGH);
      delay(50);
      digitalWrite(ringerPin, LOW);
      delay(80);
    }
    delay(2500);
    }
  else
    //play one randomly choosen audiofile out of 10 - i dont know how to
}
}

Maybe you can give me some suggestions to my coding problems.?
I wrote them inside the code descriptions.

Halo, thank you for ansering anything.. I got the loop loop loop thing now runin..

So its about playing an Audiofile if hookon == LOW ........ check it out :-)

The code now looks like this.

const int ringerPin = A0;
const int offhook = A4;
const int onhook = A5;
double beginRing = -40000;

void setup(){
    pinMode(ringerPin, OUTPUT);
    pinMode(offhook, INPUT);
    pinMode(onhook, INPUT);
    randomSeed(analogRead(0)); // this starts Arduino's random number generator
}

int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
  if (digitalRead(hookon) == HIGH){
    delay (randCall);
    beginRing = Time.elapsedTime;
    while(Time.elapsedTime - beginRing <= 30000 && digitalRead(hookon) == HIGH){
      //turn any audio off???
      for(int x = 0; x < 15; x++){
        digitalWrite(ringerPin, HIGH);   // turn the solenoid on (HIGH is the voltage level)
        delay(50);                           // wait for 50 msec
        digitalWrite(ringerPin, LOW);    // turn the solenoid off by making the voltage LOW
        delay(80);                          // wait for 50 msec
      }
      delay(2500);
    }
  }
  if(Time.elapsedTime - beginRing <= 30000){
    //play one randomly choosen audiofile out of 10
  }
}

So, now its about to stop any sound if the hookon is HIGH and to play the randomly choosen file 1 out of 10 if the hookon is LOW (its in the code as description...there i need the right comands)


How can I speed up reading of an SD card? I am working on a project using an Arduino as a web server.

Code:

webFile = SD.open("index.htm");
if (webFile) {
  while(webFile.available()) {
    client.write(webFile.read());
  }
webFile.close();

This sends data line by line, leading to a long time to load the webpage. Is there a faster way to load this page?

Well I have two ideas on the SD card side, though neither really seem great to me they could still help you. I read on the Arduino forum that the SD card R/W speeds generally come out to 600kB/s, I'm not really sure why, the Arduino SPI can go up to 8 MB/s and I didn't think there would be that much protocol/data-handling in SD.

Sector R/W - As Chris Stratton said, this is an obvious method, it's probably much faster to do sector reads. You may have to greatly change your code to implement it, but I imagine you'd see performance increase in the end. Apparently there's an unofficial library for it, though it seems to impart some potentially serious limitations.
RAM - This is the second thing that came to mind when thinking about the problem is that you could use external RAM, when not handling network transfers (Idling, should be most of the time) the Arduino transfers data to external SRAM which you add. SPI RAM is most likely the easiest to implement, but not likely to be any faster than an SD card. Parallel RAM is going to be difficult to implement, you'll likely need to write your own class/library, but it could be much faster than SPI RAM or an SD card.

I'm not actually sure if either of these would be any faster, it's all just theory and I hope others will share their thoughts. If you have trouble finding the download link for the SD Card library, it's right here. In that ZIP folder there's a file called SDCARD, just move that folder into your Arduino libraries folder on your computer.


Help understanding SoftwareSerial recv() and PCINT In the SoftwareSerial library, I see the beginning of recv() as follows

void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {

This comment seems to be testing for if the pin change was from low to high, or high to low.  If you are using inverse logic - where the line is held high, and start bits are low - then a call to rx_pin_read() should return 0.

This doesn't seem correct.  In inverse logic the line is held high and a drop indicates a start bit.

Is the SoftwareSerial library ignoring the start bit and relying on some kind of return to zero break between the start bit and any subsequent bits?

It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

This doesn't seem correct. In inverse logic the line is held high and a drop indicates a start bit.

No, in inverse logic (for a UART) the line is held LOW and a rise indicates a start bit. The diagrams you show in your question show that UART communication normally is HIGH with LOW for a start bit.

  It seems like it can't handle start bits followed by high bits since there would be no change in the pin state.

The PCINT is only used to identify the falling (or rising in the case of inverse logic) edge of the start bit. From then on it samples at pre-defined periods to read each bit. Accurate timing is needed for that, so assembly code is used to give precise delays (see tunedDelay()). Once the whole 10-bit packet has been received the interrupt handler finishes and control is returned to the main thread again. The PCINT is then free to look for the next start bit.


Changing PWM on Arduino Mega, pins 9 & 10 to 20 to 25 KHz I'm trying to run a Nema 17 motor with a l298N motor Driver for a school project. The issue is that I am running the motor with PWM to avoid overheating of the driver, however the resulting noise at the default frequency is extremely aggravating.

How can I change the frequency for pins 9 & 10 to 20-25 KHz? Any tips tricks and code examples would be highly appreciated (emphasis on code examples).

Fortunately, the timer for PWM on both pins 9 and 10 on the Arduino Mega (but not necessarily other boards) is timer 2, so changing the PWM frequency of one will change the PWM frequency of the other.

You should also check that changing the the timer frequency does not effect any other libraries (eg Servo, from memory typically uses timer 2).

The frequency for the timer is set by the TCCR2B register (bits CS22, CS21 and CS20) see p 185 of the datasheet for the Mega2560 IC http://ww1.microchip.com/downloads/en/devicedoc/atmel-2549-8-bit-avr-microcontroller-atmega640-1280-1281-2560-2561_datasheet.pdf

As far as code goes, try the following (just tested with a small speaker, appears to change to pitch as expected, but I don't have a motor to try it on:

Each line sets the frequency for timer2 (PWM 9 and 10), should be ok to do during setup, and settings will remain. Note that the first line is equivalent to normal default values:

  TCCR2B=(TCCR2B&248)|4;    //prescaler=64, f=977Hz

  TCCR2B=(TCCR2B&248)|3;    //prescaler=32, 1953Hz

  TCCR2B=(TCCR2B&248)|2;    //prescaler=8, 7812Hz

  TCCR2B=(TCCR2B&248)|1;    //prescaler=1 62500Hz

Also check that your motor driver can handle the frequency.


How do I stop 5v on the I2C port of a pro mini so I can use 3.3v devices? The theory is that you can use 3.3v I2C devices from a 5v device as long as the pull ups are only to the 3.3v. I have a 5v pro mini connected to a bmp180 board which has a 3.3v regulator but no level shifters. It is working and giving me data but I am hoping I can get better quality measurements. One observation is the power rail on the BMP board after the 3.3v regulator is being pulled towards 5v. On the scope this looks to happen between i2c messages. I am using the "Adafruit-BMP085-Library" which is in turn using "Wire". In the wire library there is a comment that says that the writedigital() of 1 to the port is setting the pull ups.

Does anyone have any general advice on this issue?

What does the comment about setting the pull-ups mean? How is that function setting the pull ups?

When does the I2C switch back to being an GPIO? Are the lines being pulled high between messages because it is reverting to an GPIO?

Whoever decided it would be a good idea to default to using the Arduino internal pull-up resistors on I2C needs taking out back and giving a good kicking. It is so wrong on so many levels.

Yes, if you disable the internal pull-up resistors you can safely use 3.3v devices. The simplest way to do this is to turn them off again as soon as you have done Wire.begin(); by writing 0 to the pins with digitalWrite().


Newbie Arduino DC motor problem So I am new to Arduino and new to electronics in general. I've looked up a few tutorials and they all have a simple early tutorial that turns on a DC motor and turns it off again. Something like this:

The transistor I am using is a 2N2222 and the motor is a little 3V DC toy motor.

The problem is that the when I use this circuit, the motor barely turns (I need to give it a little help to get it it moving). I know my code is right (motor is on for 5 seconds, off for 1). i can tell this is working but clearly something is not right.

I am powering the Arduino off the USB port.

As a test, I swapped out the 2.2K Ohm resistor for a 560 Ohm resistor and the motor seems to run fine. However, it creeps during the "off" time (the motor is not under any load). Also, the transistor gets very hot after about a minute of running this loop.

So my questions are:

1) Why does the motor not work when I use the 2.2K Ohm resistor when I see that 2.2K Ohm resistor in different circuit diagrams that demonstrate this type of circuit?

2) Why does changing to the 560 Ohm have the effect that it does

3) Why does the motor creep during the off cycle when using the 560 Ohm?

4) Why does the transistor get so hot using the 560 Ohm resistor?

5) Finally, sometimes as a test, to simple try to turn turn the motor on, I will just reroute to pin 9 wire directly to the Arduino 5V on my breadboard (bypassing Arduino control altogether). Is there any reason this is a bad idea?

I am anticipating questions about current draw but my multimeter maxes out at 200mA; I am getting a new one that goes to 10A and will help me see how much I am drawing.

Thanks in advance of any help. I have tried to be clear and concise so hopefully this does not elicit any snark. If there are any resources to point me to, I would be happy to hear them.

Thank you!

Jim

I see a couple of issues here, which are related to your questions. I will use numbers here, but these do not necessarily correspond to the numbers you have used when asking.

The first thing you need to do when controlling a motor is to know it maximum stall current. The stall current is the current that will circulate through the motor (and through the transistor) when you apply an external force to stop the motor's shaft. But it's also the same current needed for the motor to start when it's completely stopped. So, for dimentioning a transistor, you typically will select one that has, as a rule of thumb, a collector current two times bigger than the motor's stall current.
The 2N2222 has a maximum Ic of 800 mA (best case, since there are 600 mA versions as far as I know). Although you are not specifying much about your particular motor, a typical 3V DC motor may easily be asking for 500+ mA. Some small motors (specially bad quality ones) may have stall currents bigger than 1 A.
If your motor is asking for, let's say 300 mA when continuously running, then, you are near enough of the maximum current of the 2N2222.
But there is something more important here: dropout voltage in the transistor. The 2N2222 is a bipolar one, so it will have a Vce superior to 1V (probably around 2V), which means that you are dissipating a non trivial amount of power in the transistor. That power is not useful for your motor, nor for your transistor. Here, if the motor has a 3V nominal voltage, the 2V dropout in the transistor is even desirable, but I don't see your calculations about the real dropout in your description. So I assume that you are just counting that there will be an approximate 2V dropout. That means that, if your motor is taking 0.5A to work, you are dissipating 2V x 0.5A = 1W (Watt) in the transistor. But the poor 2N2222 is a 0.5W transistor! But even if your motor is using much less current, let's say 0.25 A, you are sill using it at its limits. That will explain why it's getting hot.
So, my advice is to go for a bigger transistor, if you want to count on its dropout to do not apply a voltage bigger than 3V to the motor (which can really reduce it lifespan a lot), AND do some calculations to be sure that at the currents you are using, you will have the Vce that you want.
Another option, probably better, is to replace that bipolar old transistor by a MOSFET, but you will need to provide the apropiate voltage for supplying the motor, since if not you will get nearly all the 5V to the motor (due to the very low Ron on Mosfets, and thus very low dropout voltage), and that will be very bad.
Also, please note that the 500mA of the USB port are probably not enough for your setup. But even if you are powering your Arduino from an external power supply through its power jack, you will find a good idea to use common grounds but different Vcc sources for logic and for the motor.
Finally a short advice: be sure that the diode protecting the back EMF (the diode connected with its cathode to Vcc in your circuit) is a fast diode. A slow, 1Nxxxx diode is usually to slow for effectively protecting your transistor. If you are using for example an 1N4007, you can switch to a UF4007 (Ultra Fast).
Regarding your 560R vs 2K2 resistor, this exceeds the answer a bit, so my advice is to read something about base resistors in transistors, like this. Also something about open collector configurations may help.
Finally, the practice of connecting the base resistor to Vcc in this kind of circuit to test the transistor should be fine. But DO NOT CONNECT the transistor's base directly, use always the resistor.


USing arrays, binary data and bitRead This is my first manually typed code. I'm sure there may be some glaring "schoolboy errors" in it, so wondered if people could give it the 'once over' In particular, I have never used C++ arrays, storing binary data within, and then trying to read them bit by bit. In perl, much easier; you would simply use a multi-dimensional something like this:

@code1=('10101010', '01010101');
$bit=$code1[0][0] (..through to..) code1[0][7]
$bit=$code1[1][0] ... code1[1][7]

So this is my Arduino code. Welcome to suggestions.

int pinArray[]={2,3,4,5,6,7,8,9};
int code1[]={B10101010, B01010101,B10101010, B01010101,B10101010, B01010101};
int count=0;
int split=0;    // Counter for the bit loop
int led;    // Store bit data
byte x;     // Used to store the binary data in code1

void setup(){
    for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT); // Sets pinMode as output on pinArray pins
    ]
}

void loop(){
    for (count=0; count<6; count++){
    x=code1[count];
    ledDisplay(x);
    }
}

void ledDisplay(){
    for (split=7; split>=0; split--){
    led=bitRead(x,split);
        if (led == 1){
        digitalWrite(split+2,HIGH);
        }
        else{
        digitalWrite(split+2,LOW);
        }
    }
}

Have just modified split as realised bit7 is the leftmost digit. In split, I am adding 2 to the value.  Does this need to be enclosed in brackets,ie (split+2) ?

There are only two errors I can spot in your program:

A block of code should be delimited by curly braces:

for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT);
}  // ← ‘}’ instead of ‘]’

If a function expects to be passed arguments, these should be
declared as parameters in the function prototype:

void ledDisplay(byte x){  // ← mind the “byte x”
    // ...
}

Other than that, here a few suggestions to make the code look nicer, and
hopefully more maintainable:

indent consistently
use const to qualify constants
use named constants instead of magic numbers
keep variables local if possible
note that an int that is either 0 or 1 is equivalent to a boolean
use pinArray[] for accessing the pins

Applying those suggestions, I get the following:

const int PIN_COUNT = 8;
const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int CODE_COUNT = 6;
const int code1[CODE_COUNT] = {
    B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
};

void setup() {
    for (int count = 0; count < PIN_COUNT; count++) {
        pinMode(pinArray[count], OUTPUT);
    }
}

void loop() {
    for (int count = 0; count < CODE_COUNT; count++) {
        ledDisplay(code1[count]);
    }
}

void ledDisplay(byte x) {
    for (int split = 7; split >= 0; split--) {
        if (bitRead(x, split)) {
            digitalWrite(pinArray[split], HIGH);
        } else {
            digitalWrite(pinArray[split], LOW);
        }
    }
}


Adding POE to Ethernet Board If I was to use the Arduino A000024, would I be able to add a POE MODULE to the board to get a Ethernet board with POE to run my arduino project?

If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though.  It looks ok, but it depends on the dimensions of the board whether it fits the existing pinout.


Arduino receives no external UART comms after Serial.begin(9600) I face the following issue. I connected my RasPi (3b) with an Arduino Uno via RX/TX and a logic level converter. UART comms from the RasPi to the Arduino and vice-versa work fine on minicom and serial monitor. It also works fine from my qt program to the serial monitor, but as soon as I start a Serial.begin(9600,8N1) or Serial.begin(9600) function on the Arduino there seems to be no communication anymore at all between the two. Neither the expected result (toggle an LED, works from serial monitor), nor any blinking of the tx/ex LEDs onboard anymore. Issue occurs no matter if I provide power to the Arduino via USB or the 9v powercable. Any suggestions?

Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks


Is it possible to make normal pins act like ground pins? So what exactly I am trying to do is control a motor and be able to turn it both ways without any extra parts.

So if the hmp was on (the plus pole) and the hmm (the minus pole) acted like ground the motor should start turning right.

But if the hmp acted in this case as ground and the hmm like the plus pole it should start turning the other way.

I know that it's probably not going to work. I'm just experimenting.

int Hmp=12; // the plus pole
int Hmm=11; // the minus pole

while (HR=0 || Sr > Sl+300) {
  pinMode(Hmp, OUTPUT);
  digitalWrite(Hmp, HIGH);
  pinMode(Hmm, INPUT);
}

while (HR=1 || Sl > Sr+300) {
  pinMode(Hmp, INPUT);
  pinMode(Hmm, OUTPUT);
  digitalWrite(Hmm, HIGH);
}

No, it's not going to work - even worse, you risk frying your Arduino -, for the following reasons:

The Arduino data pins can't source (neither sink) enough current for that to work.
The inductive kickback of the motor could fry Arduino pins.

The right way to do what you want to do is using an H-bridge controlled by your Arduino data pins. There are lots of Motor Driver PCB modules for Arduino (most of them based on the inefficient L298 driver IC, which you should ignore and look instead on those based on the TB6612FNG driver IC or similar, because it would be a far better solution) that implement this function.


Where can I see the output of printf? I would like to know where I can see the output when I use the command printf. I am programming using the Arduino interface.

Update

I'll add a few lines of code for better understanding:

#include <stdio.h>

int main(void)
{
    printf("Hello World");

    return 0;
}

If you're working with the standard Arduino environment and libraries then printf() won't display anything anywhere. The reason is that microcontrollers could be connected to any number of different output/communication devices in any way. stdio would have no idea how or where to send the data.

The most common approach to outputting text from an Arduino (particularly during development) is to send it to the primary UART port using Serial.begin() and Serial.print(). If the Arduino is connected to your computer via USB then the Arduino IDE's serial monitor should display the result.

If you really want to use printf() though then it is possible to make it work (or implement similar functionality). A full explanation is on this page:

http://playground.arduino.cc/Main/Printf


What features of the Arduino framework will fail if I use my own infinite loop in favor of the standard loop()? I have a strong urge to replace the framework-provided loop() function with my own like so:

__attribute__((always_inline)) inline void fastLoop()
{
}

void setup()
{
   // Performing setup here...
   Serial.begin(115200);

   // Now looping
   for(;;)
      fastLoop();
}

This way, my loop is inlined and I'm saving quite a few cycles - avoiding not only Arduino housekeeping costs, but also the function call cost which even for a void function has to be at least 6 cycles on AVR (>=2 for RCALL and 4 for RET).

This is the framework code for calling loop() from main():

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

My question is: what does this serialEvent stuff do? What features of the framework will stop working properly with my own loop?

Assuming my loop has observable side effects as required by the C++ standard, of course (otherwise it can be optimized out).

It depends on which "Arduino" you are running it on.

On an Arduino Uno, for example, then the only thing that won't work is the SerialEvent system. Everything else that matters is interrupts.

Here is main() on the Arduino AVR core:

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}

As you can see, loop() is run just the same way as your fastLoop(), just not inline, and adding in a call to serialEventRun() if it has been defined.

If no serial event handlers have been defined, then it won't do anything there anyway.

To save clock cycles you would get more benefit (as long as you don't want to use millis(), delay(), serial communication, etc) from disabling interrupts.

However, on an ESP32 or ESP8266 you will find that your watchdog times out and resets the unit. This is because it relies on code being run regularly to manage the WiFi connection that keeps "kicking the dog". Without that being run (which can be called by calling the yield() function) the watchdog times out.


Arduino remote-controlled car stops after a few seconds I am making a remotely controlled car for a project at Uni. The car is made from an Arduino Uno, a 2 motor driver and a Bluetooth transceiver. I have written some code for it, but it randomly stops after 2 or 3 loops.

Here is my code:

#include "SoftwareSerial.h"

typedef unsigned char u8;

typedef struct {
  u8 right;
  u8 left;
} speed;

SoftwareSerial bluetooth(4, 2);

const u8 RIGHT_MOTOR_PIN1 = 3;
const u8 RIGHT_MOTOR_PIN2 = 5;
const u8 LEFT_MOTOR_PIN1 = 6;
const u8 LEFT_MOTOR_PIN2 = 9;

const u8 MAX_SPEED = 0xFFU;
const u8 HALF_SPEED = MAX_SPEED / 2;
const u8 NO_SPEED = 0x0U;

static u8 command = 0U;
static speed potentialSpeed;
static speed actualSpeed;

void setup() {
  bluetooth.begin(115200);
  while (0U != bluetooth.available()) bluetooth.read();
  potentialSpeed.right = MAX_SPEED;
  potentialSpeed.left = MAX_SPEED;
  actualSpeed.right = NO_SPEED;
  actualSpeed.left = NO_SPEED;
}

void loop() {
  readCommand();
  {
    if (clockwise(command)) {
      if (0U == (command & 0xFEU)) {
        actualSpeed.right = - MAX_SPEED;
        actualSpeed.left = + MAX_SPEED;
      }
    } else if (counterclockwise(command)) {
      if (0U == (command & 0xFDU)) {
        actualSpeed.right = + MAX_SPEED;
        actualSpeed.left = - MAX_SPEED;
      }
    } else {
      if (right(command)) {
        potentialSpeed.right = HALF_SPEED;
      }
      if (left(command)) {
        potentialSpeed.left = HALF_SPEED;
      }
      if (forward(command)) {
        if (!backward(command)) {
          actualSpeed.right = + potentialSpeed.right;
          actualSpeed.left = + potentialSpeed.left;
        }
      } else if (backward(command)) {
        actualSpeed.right = - potentialSpeed.right;
        actualSpeed.left = - potentialSpeed.left;
      }
    }
    if (0U == command) {
      potentialSpeed.right = MAX_SPEED;
      potentialSpeed.left = MAX_SPEED;
      actualSpeed.right = NO_SPEED;
      actualSpeed.left = NO_SPEED;
    }
  }
  runAt(actualSpeed);
  delay(95);
}

void readCommand(void) {
  command = 0U;
  if (1U == bluetooth.available())
    command = bluetooth.read();
}

inline boolean clockwise(u8 command) {
  return (boolean)((command >> 0U) & 1U);
}
inline boolean counterclockwise(u8 command) {
  return (boolean)((command >> 1U) & 1U);
}
inline boolean right(u8 command) {
  return (boolean)((command >> 2U) & 1U);
}
inline boolean left(u8 command) {
  return (boolean)((command >> 3U) & 1U);
}
inline boolean forward(u8 command) {
  return (boolean)((command >> 4U) & 1U);
}
inline boolean backward(u8 command) {
  return (boolean)((command >> 5U) & 1U);
}

void runAt(speed Speed) {
  if (Speed.right > 0U) {
    analogWrite(RIGHT_MOTOR_PIN1, 0U);
    analogWrite(RIGHT_MOTOR_PIN2, Speed.right);
  } else {
    analogWrite(RIGHT_MOTOR_PIN1, (-(Speed.right)));
    analogWrite(RIGHT_MOTOR_PIN2, 0U);
  }
  if (Speed.left > 0U) {
    analogWrite(LEFT_MOTOR_PIN1, 0U);
    analogWrite(LEFT_MOTOR_PIN2, Speed.left);
  }
  else {
    analogWrite(LEFT_MOTOR_PIN1, (-(Speed.left)));
    analogWrite(LEFT_MOTOR_PIN2, 0U);
  }
}

Could you please help me find the cause?
Also, I am unable to make it go backwards. Can that be related?

The problem was that the bluetooth module would receive bytes faster than the SoftwareSerial was able to read, so bluetooth.available() would return more than 1U after a couple of loops. This was fixed by changing the following:

void readCommand(void) {
  command = 0U;
  if (bluetooth.available()) {
    while(bluetooth.available() > 1U)
      bluetooth.read();
    command = bluetooth.read();
  }
}

The 'make-it-run-backwards' problem was also solved, but was unrelated.


Error "cstddef: No such file or directory" on use AzureIoTHub Good Morning
I'm trying to integrate with Azure IoT with Arduino Mega 2560.
I imported the AzureIoTHub and AzureIoTUtility lib.
I just created this part of the code
 #include <AzureIoTHub.h>

void setup() {
  // put your setup code here, to run once:

}

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

}

however, when I compile, I get the following error message.

In file included from
C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/platform.h:7:0,
from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/AzureIoTUtility.h:7,
from C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTHub\src/AzureIoTHub.h:7,
from D:\Documents\Dev\Pocos\Arduino\ArduinoSolution\ArduinoSolution.ino\WiFiPoco\RoboCore\azureHub\azureHub.ino:3:
C:\Users\MercurioNote\Documents\Arduino\libraries\AzureIoTUtility\src/azure_c_shared_utility/strings.h:8:10:
fatal error: cstddef: No such file or directory  #include

I imported ArduinoStl and the problem continued.
what am i doing wrong in this case?
thanks

Azure IoT is only supported on ESP8266 and ESP32. As stated in the README for the library:

Currently supported hardware:

ESP8266 based boards with esp8266/arduino

SparkFun Thing

Adafruit Feather Huzzah

ESP32 based boards with espressif/arduino-esp32

Adafruit HUZZAH32