ESP-01 Deep Sleep not waking up properly I have a temperature/humidity project using an ESP-01 and DHT11.  I want to be able to put t into deep sleep to preserve battery life.  I have soldered a wire from GPIO16 to RST.

#include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
#include <ESP8266WiFi.h>
#include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
#include "DHT.h"

//USER CONFIGURED SECTION START//
#define DHTPIN 2     // what digital pin we're connected to

const char* ssid = "mySSID";
const char* password = "password";
const char* mqtt_server = "mqttserverip";
const int mqtt_port = 1883;
const char *mqtt_user = "usser";
const char *mqtt_pass = "pass";
const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
//USER CONFIGURED SECTION END//

// Uncomment whatever type you're using!
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);
SimpleTimer timer;

bool boot = true;
int status = WL_IDLE_STATUS;

//Functions
void setup_wifi()
{
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void getTemperature()
{
  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print(f);
  Serial.print(" *F\t");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
  Serial.print(hif);
  Serial.println(" *F");

  char temperature[50];
  char humidity[50];

   // Update temperature and humidity
  String temp_str = String(f);
  temp_str.toCharArray(temperature, temp_str.length() + 1);
  client.publish("dryer/temperature", temperature);

  String hum_str = String(h);
  hum_str.toCharArray(humidity, hum_str.length() + 1);
  client.publish("dryer/humidity", humidity);

}

void setup() {
  Serial.begin(38400);
  delay(2000);
  Serial.println("Booting");

  dht.begin();
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  getTemperature();

  Serial.println("Going to sleep");
  ESP.deepSleep(10000000,RF_DEFAULT);
}

void loop() {

}

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up.  Serial output:

Booting

Connecting to SSID
  ......
WiFi connected
IP address:
mqttip
Humidity: 51.00 %   Temperature: 20.00 *C 68.00 *F  Heat index: 19.39 *C 66.90 *F
Going to sleep

ets Jan  8 2013,rst cause:5, boot mode:(3,7)

ets_main.c

In the question the OP said:

  I have soldered a wire from GPIO16 to RST.

But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:

The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board.  You need to add this connection which can be difficult for most people.  You can see the modification in this picture:

...which comes from this instructables posting.

If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.


Powering Arduino through 12V USB communication unstable When powering Arduino through Japan Jack at 12V USB communication becomes unstable and frequently interrupts/disconnects. Using Arduino Uno R3 and Linux on the connected computer.

Does anyone have any insight why this might be happening?

12V is a little on the high end for what the arduino can handle by itself. If I were you I would use a DC step down Buck Converter module to hold the voltage at somewhere around 6v.

http://www.ebay.com/itm/like/400673913185?lpid=82&chn=ps

They're super cheap and pretty easy to use. Simply solder the + and - leads from your 12v power supply to the +in and -in on the buck converter. Then the + out and -out to the + and - for your arduino. Turn the potentiometer until you get somewhere around 6V.

Edit:

Actually I was just reading online, and some people have trouble communicating with the arduino through USB while an external power source is connected. Internet says this problem is related to sharing voltages.

https://forum.arduino.cc/index.php?topic=194598.0


Program Arduino then Remove Atmega? Can I program an Arduino and then remove the micro-controller from it and use it on a breadboard without reprogramming the micro-controller again?

My steps would be:

create my Arduino code.
I upload the compiled code to the board.
I remove the Ic and use it alone without the whole board.

Will the code be preserved on the microcontroller?

Yes. The programming of the arduino microcontroller sets the values inside the FLASH. This is non volatile memory and as such won't be erased by taking out the IC.

Please note that this is assuming a DIP package IC as these can be removed without force, heat and stress. A TQFP, and SMT packages like that, IC might get damaged by moving them in such a way. This doesn't mean it has to be erased, it is still non volatile storage, but the moving process is much more dangerous for the chip.

I would recommend connecting the whole arduino or if you really need the whole chip: designing your own board/circuit which allows you to program the chip without moving it around as this is really tedious and not worth the effort. Also moving the chip around is a ESD hazard.

Also please note that you'll need to add a clock source for the chip to work (most of the time). Or you'll need to enable an internal PLL. It will in any case require more effort on your part to make sure that the MCU can work. Therefore using the whole arduino board is preferable.


Microphone input into Arduino uno R3 I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .

Is it a correct value?(circuit taken from here http://wiring.org.co/learning/basics/microphone.html)

EDIT: If I put my finger on it the values go up a bit like 792 ,794,800

This schematic contains also the OpAmp stage for a microphone.
You could take it as reference against the design you are using.
The LM386 is basically a more integrated version, iirc.


Bluetooth module HC-05 not finding mobile phones, only PC I put the HC-05 in the AT mode with arduino and the comands:

AT+CMODE=1
AT+ROLE=1
AT+INQM=0,10,48
AT+CLASS=0
AT+INIT
AT+INC

It responds "OK" after all till AT+INC, and after this, shows only my notebook's adress, but it has many other mobile phones near with bluetooth on (I can find with my cell phone) and they are not found. Why? Someone help me please

Bluetooth maybe on, but some phones are "invisible" until you put them in "other Bluetooth devices can find me" -mode.

Current iPhones are visible when Bluetooth is on but, Androids for example, (at least 7.0 upwards) are visible only when you have the Bluetooth settings screen open.


I don't have "Process" header I'd like to run an application on my system after pushing a button on an Arduino shield. I've read that I need to use the runShellCommand() function, which can be accessed from a Process header. However when I add the #include <Process.h> line to my program I'm getting this error:

.build/uno/src/sketch.cpp:2:21: fatal error: Process.h: No such file or directory
 #include <Process.h>

I'm using Ubuntu 14.04 and I've installed Arduino software from repositories.

That only works on an Arduino Yún (as described in this tutorial).


Arduino I2C long string I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
while (Wire.available())
{char c = Wire.read();
cmdInStr.concat(c);
}

Slave sends

int len = cmdOutStr.length()+1;
char ascii_num[len];
for (int i=0; i<len; ++i)
{ Wire.write(ascii_num[i]);
}

You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:

Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.


Arduino server to read from multiple clients Socket programming question here.

My interface comprises of an Android device(client), A wireless module hosting an access point, and an Arduino Uno(server).

My Android client class works when 1 user connects and sends commands to my Arduino server class.

I want to make my program friendly to many users at the same time.  My server will only read in values from 1 connected client at a time.

After some research I've found that Arduino does not allow multithreading naturally, which is why i've decided to look into a number of libraries.

The Arduino library that I've decided to use for this specific issue is protothreads.  Unfortunately, i've been unable to find any examples of creating a server with Arduino to accept a client's commands.  Furthermore I'm having a lot of trouble figuring out how to make this library work in my favor.

Now for my question,

  How exactly can I allow my Arduino server to constantly listen for
  incoming messages from more than 1 client device?

Or is there something I can do on the client side that would make this communication possible?

A lot of work is handled by my Wifly Module.
I was able to telnet in and set my ipaddress/port#/etc..
Anything sent over IP goes straight through my Module and straight to my arduino.

My
Client Code:

My Server:

WiFlySerial wifi(rxPin ,txPin);

void setup() {
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  pinMode(led, OUTPUT);
}

void loop() {
  //Serial.println("I'm in the LOOP!!");
  androidLed();
  serialLed();

}

void androidLed()
{
  if(wifi.available() > 0){
    data = wifi.read();
    Serial.println(wifi.getDeviceStatus());
    Serial.println(data);
}
}

Without knowing your exact implementation details...

You should be OK as long as you don't have multiple clients connected at the same time. You may think that there are multiple clients connected to your server, but the connection is closed after the resource is obtained by the client over a protocol.*

The standard flow of a server on Arduino:

A client connects to the Arduino.
The Arduino code realizes this connection and reads the data provided by the client.
The Arduino then sends some data back to the client.
The Arduino closes the connection and waits for another client to connect.

This happens relatively fast so multiple people can connect.

If you call a function like .close(); after you send data to your client, you should be okay. If you don't, redesign your code to have this element (avoid loops and blocking functions) and make sure to have your client reconnect every time it sends a command.

I wouldn't mess with this and Protothreads because I'm not sure that the Arduino hardware is designed to be able to handle multiple connections at the same time. [Citation needed]


Arduino IDE says fcould not convert 'pinMode(buttons[((inti)], 0u)' from 'void' to 'bool'. How do I fix Alright, so this code is for a game that is a power source connected to 6 buttons at ports 1, 2, 9, 11, 12, and 13. These are consequently supposed to light up 6 LEDs, each connected to 1. If you press the buttons in the right order, all the LEDs blink at once. Does it work?

#define DEBOUNCE 10  // button debouncer, how many ms to debounce, 5+ ms is usually plenty

// here is where we define the buttons that we'll use. button "1" is the first, button "6" is the 6th, etc
byte buttons[] = {1, 2, 9, 11, 12, 13}; // the analog 0-5 pins are also known as 14-19
// This handy macro lets us determine how big the array up above is, by checking the size
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'currently pressed'
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

void setup() {
byte i;

// set up serial port
Serial.begin(9600);
Serial.print("Button checker with ");
Serial.print(NUMBUTTONS, DEC);
Serial.println(" buttons");

// pin1 LED
pinMode(1, OUTPUT);

 // Make input & enable pull-up resistors on switch pins
 for (i=0; ipinMode(buttons[i], INPUT);
 digitalWrite(buttons[i], HIGH);
  }

 // Run timer2 interrupt every 15 ms
 TCCR2A = 0;
 TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

 //Timer2 Overflow Interrupt Enable
  TIMSK2 |= 1<<TOIE2;

 }

SIGNAL(TIMER2_OVF_vect) {
check_switches();
}

void check_switches()
{
  static byte previousstate[NUMBUTTONS];
static byte currentstate[NUMBUTTONS];
 static long lasttime;
 byte index;

  if (millis() // we wrapped around, lets just try again
     lasttime = millis();
  }

  if ((lasttime + DEBOUNCE) > millis()) {
    // not enough time has passed to debounce
return;
  }
  // ok we have waited DEBOUNCE milliseconds, lets reset the timer
  lasttime = millis();

  for (index = 0; index digitalRead(buttons[index]);   // read the button

    /*
    Serial.print(index, DEC);
    Serial.print(": cstate=");
    Serial.print(currentstate[index], DEC);
    Serial.print(", pstate=");
    Serial.print(previousstate[index], DEC);
    Serial.print(", press=");
    */

    if (currentstate[index] == previousstate[index]) {
      if ((pressed[index] == LOW) && (currentstate[index] == LOW)) {
          // just pressed
          justpressed[index] = 1;
      }
      else if ((pressed[index] == HIGH) && (currentstate[index] == HIGH))        {
          // just released
          justreleased[index] = 1;
      }
      pressed[index] = !currentstate[index];  // remember, digital HIGH     means NOT pressed
    }
    //Serial.println(pressed[index], DEC);
    previousstate[index] = currentstate[index];   // keep a running tally  of the buttons
  }
}

void loop() {
  for (byte i = 0; i if (justpressed[i]) {
      justpressed[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just pressed");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (justreleased[i]) {
      justreleased[i] = 0;
      Serial.print(i, DEC);
      Serial.println(" Just released");
      // remember, check_switches() will CLEAR the 'just pressed' flag
    }
    if (pressed[i]) {
      Serial.print(i, DEC);
      Serial.println(" pressed");
      // is the button pressed down at this moment
    }
  }
}

int questionNumberArray[] = {1, 2, 9, 11, 12, 13};//the array itself
const size_t n = sizeof(questionNumberArray) / //the array used
sizeof(questionNumberArray[0]);//the base of the array

for (size_t i = 0; i < n - 1; i++) //the loop itself
{
size_t j = random(1, n - i);
int t = questionNumberArray[i]; //integer output for increase
questionNumberArray[i] = questionNumberArray[j];//the value definition
questionNumberArray[j] = t;
pinMode(questionNumberArray, INPUT);
if (digitalRead(questionNumberArray) == HIGH) {
  then(digitalRead(1, 2, 9, 11, 12, 13 == High(3))
  break;
}
}

Also, how do I make it so that people have infinite times to try

There is very little about the code you are producing at the moment that could be classified as "right".

You are like a child who has been playing with LEGO® being let loose on the workings of a nuclear reactor.  You're sticking things together without a) knowing what they do and b) knowing how they are supposed to work, and it's all going to end in tears.

I suggest that, for the time being, you forget this game project of yours and go back to the basics.  Start by learning how to make an LED light up when you press a button.  That will teach you both how to read the state of a button and how to control an LED.  Then move on to doing it with multiple LEDs and multiple buttons.

As it stands you are just going to end up getting frustrated and annoyed.  You're asking questions without either knowing just what it is you are asking or how to understand the answers when you are given them.  And that is going to end up reflecting badly on the rating of your various users (hint: if you ask reasonable questions you get reasonable answers, and that means upvotes and reputation, which then means you can ask more questions so you don't have to keep creating new users to ask more questions where you don't actually understand what you're asking).


Questions on how to connect Arduino to Matlab through the serial port I have an Arduino board with Intel Edison on it. I have tried to read data in Arduino from MatLab through the serial port. I'm sure the Arduino board is working because when I use the serial monitor from Arduino, it shows the data read from the Arduino board. My command is like this in Arduino:

   reading = Wire.read();
   Serial.println(reading)

I got errors in Matlab when I tried to work with these piece of code:

   s=serial('COM4');
   set(s,'BaudRate',9600);
   fopen(s);

MatLab complains that "Port: COM4 is not available. No ports are available.
Use INSTRFIND to determine if other instrument objects are connected to the requested device." I have tried with "instrfind()" in matlab and got this:

   Instrument Object Array

   Index:    Type:     Status:   Name:
   1         serial    closed    Serial-COM4
   2         serial    closed    Serial-COM4
   3         serial    open      Serial-COM4
   4         serial    closed    Serial-COM4
   5         serial    closed    Serial-COM4

I still can't get any clue on this. Can anybody help me?

I might try to reboot with out the Arduino plugged into the USB port, bring up the device manager and open the COM section and watch which COM becomes available when you do plug in the Arduino's USB cable. Then try connecting to that COM with matlab. Don't use anything else that may connect to that COM port.


what is arduino adc reference? I'm using arduino for the first time and don't really understand what am I suppose to plug to the ADC refernce PIN... or if I even have to use it while plugging analog sensor to the arduino,
thanks!

The AD converter in the ATMega microcontroller (as used in Arduino) converts an input voltage to a number.

This ADC happens to be 10 bit that means 2^10 states which is 1024.

The number 0 (zero) means 0 Volt input voltage.

The number 1023 means the maximum input voltage.

Since 0 is also a value the scale runs from 0 to 1023 making 1024 values.

The scale is linear so 511 means half of that maximum voltage.

What is this maximum input voltage?

That is the ADC Reference voltage. By default the power supply voltage is used so if you run your Arduino on 5 V, then 1023 = 5 V. But if you run your Arduino on 3.3 V, then 1023 = 3.3 V.

There is also in internal reference of 2.56 V (or 1.1 V depending on your Arduino), if you use that then, you guessed it, 1023 = 2.56 V (or 1.1V).

You might have a very fancy external reference voltage already available and if you want to use that, use the external setting and connect that reference voltage to the AREF pin.

If your analog sensor gives 0 to 5 V and your Arduino is also powered by 5 V then you should use the default setting so that the VCC is used as ADC reference.

If your sensor gives a voltage between 0 and 1 V then you could use the internal reference so that more of the 0 to 1023 range is usable. Giving you get better resolution.


Using INT2/3 on Arduino Micro (Atmega32u4) My project is using almost all the pins on this board and I require an interrupt pin to read radio state (rather than polling). I'm using I2C, so that leaves INT2 and INT3, which are the TX and RX pins for USB/Serial1. According to the documentation, disabling serial, using Serial.end(), should allow me to take control of those pins. However, using the pins as interrupt handlers doesn't work. Here is a sample sketch:

static int ledpin = 13;
volatile byte state = LOW;

void func()
{
  state = !state;
}

void setup() {
  Serial.end();

  pinMode(ledpin, OUTPUT);

  // INT2
  pinMode(0, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(0), func, CHANGE);

  // INT3
  pinMode(1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(1), func, CHANGE);
}

void loop() {
  digitalWrite(ledpin, state);
}

This example is mostly copy-pasted from the Arduino website. All the other interrupts work fine, only INT2 and INT3 don't.

Is there a way to use these interrupts?

You problem isn't with your pins or code, but with debouncing the signals. I've changed the "func()" method to read:

void func()
{
  static uint32_t lastChange = 0; // Note millis() don't change inside ISR, but can be read
  if (millis() - lastChange > 100)
  {
    state = !state;
  }
  lastChange = millis(); // Set new value
}

which will ignore spurious interrupts if they occur within 100ms of each other. This solves the issue that you are seeing, I've tested it on an Arduino Micro I have lying around.


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

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

RX->pin 10

TX->pin 11

GND->GND pin

VCC-> 5V VCC

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

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


Sketch does not work without delay() or other complex functions like digitalWrite() I have a simple sketch here that should just blink a led once a second or so (approximately):

boolean onOff=true;
int count=0;

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

void loop() {
    count++;
    delay(1);

    if (count == 316) {
    onOff=!onOff;
    digitalWrite(13, onOff);
    count=0;
    }
}

So, if count is 316 it changes the state of led. It works right now, but it does not without delay() function or some other complex ones like digitalWrite() being in the loop() too. If i am deleting delay(), than led is just always on. I can feel it is smth about interrupts, but i am not sure.

What am i trying to do here is to make an alternative to delay() and millis() for my other project. One of the most needed thing for me is to make ASAP (as soon as possible) "timer", so that some code could run every 2(3-4...) iterations of loop(). delay() is bad always, and millis() uses long variable (which is bad for cpu time and ram), and while having problems with ram and cpu time in my project, i want smth lighter for ASAP and other not very precise timing.  So, the questions are:

Why does my sketch works only with delay(), but does not work
without it?
Why does blinking sketches work with millis(), while they do not use any delay() just like my sketch.
Am i a bad person for trying to make smth like an ASAP timer?:)  Is saved ram and cpu time worth of it?  Any other possible problems?
Can this sketch be workable without delay() or other complex or ram and cpu costly functions?

Thank you.

So, the sketch up there works indeed, but here is the version that you can can observe with your eyes:

boolean onOff=1;
unsigned int counter=0;
unsigned long time=0;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(57600);
}

void loop() {
   if (counter==0)  time=micros();
    counter++;
    if (counter == 0) {
        onOff= !onOff;
    digitalWrite(13, onOff);
    Serial.println(micros()-time);
    }
}

With Serial i was checking delay between blinks, and it is 140164 mcs = 140 ms = 0.14s. But to be honest it feels slower, so please correct me if i can benchmark it in a better way.

As majenko answered in the comments, the blinking rate will be so fast you can not see it.
Also it is possible that without the delay the optimizer removes the whole counting. So increasing the number as proposed by majenko may not even work due to compiler optimisations.
Using a method based on counters is a very unreliable way to use timings.

Look at the blinkwithout delay example as proposed by Dirk.
It boils down to using millis() for timing. millis tells you how many millis the arduino is running.

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}


Can I emulate Arduino in a headless CI/CD setup? 6 years ago, there has been a question "How to emulate Arduino on PC".

Since then, probably many more Arduino emulators have been introduces.

With this question, I would like to narrow the search scope down to the following criteria:

Linux compatible
headless operation mode without UI/IDE possible to run in a CI/CD (continuous integration/delivery) system in collaborative environment where many code versions need to be merged and tested.

Do such setups exist already?

The problems with this kind of software is:

always behind the recent releases of cores/ hw variations.
reliable only for simple programs/tasks
Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)


Connect Arduino to Socket IO Webserver via Esp8266 As part of a project I want to receive data on my arduino uno via a sensor, which is working fine. This data should be sent to a webserver where a node js with socket io is running. Therefore i bought a esp8266 and the corresponding adapter (https://www.amazon.de/gp/product/B01LZLVEJ4/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1).

In the IDE I have the following code:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2, 3);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      Serial.println("Started");

      // set the data rate for the SoftwareSerial port
      esp8266.begin(115200);
    }

    void loop() {
      if (esp8266.available()) {
        Serial.write(esp8266.read());
      }
      if (Serial.available()) {
        esp8266.write(Serial.read());
      }

    }

I use the serial monitor to perform my AT Commands and it seems to work some times, however there seems to be a problem with the output, for example if I type the command AT+CWLAP to display the Access Points. If I do so, it outputs something like:

    +CWLAP:(3,"WLAN-32CC39",-73,"10:c6:0f:2c:32:cc",1,65,0)
    +CWLAP:(3,"F1e:,:oMc:0(x8:1LN⸮⸮⸮:b),k7:,(-,36Ao-2,
    (e0e,C".66,Cwe8:"+L,:"+27:6L W79",944,Ab,::0(ot230( -5,CTO940PBc,63+3y8:")3,dc3
    "P4-ze6P!"80,3716

I should also note, that even if I input the same, the response differs, and sometimes it is just single characters that are wrong, e.g. "wigi" instead of "wifi". I tried different baud's for the esp8266 but the current one produces the least problems. So my questions here are:

1: Is there anything I am currently doing wrong while connecting to my local wifi network?

2: If there is a connection made, is there any way to connect to a socket io server as a client? Most Tutorials I have found have the arduino as a server. However, I want to have it as a client which communicates to a server. Therefore it should both be able to send and receive messages to/from the server.

Thanks in advance!

Using the ESP8266 in general

The easiest, most flexible, and most efficient way is to program the ESP8266 directly.
If it is possible, have it replace the Arduino entirely. To do this, it is best to get an ESP8266 development board that breaks out all IO pins and has a USB interface for easy programming. Programming these development boards is just like programming an Arduino: plug in the USB connection and hit upload in the Arduino IDE. One of my favourites is the WeMos D1 mini (around $3.50 from China).
The ESP8266 is a very powerful microcontroller on its own: it has a 32-bit processor that runs 10 times faster than an Arduino Uno, it has up to 4MB of flash memory (vs 32KB on the Uno), 160KB of RAM (vs 2KB on the Uno). It has 11 digital IO pins, an analog input, support for I²C, SPI, PWM, etc., just like an Arduino. If you use AT commands, you don't use its full potential.

Your specific situation

Given that you already bought an ESP-01 + adapter that only gives you access to the UART, connecting the sensor to the ESP directly is probably not possible.
In this case, you can do one of three things:

1) Program the ESP8266 directly:
Write a program that just reads a number from the serial port, and sends it to the server over WiFi.
This is the easiest, because you can use all features of the ESP8266, and you don't have to change the program that you wrote for the Arduino (it should just measure the sensor value, and send it to the ESP8266 over the serial port, this is exactly the same as sending it to the serial monitor on your computer).

2) Don't program the ESP8266, but use an AT commands library on the Arduino. (For example WiFiEsp)
The downside is that you have to make significant changes to your Arduino sketch, and that you cannot use all of the functions and resources of the ESP.

3) Control the ESP8266 using AT commands yourself, without any libraries.
This is very cumbersome, and is a complete waste of time, IMHO.

Practical

Programming the ESP8266 directly
To program the ESP8266 directly (both with an Arduino and stand-alone), you need a USB-to-Serial converter. You can either use something like an FT232 (3.3V) or an Arduino. How to program it is covered here. If you use an Arduino as USB-to-Serial adapter, the right connections are TX-TX, RX-RX.

Using AT commands or an AT commands library
If your Arduino has a hardware UART that is not used for programming the Arduino (e.g. Arduino Mega, Arduino Leonardo, Arduino Due, ...), you can use this UART for communicating with the ESP8266. The right connections are TX-RX, RX-TX. You can use any baud rate that's supported by both devices (9600 - 921600).
If your Arduino doesn't have an extra hardware UART, you'll have to use the UART on pins 0 and 1, that's used for programming, and you'll have to disconnect the ESP8266 every time you upload new firmware to the Arduino.
Alternatively, you can use SoftwareSerial. Keep in mind that this is far from an optimal solution, as it uses a lot of resources, it is very slow, and data might get corrupted if you spend a lot of time in interrupts on the Arduino.
To use the ESP8266 with SoftwareSerial, you need to lower the baud rate to 9600 baud. To do this, first upload an empty sketch (bare minimum) to the Arduino to make sure that the hardware UART is not used. Then connect the ESP8266 to pins 0 and 1: TX-TX, RX-RX.
Open the Serial Monitor from the Arduino IDE, and select the baud rate that the ESP8266 is currently operating at. (This is probably 115200, but it could be something else.) Select "Both NL + CR" as the line ending, and send "AT" (without the quotes) to verify that it is working. If everything works, it should answer with "OK". If it doesn't, check your hardware, or try a different baud rate. Finally, send "AT+UART_DEF=9600,8,1,0,0" to set the baud rate to 9600 baud. Then change the baud rate of the serial monitor to 9600 as well. Send "AT" again to verify that it is working.
Now you can connect the ESP8266 to the SoftwareSerial pins, using a baud rate of 9600 baud.

Edit: The WebSocket protocol is not supported using AT commands, so you have no other choice but to program the ESP8266 directly.


Is there an Arduino simulator that runs on Mac OS X? I need to simulate my Arduino project with other circuit components before implementing the project. Is there a decent simulator that runs on Mac platform?

There is a decent program called Simulator for Arduino made by Virtronics. Although it is made to run only in windows, you could run it in a WINE environment. WINE allows windows programs to be ran in Mac and Linux OS.


multiple graphs on serial plotter I'm trying to  run an Arduino code that simultaneously:
1) blinks an led on-off every 3 seconds
2) gets a voltage input from an EMG sensor and positions a servo motor accordingly

While I run this program, I'd like to plot the following on the same graph
1) LED status on/off printed as 600 if on and 0 if off
2) EMG value being fed to the arduino
3) The angle the Arduino is sending to the servo motor

I wrote the following code which works to an extent but the problem I'm facing is, I only get two graphs on the plotter instead of 3, I think the EMG value and the angle have combined into a single line as seen in this picture:

However, if I remove the angle print statement, I get a proper graph for the other 2 as this:

How do I change my code so I can plot all three separately?
Thanks in advance.

#include <Servo.h>
Servo myservo;
const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 3000;
int led=0;
int servovalue=0;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(A0);
int angle = map(sensorValue, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print(sensorValue);
Serial.print(“ ”)
Serial.println(angle);
delay(15);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
      led = 600;
    } else {
      ledState = LOW;
      led = 0;
    }
    digitalWrite(ledPin, ledState);
  }
  Serial.print(" ");
    Serial.println(led);
}

The part of your code that prints data to the serial looks like this:

void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}

The bug is in the Serial.println(angle); line. The println method inserts a "newline" character at the end. Try changing it to Serial.print(angle); so there is only one "newline" character.

void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}


How to monitor 12 V LiPo charging from Arduino What's the safest way to determine a lithium-ion polymer battery's discharge and charging state using an Arduino?

I see a ton of 12 V LiPo batteries like this being sold on eBay and elsewhere.

They have a built-in charger, and I'd like to use one to power an Arduino, but the Arduino needs to know "when" the battery needs to be charged, and "when" the battery is fully charged. Unfortunately, the battery doesn't expose any pins or LEDs or other outputs that I could tap into.

I've found a few LiPo charging circuits specifically designed for the Arduino, but they all can only handle 3.7 V cells.

I'd like to avoid having to disassemble the battery or modify it to allow me to monitor its state. Is there an easier way, like connecting a battery lead to an analog pin and measuring voltage, or using a coulomb counter?

If you want to buy something off the shelf that will provide power for an Arduino, try a power bank - they have USB out, and are also charged via USB. I found that I had to put a 100 Ohm resistor to stop mine going to sleep, but it's +5V native.

A 100 ohm resistor (0.25 watt at least!) draws 50mA, so a 5200mAH powerbank like http://www.dx.com/p/universal-5200mah-external-li-ion-battery-charger-power-bank-w-led-indicator-usb-cable-pink-362725#.VQneCnWjlIc would leak it empty in 104 hours. If you use at least 50mA at all times, then this isn't needed - I think an Arduino draws 35mA already, so you should get away with a 300 Ohm resistor, drawing 16mA. Some experimentation might be needed.


Is there something like a Virtual Environment for Arduino? I'm using Arduino IDE for a variety of projects.
The libraries and boards used in different projects are different and I would like to have a customized environment for each project.
Eg: In a project involving an Arduino, I don't want all the ESP boards or Adafruit libraries that I might use on another project.
Python has something called Virtual Environments, where you can switch between environments and have a different setup of libraries and configurations for each project.
Is there something like this I can configure for Arduino?

Sorry, but in Arduino IDE no such functionality as virtual enviroment. To add your own version of libraries to each projects you may only add it (libraries) directly to a project dir.


Brushless motor "jiggles" When I run my code, the ESC makes some noises, different on the high pulse and low pulse, then it begins to jiggle for a bit when it gets to the loop. Here is the code:

#include <Servo.h>

#define MAX_SIGNAL 2000
#define MIN_SIGNAL 1000
#define MOTOR_PIN 10

Servo motor;

void setup() {
  Serial.begin(9600);
  Serial.println("Program begin...");
  Serial.println("This program will calibrate the ESC.");

  motor.attach(MOTOR_PIN);

  // Wait for input
  while (!Serial.available());
  Serial.read();

  Serial.println("Now writing maximum output.");
  motor.writeMicroseconds(MAX_SIGNAL);
  delay(2000);

  // Send min output
  Serial.println("Sending minimum output");
  motor.writeMicroseconds(MIN_SIGNAL);
  delay(2000);

}

void loop() {
  motor.writeMicroseconds(MAX_SIGNAL);
}

Your code is familiar to the process of calibrating ESC controllers and is common. As your code is correct, we have to look at the connections. How is arduino connected to the ESC controller? can you provide a diagram? Only GND and Pin 10 should be connected. Do not connect the 5V of arduino. Power up the ESC with an external source. I think ESC signal port is Hi impedance so it should be no need for any resistor. Take a look at this site: http://robots.dacloughb.com/project-2/esc-calibration-programming/

You can see in that picture ( and the picture on the link provided), only pwm pin and ground are connected to arduino. Show us your connections if things keep going wrong. Also, does your power source provides enough juice to the motor?


LCDs measuring volts arduino How do we measure 100 Volts Arduino LCD Proje

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int analogInput = 0;
float vout = 0.0;
float vin = 0.0;
float R1 = 100000.0; // 100K ohm direnç
float R2 = 10000.0; // 10K ohm direnç
int value = 0;
void setup(){
   pinMode(analogInput, INPUT);
   lcd.begin(16, 2);
   lcd.print("DC VOLTMETRE-PROJEHOCAM");
}
void loop(){
   // read the value at analog input
   value = analogRead(analogInput);
   vout = (value * 5.0) / 1024.0;
   vin = vout / (R2/(R1+R2));
   if (vin<0.09) {
   vin=0.0;
}
lcd.setCursor(0, 1);
lcd.print("VOLTAJ V= ");
lcd.print(vin);
delay(500);
}

The project that you show as your reference : link in your question,  shows this picture :

Change R1 to 200 K ohms.   The Arduino will receive 4.76 volts when the input is 100 volts.

You will also need to change your program line for float R1 = 100000.0;

CAUTION :  Beware of high voltage.  Also, the Arduino is not isolated from the 100 volts.


Boolean function call with character pointer input - dont understand how to get updated pointer value Thank you for everyone's help in trying to find a solution. This library I'm working with was prewritten and is one of the most buggy hardware libraries I've had the misfortune to use. I have now solved to problem by reusing the response parsing code from the library and rewriting my own sequence to return the number using a completely different approach. Many Thanks again!

I am currently attempting to understand how this function works and am struggling. I want to be able to access the 'number' variable in my main function but currently when I do that I get nothing (as in "") when I try to printout the variable with:

Serial.println(incomingNumber);

I am currently preassigning the number as:

char incomingNumber[14];

at the top of my project file.
With a class initial setup of:

DFRobot_SIM808 sim808(&Serial);

I'm then later calling the function like this:

if(sim808.isCallActive(incomingNumber)){Serial.println(incomingNumber);}

This seems like I'm currently making a fundamental error in understanding data types but I'm a bit lost so any help would be really appreciated.

I havent included my entire project here because its currently quite long and spread across both the main and some library files but if anyone needs more info please ask and I'll upload the extras.

The function from the library I'm working with is included below:

bool DFRobot_SIM808::isCallActive(char *number)
{
char gprsBuffer[46];  //46 is enough to see +CPAS: and CLCC:
char *p, *s;
int i = 0;

sim808_send_cmd("AT+CPAS\r\n");
/*Result code:
    0: ready
    2: unknown
    3: ringing
    4: call in progress

  AT+CPAS   --> 7 + 2 = 9 chars
            --> 2 char
  +CPAS: 3  --> 8 + 2 = 10 chars
            --> 2 char
  OK        --> 2 + 2 = 4 chars

  AT+CPAS

  +CPAS: 0

  OK
*/

sim808_clean_buffer(gprsBuffer,29);
sim808_read_buffer(gprsBuffer,27);
//HACERR cuando haga lo de esperar a OK no me har閾哸 falta esto
//We are going to flush serial data until OK is recieved
sim808_wait_for_resp("OK\r\n", CMD);
//Serial.print("Buffer isCallActive 1: ");Serial.println(gprsBuffer);
if(NULL != ( s = strstr(gprsBuffer,"+CPAS:"))) {
  s = s + 7;
  if (*s != '0') {
     //There is something "running" (but number 2 that is unknow)
     if (*s != '2') {
       //3 or 4, let's go to check for the number
       sim808_send_cmd("AT+CLCC\r\n");
       /*
       AT+CLCC --> 9

       +CLCC: 1,1,4,0,0,"656783741",161,""

       OK

       Without ringing:
       AT+CLCC
       OK
       */

       sim808_clean_buffer(gprsBuffer,46);
       sim808_read_buffer(gprsBuffer,45);
        //Serial.print("Buffer isCallActive 2: ");Serial.println(gprsBuffer);
       if(NULL != ( s = strstr(gprsBuffer,"+CLCC:"))) {
         //There is at least one CALL ACTIVE, get number
         s = strstr((char *)(s),"\"");
         s = s + 1;  //We are in the first phone number character
         p = strstr((char *)(s),"\""); //p is last character """
         if (NULL != s) {
            i = 0;
            while (s < p) {
                number[i++] = *(s++);
            }
            number[i] = '\0';
         }
         //I need to read more buffer
         //We are going to flush serial data until OK is recieved
         return sim808_wait_for_resp("OK\r\n", CMD);
       }
     }
  }
}
return false;
}

You can't use Serial.println(array);. In fact, I'm not even sure how the compiler even let you do this...

A better approach would be to use Serial.write(array, sizeof(array));

Also, in order to ensure the function is even executing that portion of the code in the first place, you should but some debugging prints in the code. Like this:

     if (NULL != s) {
        i = 0;
        while (s < p) {
            number[i++] = *(s++);
            Serial.write(number[i++]); //-------- debug
            Serial.print(' '); //-------- debug
        }
        number[i] = '\0';
        Serial.println(); //-------- debug
     }

Also, proper use of whitespace is your friend ;)


Testing network of SIM900A Do I have to connect RX and TX of SIM900A with any pins (say TX, RX of Arduino) for network purpose? Shouldn't the network status LED blink slower after connecting the power sources with SIM900A?

To answer your questions in turn:

It is not necessary to connect to the Arduino solely for the purpose of making a GSM network connection.
When the SIM900A is powered on, the Status LED will blink once every second.
When the GSM connection has been established the Status LED of the SIM900A will blink every 3 seconds.

Follow this guide, from Tutorial to interface GSM SIM900A with Arduino:

  Initial startup of SIM900

  Insert your SIM card to GSM module and lock it.
  Power up the SIM900A by connecting it to Arduino's 5V and GND pins
  Connect the Antenna
  Now wait for some time (say 1 minute) and make note of the blinking rate of ‘status LED’ or ‘network LED’ (D6).
  The GSM module will take some time to establish connection with mobile network
  Once the connection is established successfully, the status/network LED will blink continuously every 3 seconds. You may try making a call to the mobile number of the sim card inside GSM
  module. If you hear a ring back, the GSM module has successfully
  established network connection.

  Connection to Arduino

  The SIM900A has the following pins:

  3VR;
  3VT;
  5VR;
  5VT;
  VCC, and;
  GND.

  For serial communication between the Arduino and SIM900A module. you
  have to connect:

  SIM900A 5VT to Arduino D9 and;
  SIM900A 5VR to Arduino D10

  Basic Communication

  To change SMS sending mode: AT+CMGF=1

mySerial.println("AT+CMGF=1");

  To read SMS in text mode: AT+CNMI=2,2,0,0,0

mySerial.println("AT+CNMI=2,2,0,0,0");

  To make a call: ATD+60XXXXXXXXX (replace X with number you want to call, change +60 to your country code)

mySerial.println("ATD+60XXXXXXXXX;");

  To disconnect/hangup call: ATH

mySerial.println("ATH");

  To redial: ATDL

mySerial.println("ATDL");

  To receive a phone call: ATA

mySerial.println("ATA");


How much can an Uno be overclocked? When running the board at room temperature (20 C) without any extra cooling mechanisms added, how much can the Arduino Uno be overclocked?

Also, what would I need to change/update to overclock the board?

With no active cooling, most ATmega328P will run at 30MHz but you will need to up the supply voltage to ~6V. I have never done this on an Arduino board, just an ATmega328P.

I provided an external clock from a signal generator.

The only way to achieve a speed faster than 16MHz is to change the crystal/oscillator/clock input for one faster than 16MHz.

As this was just an experiment, I didn't alter f_cpu in boards.txt, so all timers etc. would be incorrect. Baud rates would also be incorrect - the only way to upload code was to change back to 16MHz.


Broken Score on Game Sketch I have modified the code for Flappy Duino to give me a score at the end of the game. Here is the code:

#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Adafruit_PCD8544.h>

Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

#include "Sprite.h"
#include "Chym.h"
#include "Bar.h"

Chym player;
Bar bar; Bar bar2;
int gameScore = 0;
int highScore = 0;
int KNOCK_PIN = 2;
int LED_PIN = 8;

boolean clicked = false;

void loop(){}

void resetGame() {
  player.respawn();
  bar.setPos(0, 20);
  bar2.setPos(50, 30);
  gameScore = 0;
}

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

  display.begin();
  display.setContrast(50);
  display.clearDisplay();
  display.display();

  digitalWrite(LED_PIN, HIGH);

  pinMode(KNOCK_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);

  resetGame();

  while(1) {
    getInput();
    player.update();
    bar.update(); bar2.update();
    drawLCD();
  }
}

void getInput() {
  int knock = digitalRead(KNOCK_PIN);
  if (knock == 0) { // push down
    clicked = true;
    gameScore = gameScore + 1;
    Serial.println(gameScore);
  }
  else {
    clicked = false;
  }
}

void drawLCD() {
  display.clearDisplay();

  if (!player.isDead()) {
    int ht1 = bar.hitTest(player.getX(), player.getY());
    int ht2 = bar2.hitTest(player.getX(), player.getY());
    int die = ht1 + ht2;
    if (die == 1) {
        // game over
        player.die();
    }

    if (clicked) {
      player.flyUp();
    }
    else {
      player.cancelJump();
    }
    player.render();

    bar.render(); bar2.render();
  }
  else {
    if (gameScore >> highScore) {
      highScore = gameScore;
    }
    display.setCursor(0, 0);
    display.setTextSize(1);
    display.print("ur Score- ");
    display.println(gameScore);
    display.print("HI Score- ");
    display.println(highScore);
    if (clicked) {
      resetGame();
    }
  }

  display.display();
}

The first time the game runs thru the gameScore is greater than highScore so gameScore and highScore print as the same. However every other time the function is called up the highScore doesn't change even when the following statement is true:

if (gameScore >> highScore) {
          highScore = gameScore;
        }

What am I doing wrong?

if (gameScore >> highScore)

You have the wrong operator there.  >> is right shift, so you are right shifting the gameScore by highScore bits, which if it's more than 16 will end up as 0.

Instead you just want > for greater than:

if (gameScore > highScore)


Adafruit Metro Mini FTDI chip overheating I have an Adafruit Metro Mini board that I am using. After soldering the board and accessories to a perfboard the FTDI chip is overheating, the COM port will not show up on the PC, and the 3V pin does not produce any power while the board is plugged in.

Is there a way to fix this? Have I nuked my board?

Is there a way to fix this?

Yes. Undo whatever short circuit you have created with your soldering.

  Have I nuked my board?

Possibly, possibly not. Most likely the short is making the regulator go into thermal shutdown and no lasting damage has been caused. But you can't be sure.


How to measure direction the car is coming to garage door? my garage door is pretty narrow, about 10 cm (4") on each side of my car's rear mirrors. So every time I drive to garage, I need to go very slowly because I am afraid I might not be lined up correctly.

I am thinking about using Arduino and some sensors to help me. Output is pretty simple, just two leds, one for each side, showing me if I should turn little right or left to have perfect lineup to center. This I can handle with no problem

What I am asking for is idea how to measure the alignment of my car. I know how to use ultrasonic sensors for measuring distance. But I am not sure they are suitable for this project, because I want preferably to put arduino and sensors in my garage, not in my car.

Any idea how to work this out ?

It is very hard to determine position accurately there is a new project on kickstarter called Pozyx, you can look at that but that's expensive, to be honest this sounds like a job for hanging tennis balls or strings or something like that. But if you have a lot of money to blow and you just want a project go for it, you may be able to do this with ultrasonic sensors but I reckon that would be painful. Anyway good luck


Why does pulse sensor shows gaps when I move it? I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:

//////////
/////////  All Serial Handling Code,
/////////  It's Changeable with the 'serialVisual' variable
/////////  Set it to 'true' or 'false' when it's declared at start of code.
/////////

void serialOutput(){   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
 } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
 }
}

//  Decides How To OutPut BPM and IBI Data
void serialOutputWhenBeatHappens(){
 if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
    //ASCII Art Madness
    Serial.print(BPM);
    Serial.println("");

 } else{
        sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
        sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
 }
}

//  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
void sendDataToSerial(char symbol, int data ){
    Serial.print(symbol);

    Serial.println(data);
  }

//  Code to Make the Serial Monitor Visualizer Work
void arduinoSerialMonitorVisual(char symbol, int data ){
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data;
  // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the
  // range value:
  switch (range) {
  case 0:
    Serial.println("");

  }
}

63

63
63
63
63
62
62
62
62
62
62
62
63
62
63
64
63
63
64
64
65
65

65
68
74
78
86
95
105
112
123
141
167
154
136
128
123
125
123
127
132
104
93
92
92
89
83
77
73
69
65
70
70
71

You can find all the code here:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using.
You can also see huge changes in the heart rate that surely don't reflect the reality.

One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits data = 0, and it will cause

Serial.println("");

in your switch-case.


Send and Read packet XBee AT mode I have a simple network created using XBee Series 2 devices.

My network is very simple, my end-device with Arduino Uno read a temperature and Lightning, display this value into LCD and send using XBee to a coordinator. It is setting for sleep and wake up using PIN hibernation.

It is setting like End-Device AT mode.

I try to send a Remote AT command with XCTU from coordinator to my end device and it parse this command and response.

What I try to do is parse received packet into my Arduino code and decide what response (for example discharge it).

It is possible to do using only one Serial? The Arduino Uno and XBee are connected with an XBee shield.

I have try using this code but the Arduino don't display the packet received from the Coordinator.

This is my code:

#include <avr/sleep.h>
#define XBEE_sleepPin 7
#include <LiquidCrystal.h>

//Sensor variable
int sensorPin = 0;
int fotoResistenzaPin = A1;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
String data = "";
String name = "Arduino1";

//Time Variable
unsigned long seconds = 1000L;
unsigned long minutes = seconds * 60;
unsigned long hours = minutes * 60;

void setup() {
  pinMode(fotoResistenzaPin, INPUT);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("Status:");
  lcd.setCursor(0, 1);
  lcd.print("Connected");
  Serial.begin(9600);
  delay(2000);
}

void xbeesleep() {
  delay (300);
  pinMode (XBEE_sleepPin, OUTPUT);   // put XBee to sleep
  digitalWrite(XBEE_sleepPin, HIGH); // Setting this pin to LOW turns off the pull up resistor, thus saving precious current
  //delay(10 * minutes);
  delay(5 * seconds);
}

void xbeewake() {
  pinMode(XBEE_sleepPin, OUTPUT);  // Set the "wake-up pin" to output
  digitalWrite(XBEE_sleepPin, LOW); // wake-up XBee
  delay(10 * seconds); //make sure that XBee is ready, time to connect to Xbee Coordinator

}

void loop() {
 //wait message
  if (Serial.available()>0) {

    //see if it is a Xbee packet
    if (Serial.read() == 0x7E) {

      for (int i = 0; i < 15; i++) {
        byte skip = Serial.read();
        Serial.println(skip);

        //check if it is a Remote AT commnad
        if (skip == 0x17) {

            //do something when i find the Remote AT command packet
          lcd.setCursor(0, 0);
          lcd.print("Remote AT command ");
        }
      }
    }
  }

  xbeewake();
  int reading = analogRead(sensorPin);
  int val = analogRead(fotoResistenzaPin);
  float voltage = reading * 5.0;
  voltage /= 1024.0;

  float temperatureC = (voltage - 0.5) * 100 ;
  data = name + ',' + temperatureC + ',' + val;
  if (Serial) {
    Serial.println(data);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp: ");
    lcd.print(temperatureC);
    lcd.print(" C");
    lcd.setCursor(0, 1);
    lcd.print("Lightning: ");
    lcd.print(val);
  }
  else {
    lcd.setCursor(0, 0);
    lcd.print("Serial Error ");
    lcd.setCursor(0, 1);
    lcd.print("Stop Trasmission");
  }

  xbeesleep();

}

I'm not sure about this, but similar to any other serial communication modules used on the Arduino, you need to setup a software serial pins which act as Tx and Rx between the Arduino and the module, XBee in this case. Look at software serial. this should solve your problem. Then you can use the "Serial" object to debug your communication between the two. I have worked with both a GSM and a Wifi module and the method was the same as I have explained above.


Using AA batteries to power Arduino and GPS unit I'm more of a software guy, so I need your help to figure out the power issue with my Arduino.

What I would like to do is using a GSM/GPS unit (Ai-Thinker A7) with Arduino Nano as a car tracking system. I have USB cables in the car, so I can plug it into my Arduino and power both while I'm driving. To power the unit while I'm not driving, I thought using rechargeable batteries would be a good idea. I'm planning to use GPS via SMS activation, so I hope fully charged batteries will be enough to power it for at least a week. But I'm confused about a couple of things.

Rechargable batteries are 1.2V. So technically I can use 5 of them and power my Arduino and the GPS unit (which requires 5V), right? However, for a similar unit at Adafruit they say that a LiPo battery is a must. Well, I think it is because GPS unit draws more power while using GPS and stuff. So, in this case are AA batteries out of the question? Will I fry anything if I build the system as follows?

If AA batteries happen to be fine, do I need another piece in my design, such as this one?

At last, I have no idea if I need any diode, capacitor, resistance or sth else for this system. I would appreciate further comments about my design.

I suggest using 6 or 8 AA's (eg 6 alkalines or 8 NiMH) and a  MP1584EN DC DC Power Stepdown Buck Converter (about a dollar on ebay, 1.5 to 3 times that on Amazon).  Note, the hole pattern does not match up with breadboard spacing:

The batteries would tie in via a couple of diodes (preferably Schottky), as shown below.  When the 12 V supply is off, the converter would be powered by 9.6 V from eight rechargeable AA's.  When the  12 V supply is on, no current is drawn from the AA's.  The converter output should be adjusted to 5V before being connected to the Nano or other devices it powers.

Using a buck regulator has two advantages vs a linear regulator: battery current is lower (allowing the battery pack to be more efficient as it discharges) and less energy is wasted as heat.

Note, it might make sense to remove the power LED from the Nano, to save 3 to 5 mA of current.

simulate this circuit – Schematic created using CircuitLab


Not sure if my Arduino Uno is damaged When I plug the USB cable to my Arduino and try to upload a sketch I get thtis error:

avrdude: ser_open(): can't open device "/dev/cu.usbmodem1411": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

when I go to Tools > ports I can't find the USB port.
The Arduino still working and green ligh is on, so what is the problem exactly?

Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.

Try rebooting your Mac.

If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.


Can I use IO10 as digital IO while using SPI interface? If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

I am actually using an Intel Galileo, with the same pinout as an Arduino Uno Rev3.

Can I use IO10 as digital IO while using SPI interface?

On AVR it must be OUTPUT when using SPI in master mode and INPUT in slave mode.

  If my arduino is the master device in a SPI network, hence not using the slave select SS pin, can I use the same pin as IO10?

The SS pin (D10) has to be OUTPUT when using SPI master mode. It can be used for chip select on the SPI bus (slave select) or some other output function.

So far the Arduino design with AVR (e.g. ATmega328). The Intel Galileo based Arduino has the following block diagram:

IO10-IO14 are multiplexed from SPI1 or GPIO. This implies that the SPI SS (IO10) signal is hardwired to the SPI controller when enabled. Last, according to the product info SPI is master only. More details schematics details here.

Cheers!


Change/declare a constant in setup and use it in loop I want to change or declare a constant in the setup() and then, I want to access it in the loop().
I have searched a lot, but the only questions I found could be solved by declaring the constant in the beginning of the program. That doesn't work for me because I am using the Adafruit BMP388 and I can't use the pressure before the setup().
I also tried declaring the variable before the setup() and changing it inside the setup(), but it didn't change when I used it in the loop().
How can I solve this?

You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:
why not try something roughly like this (untested and incomplete)?
Adafruit_BMP3XX bmp;
float startPressure;
float difference;

void setup() {
  bmp.begin_I2C();
  startPressure = bmp.readPressure();
}

void loop() {
  difference = startPressure - bmp.readPressure();
}

Or, better:
Adafruit_BMP3XX bmp;

void setup() {
  bmp.begin_I2C();
}

void loop() {
  static const float startPressure = bmp.readPressure();
  static float difference;
  difference = startPressure - bmp.readPressure();
}


Can i run brushless ESC from any digital pin of arduino {assume arming is done}
Can i connect the brushless ESC to any digital pin and give writemicroseconds() to it? Will this work. because i have connected my 4 ESC's to "~" pins. so i thinks that other will not work.

It should work.

The Servo library doesn't use hardware PWM, so you can connect them to a non "~" (PWM) pin.


Do I have to use an RTC to build a clock? While I was researching ideas for an Arduino clock, I found several clocks that incorporated an RTC (Real Time Clock) module.

I don't know why it is used in some clocks.

So, here are my questions:

How does an RTC module work?
Do I have to use it "like a rule" (is an RTC necessary or unnecessary) in my clock?

How does a RTC module works?

It counts. As simple as that. Once a second it ticks and counts up. It also remembers - most have a battery backup and will continue ticking when you turn the main power off.

  I have to use it "like a rule" (if it is necessary or unnecesary) in my clock?

If you want accuracy and continuation, yes.  An RTC is designed to tick at (as close as reasonably possible) once per second. Trying to do that with just an Arduino is incredibly difficult. The ceramic resonator on an Arduino is not as accurate as the quartz crystals used with an RTC. After a week you may find you are an hour out.


How to control segments with SevSeg library The SevSeg library by Dean Reading seems to have a keyword to control individual segments on SSD's. I am using four common cathode, single digit displays. Does anyone know how to program individual segments?

#include "SevSeg.h";

SevSeg sevseg;

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

  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
    resistorsOnSegments,
    updateWithDelays, leadingZeros, disableDecPoint);

}

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

  sevseg.setSegments();
  //sevseg.setNumber(1234,0);
  //sevseg.setChars("");
  //sevseg.blank();
  sevseg.refreshDisplay();

}

You can't with that library. The author has not provided any public methods that will do the job.

There are private methods (segmentOn and segmentOff) that might be usable, but you would have to modify the library to be able to access them.


Refreshing a web-page hangs after few times I'm using a Nucleo F429ZI board and I wrote a sketch that enables a simple web-server:

#include <LwIP.h>
#include <STM32Ethernet.h>

const int WEB_PORT = 80;
EthernetServer server(WEB_PORT);
char buffer[1024];

void setup()
{
    Serial.begin(115200);
    // define variables
    Ethernet.begin(localIP, netmask, dns, gateway);
    server.begin();
}

void loop()
{
    processServer();
}

void processServer()
{
  String readString;
  EthernetClient client = server.available();
  if (client)
  {
    while (client.connected())
    {
      if (client.available())
      {
        char c = client.read();
        readString += c;

        if (c == '\n')
        {
          if (readString.startsWith("GET"))
          {
            readString.remove(0, 4);
            int pos = readString.indexOf(' ');
            String path = readString.substring(0, pos);

            if (path == "/status") pageStatus(client);
            break;
          }
        }
      }
    }
    delay(1);
    client.stop();
  }
}

void pageStatus(EthernetClient client)
{
    sectionHeader(client, 2);
    client.println("");
    client.println("");
    client.println("
");
    client.println("
Servo	Position	Running	Initialized
");

    for (int i = 0; i < getParamUInt8(P_SERVO_SIZE); i++)
    {
        sprintf(buffer, "
%u	%d	%s	%s
", i + 1, (int16_t) _servo[i].current, _servo[i].ended ? "NO" : "YES", _servo[i].initialized ? "YES" : "NO" );
        client.println(buffer);
    }
    client.println("
");

    client.println("

");

    client.println("
");
    client.println("
Led	PWM	Running
");

    for (int i = 0; i < getParamUInt8(P_LED_SIZE); i++)
    {
        sprintf(buffer, "
%u	%d	%s
", i + 1, (int16_t) _led[i].pwm, _led[i].ended ? "NO" : "YES");
        client.println(buffer);
    }
    client.println("
");

    client.println("

");

    client.println("
");
    client.println("
Stepper	Position	Running
");

    for (int i = 0; i < getParamUInt8(P_STEPPER_SIZE); i++)
    {
        sprintf(buffer, "
%u	%d	%s
", i + 1, (int16_t) _stepper[i].stepper.getCurrentPositionInMillimeters(), _stepper[i].stepper.motionComplete() ? "NO" : "YES");
        client.println(buffer);
    }
    client.println("
");
    client.println("");
}

void sectionHeader(EthernetClient client, int refresh)
{
    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: text/html");
    client.println("Connection: close");
    if (refresh) client.println("Refresh: 2");
    client.println();
    client.println("<!DOCTYPE HTML>");
}

As you can see in the sectionHeader() I want to refresh the page every 2 seconds. It works, but after 3 or 4 refreshes it hangs and I have to reset the whole board.

Of course with an embedded system I would use Ajax... here I thought reloading the page should be enough.

What might cause such a hang?

The code you have that says readString += c has to allocate a whole new string whenever it runs out of space for more characters. All those allocations are filling up memory.

Instead of the String class, use a single C character array, e.g.

char s[128];

that is big enough for whatever you put in it.

If it helps, I wrote a simple arduino web server for my own project, and if you look at the code here that may give you ideas for how to implement this.


If I have a group of Arduinos connected via I2C, can one Arduino cause the rest to freeze? I have a group of four Arduino boards connected via I2C.  One is the master, which sends and receives values from all of the others.  I noticed that the Master will stop executing its loop if power is removed from one of the other Arduino boards.

Can one Arduino in a I2C group cause the rest to freeze?
Is there a way to prevent this?

I am using one of the Arduino boards to connect to a server via network shield and I don't want the other Arduino boards to be effected if the networked Arduino freezes.

There are a number of places in the standard Wire library where the code goes into a tight loop waiting for an interrupt to occur. If that is missed for some reason, it will loop indefinitely.

By removing power from one of your devices you may be introducing electrical conditions that prevent the I2C messages from being transmitted properly (possibly just noise). Alternatively the device may parasitically power up from the SDA/SCL data and then behave in unpredictable ways. It is probably unwise to do this.

There is an alternative I2C master library at http://dsscircuits.com/articles/arduino-i2c-master-library which does not hang (I believe it times out instead).


Expected unqualified-id before 'public' I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say expected unqualified-id before 'public'.

Does anybody know how to fix this?

void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}

static public int recordings[99999999] = {NULL}

This is not valid C code. Remove the word public.
Also you cannot create such a big array. The Arduino has only 2 KB (SRAM) memory and also since it is static you have to fill it with values directly, like:

static int recordings[5] = { 0, 1, 2, 3, 4 };

How many values you want to store?

In case you need quite a lot (like hundreds), I would use a different solution for the state array as it only stores values 0 or 1. For example, you can use arrays of uint8_t which cost only 1 byte per element, but even better would be to store 8 0 or 1 (boolean) values in one byte each, but that means you have to get/set the values in the correct indices yourself.


FastLED fill_rainbow - Unexpected red pixel I'm using FastLEDs builtin fill_rainbow function for generating a rainbow spectrum on an LED strip. The issue is, I get a random red pixel midway through the yellow region. I've tried it on 3 different Arduino nano's, and two different LED-strips. Here's the code:

#include <FastLED.h>

#define DATA_PIN 2
#define NUM_LEDS 114
CRGB leds[NUM_LEDS];

uint8_t hue = 0;

void setup() {
  Serial.begin(115200);
  FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);

  fill_rainbow( leds, NUM_LEDS, hue, 1);
  for(int i=0; i<NUM_LEDS; i++) {
    Serial.print(i);
    Serial.print(' ');
    Serial.print(leds[i].r);
    Serial.print(' ');
    Serial.print(leds[i].g);
    Serial.print(' ');
    Serial.println(leds[i].b);
  }

  CHSV hsv;
  CRGB rgb;
  //rgb = hsv;
}

void loop() {
  fill_rainbow( leds, NUM_LEDS, hue, 1);
  FastLED.show();
}

Here pixel number 60 gets the rgb code 160, 0, 0. When it should have something like 160, 150, 0.

The strangest part of all is that I can get rid of the problem in two ways, either by uncommenting the line rgb = hsv;, or by commenting out the fill_rainbow function in the loop function. This strange behavior leads me to believe im somehow messing up a pointer or misusing a FastLED feature. Additionally the fill_rainbow function is very simple and relies on FastLEDs hsv to rgb typecasting, which is another reason to believe I'm doing something wrong.

So help me out here, am i doing something silly, or have I discovered a bug with FastLEDs hsv to rgb converter?

I just copied your exact code and ran it with 600 of my LEDs. I have WS2812B as well, and using the same data pin coincidentally.

I haven't experienced your red LED issue. I then ran it again on my LEDs after adding

 hue++;

at line 33.

Only problem I can see is that the last 30 LEDs at the end of the rainbow kind of flicker. Groups of 10 LEDs spontaneously flicker at once, then another 10, and so on. This could be a problem with my LEDs though because they were the cheapest one's I could find on ebay 2 years ago. The code seems to work fine for me though!


Multiple If statements I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages.
my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?

#include <LiquidCrystal595.h>
#include <GSM.h>

GSM gsmAccess;
GSM_SMS sms;
char sendernumber[20];
int Enable_m=11;
int Control_2=12;
int Control_7=10;
LiquidCrystal595 lcd(7,8,9);
void setup()
{
   Serial.begin(9600);
   pinMode(Enable_m,OUTPUT);
   pinMode(Control_2,OUTPUT);
   pinMode(Control_7,OUTPUT);

   digitalWrite(Enable_m,LOW);
   digitalWrite(Control_2,LOW);
   digitalWrite(Control_7,LOW);

   lcd.begin(16,2);
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Hello");
   lcd.setCursor(0,1);
   lcd.print("Everyone");
   delay(2000);

   while (!Serial)
      Serial.println("SMS Messages Receiver");
   boolean notConnected = true;
   while(notConnected)
   {
      if(gsmAccess.begin("0000")==GSM_READY)
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   Serial.println("GSM initialized");
   Serial.println("Waiting for messages");
}

void loop() {
   // put your main code here, to run repeatedly:
   char c;
   int val=0;
   val=digitalRead(Enable_m);
   if (val==LOW){
      digitalWrite(Enable_m,HIGH);
   }
   if (sms.available())
   {
      Serial.println("Message received from:");
      sms.remoteNumber(sendernumber, 20);
      Serial.println(sendernumber);

      if(sms.peek()=='#')
      {
         Serial.println("Discarded SMS");
         sms.flush();
      }
      while(c=sms.read())
         if(c=='motoroff'){
            analogWrite(Enable_m, 0);
            digitalWrite(Control_2,LOW);
            digitalWrite(Control_7,LOW);

         }
      if(c=='motoronclockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='motoronanticlockwise'){
         analogWrite(Enable_m, 255);
         digitalWrite(Control_2,HIGH);
         digitalWrite(Control_7,LOW);
      }
      if(c=='speedhalf'){
         analogWrite(Enable_m, 128);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speedquarter'){
         analogWrite(Enable_m, 65);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      if(c=='speed75'){
         analogWrite(Enable_m, 192);
         digitalWrite(Control_2,LOW);
         digitalWrite(Control_7,HIGH);
      }
      else{
         digitalWrite(Enable_m,HIGH);
         Serial.print(c);
      }
      Serial.println("\nEND OF MESSAGE");
      sms.flush();
      Serial.println("MESSAGE DELETED");
   }

}

Two things:

The else will only be subject to the last if being false, the rest of the if statements are completely separate and can affect the else in no way whatsoever.  To chain them you need if (...) { blah blah } else if (...) { blah blah } etc.
You cannot compare characters and strings like that (and in fact they're not even strings, they're lots of characters squeezed into a single character through the use of the wrong kind of quotes).

So basically no, your whole program there is completely wrong and won't do what you think it will and you need to completely re-thing how it works.

Some tips:

Use strcmp() to compare strings.
If reading strings from serial store them in character arrays not a single character.

You might find this useful:

http://hacking.majenko.co.uk/reading-serial-on-the-arduino
http://hacking.majenko.co.uk/the-evils-of-arduino-strings


Nano Every clone with ATMega4808 not recognized I've bought an Arduino Nano Every clone/compatible (not a standard Nano V3) that uses an ATMega4808 instead of the ATMega4809 the official Nano Every uses. This rather insignificant change of chip is detected by the Arduino IDE (v. 1.8.13) which tells me that the chip is wrong when I select "Nano Every" from the boards list and try to upload a sketch. The seller (link to the product) does not answer to my help requests. Does anybody own one of these and knows how to make it run?
Below a photo of the board. Note the small difference in pinout (4 extra pin, D22, D23, D24 and UPDI)

Probled solved, it turns out to be a Thinary Nano Every.
Instructions for installing on the Arduino IDE are on Github here: https://github.com/Thinary/ThinaryArduino


share enum between python and arduino I have created a gui in python that allows an arduino controlled mecanum wheel cart to move around.
The cart allows for 8 different move directions and can rotate left and right. Commands are sent over a serial connection between the laptop(w10, python) and the arduino.
I have an Enum class in python representing the different move directions.
I have a corresponding enum in the arduino to interprete the commands from the python task.
What is an easy way to share a single common enum definition for both coding environments?

One approach that I have used for similar purposes is to generate the appropriate header files (or module or whatever) from a simple text file for all the required uses.
Since you already know python this should be pretty easy. Quick "proof of concept" follows. (Warning: I barely know any python.)
One downside to this is that you have to remember to regenerate the header/module each time you update the enum (keys or values) - don't forget to recompile for the C++ part. If you have a build system, it is best to integrate that code generation step into it.
A variation of this is to parse one of the language's source code to extract the definition and output it in a format suitable for the other. That is generally much harder to do though if you want to make it robust.

robot.enum
UP    1
DOWN  2
LEFT  3
RIGHT 4
JUMP  5

enum_generator.py
def python_enum(filename):
    with open(filename, 'w') as w:
        w.write('class Robot(Enum):\n')
        with open('robot.enum') as r:
            for line in r:
                parts = line.split()
                w.write(f'    {parts[0]} = {parts[1]}\n')

def cplusplus_enum(filename):
    with open(filename, 'w') as w:
        w.write('#pragma once\n')
        w.write('enum Robot: int {\n')
        with open('robot.enum') as f:
            for line in f:
                parts = line.split()
                w.write(f'  {parts[0]} = {parts[1]},\n')
        w.write('};');

python_enum('robot_enum.py')
cplusplus_enum('robot_enum.h')


How to use more than 2 I2S microphones on MKR Zero? I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.

By definition, the I2S bus only allows up to 2 channels to be transmitted at the same time.  Here is a quote from the Details section of the Wikipedia's I2S page:

  The word select clock lets the device know whether channel 0 or
  channel 1 is currently being sent, because I²S allows two channels to
  be sent on the same data line.

This is further illustrated in Figure 8 / Page 6 of the Knowles SPH0645LM4H data specifications.  In this figure we see where 2 SPH0645LM4H microphones are configured (ground or Vcc to the SEL pin 2) such that they can be multiplexed onto the I2S bus by the I2S bus master.


Use of "static" with "RTClib" I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".

Here you can see an excerpt from the example provided for the pcf8523 real-time clock:

#include "RTClib.h"

RTC_PCF8523 rtc;

void setup () {

  while (!Serial) {
    delay(1);  // for Leonardo/Micro/Zero
  }

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    /*
    do some more stuff
    */
}

In the beginning of loop() they wrote:

DateTime now = rtc.now();

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right?
This appears inefficient to me.

I thought about rewriting it this way:

static DateTime now;    // static declaration, executed only once
now = rtc.now();    // assignment to "now" every time loop() starts over

In this case "new" should be allocated on the stack like a global variable, right?

I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.

Link to the library:
https://github.com/adafruit/RTClib

Thank you! :-)

EDIT: For some reason I CAN NOT declare DateTime now; in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.

You wrote:

  DateTime now = rtc.now();

  Thus, with every iteration of loop() "now" gets defined anew (on the
  heap?!), right?

No. Local variables like this are usually allocated on the stack,
although the compiler may keep them in CPU registers if that helps
optimization.

  static DateTime now;    // static declaration, executed only once

  In this case "new" should be allocated on the stack like a global
  variable, right?

No. It is allocated statically, in the .bss section, like uninitialized
global variables.

  I want to use "static" to increase overall performance by reducing
  work for the processor

Not sure it will make much difference. Static allocation may save you a
few CPU instructions compared to stack allocation (the instructions that
move the stack pointer). On the other hand, it will cost you a few
instructions compared to register allocation (the instructions to access
the RAM).

  avoiding heap fragmentation

Stack allocation does not use the heap, and the stack never fragments.

  Does this make sense or will it cause more problems than it solves?

If you really care about sub-microsecond differences in the execution
time, you should either look and the disassembly of the program, or do
some benchmarking. Otherwise just write whatever makes more sense from
the point of view of the program's logic: does the variable need to keep
its value across calls to loop()? If the answer is “no”, do not use
static.


Is my sketch 'thread safe'? I come from a .Net background, typically I would 'lock' operations on an integer when I have thread-safe requirements. I'm not sure that applies to my sketch here? Could I potentially bypass an increment from one of my interrupt pins?

In summary, I have 2 interrupt pins - I want to increment a count which (every 5 seconds) writes via serial and resets.

I'm doing this to, kind of, avoid writing serial from within an interrupt - since I've read it's strongly discouraged.

#include <Controllino.h>

const byte interruptPin0 = CONTROLLINO_IN0;
const byte interruptPin1 = CONTROLLINO_IN1;
int counter1 = 0;
int counter2 = 0;
unsigned long previousMillis = 0;
unsigned long interval = 5000;
int a = 60;
char buffer[256];

void setup()
{
  pinMode(interruptPin0, INPUT_PULLUP);
  pinMode(interruptPin1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin0), pin1Fired, RISING);
  attachInterrupt(digitalPinToInterrupt(interruptPin1), pin2Fired, RISING);
  Serial.begin(9600);
}

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    sprintf(buffer,"A%d",counter1);
    Serial.println(buffer);
    sprintf(buffer,"D%d",counter2);
    Serial.println(buffer);
    counter1 = counter2 = 0;
  }
}

void pin1Fired()
{
  counter1++;
}

void pin2Fired()
{
  counter2++;
}

There is indeed a race condition in your code: if an interrupt fires
while you are reading one of the counters, you might read garbage. If it
fires between reading and resetting the counter, you loose one count.

The way to prevent the race is to block interrupts while the main thread
(everything that does not run in interrupt context) accesses the
counters. BTW, do not forget to make the counters volatile.

The portions of the code that run with interrupts disabled are called
“critical sections”, and you should keep them as short as possible in
order to limit the interrupt latency they introduce. Typically, within
those critical sections you do nothing more than access the shared
variables. Example:

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    noInterrupts();  // start of critical section
    int counter1Copy = counter1;
    counter1 = 0;
    interrupts();  // end of critical section
    Serial.print("A");
    Serial.println(counter1Copy);
    noInterrupts();  // start of critical section
    int counter2Copy = counter2;
    counter2 = 0;
    interrupts();  // end of critical section
    Serial.print("D");
    Serial.println(counter2Copy);
  }
}


EEPROM bytes preset to 255 while programming I'm working on a program with Arduino Uno which involves writing and reading EEPROM. I'm using a basic EEPROM library. My problem is: EEPROM values are preset to 255 whenever I burn my program. And there is nothing in my code which will write 255 in these bytes.

I even tried EEPROM_read example from the EEPROM library and got same result. I used EEPROM_clear code before EEPROM_read to set all values to 0. But when I read those values using EEPROM_read, they are 255.

Please help explain what is happening.

In flash and eeprom memory an erased value is 255. It's all about how flash memory works. If you want something other than 255 in there you will have to write something other than 255 in there.


Stopping motor DC with 2 limit switches I try to build an automatic roof with rain sensor input, when it's rain the roof then closed pulled by DC motor on the tracks and activate a buzzer. When it reach the end (limit switch pressed) then the motor stopped and buzzer off. And when the rain stopped, motor will turning again to open the roof until the second limit switch pressed to stop the DC motor.

I have try to make my own program but it have an error, when it's has no rain detected the motor spin to close the roof and stop when limit switch pressed (LOW logic), but when rain detected the buzzer turned on but the motor doesn't spin at all. Here is my code, I'm using L293D for motor driver and using its enable pin.

void setup() {
  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  if (analogRead(rainSensor) < 650){
    digitalWrite(alarm, HIGH);
    digitalWrite(motor_close, HIGH);
    digitalWrite(motor_open, LOW);
  }
  else if (digitalRead(stop_close) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else if (analogRead(rainSensor) > 850){
    digitalWrite(alarm, LOW);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
  }
  else if (digitalRead(stop_open) == LOW){
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
  }
  else {
    digitalWrite(enable_motor, HIGH);
    digitalWrite(alarm, LOW);
  }
}

Can I use If-Else logic? Or I make a mistake?

Your logic is a bit off. For example, when it is raining and rainSensor < 650, only that part of the if gets executed and the else if parts never happen.

You could just wait for the roof to open/close in a loop. Also, you will find it helpful to break your code into smaller functions. (I'm not sure what the enable_motor pin is for, so that part may need fixing).

// This function determines the current status of the roof
enum {OPEN, CLOSED, OPENING, CLOSING, UNKNOWN};
byte get_roof_status()
{
    if (digitalRead(stop_close) == LOW) return CLOSED;
    else if (digitalRead(stop_open) == LOW) return OPEN; // Fixed typo
    else if (digitalRead(motor_open) == HIGH) return OPENING;
    else if (digitalRead(motor_close) == HIGH) return CLOSING;
    return UNKNOWN;
}

// Helper functions
void open_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_close, LOW);
    digitalWrite(motor_open, HIGH);
    // Loop until roof is open
    while (OPEN != get_roof_status()) /* NULL */;
    stop();
}
void close_roof() {
    digitalWrite(alarm, HIGH);
    digitalWrite(enable_motor, HIGH);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, HIGH);
    // Loop until roof is closed
    while (CLOSED != get_roof_status()) /* NULL */;
    stop();
}
void stop() {
    digitalWrite(alarm, LOW);
    digitalWrite(enable_motor, LOW);
    digitalWrite(motor_open, LOW);
    digitalWrite(motor_close, LOW);
}

void setup() {
  // Set the pinmodes
  pinMode(enable_motor, OUTPUT);
  pinMode(motor_open, OUTPUT);
  pinMode(motor_close, OUTPUT);
  pinMode(stop_close, INPUT_PULLUP);
  pinMode(stop_open, INPUT_PULLUP);
  pinMode(alarm, OUTPUT);

  digitalWrite(enable_motor, HIGH);
  digitalWrite(motor_open, LOW);
  digitalWrite(motor_close, LOW);
  digitalWrite(alarm, LOW);
}

void loop() {
  // This function is much simpler now
  if (analogRead(rainSensor) < 650) {
    close_roof();
  }
  else if (analogRead(rainSensor) > 850){
    open_roof();
  }
}


Missing time when using timer I have set up Timer2 to count every tick at 16MHz, or 62.5ns per tick. Then I run the following code:

int t = 0;
    for (int i=0;i<64;i++){
  data[4*i] = TCNT2;
  data[4*i+1] = TCNT2;
  byte now = data[4*i+1];
  byte last = data[4*i];
  t += now > last? (long)(now-last) : 256 -(long)(last-now);
  data[4*i+2] = TCNT2;
  data[4*i+3] = TCNT2;
  }
}
for (int i=0;i<255;i++){
  Serial.println(data[i]-data[i+1]);
}

and I get the output: "4 4 4 11" (repeated) which makes sense, 4 clock cycles to read TCNT2 and write it to the correct place in data and 11 cycles when also evaluating the loop condition. However, I can't understand when the variable t is updated. I have tried running with and without t and both give the same timings. From my (obviously lacking) understanding updating a variable is at minimum one instruction, so how can it do it under one clock cycle? Am I misunderstanding what one instruction is or does the TCNT2 counter for the timer not update accurately here?

Ops, I just realized it's the compiler working it's magic. I never used t, thus the compiler said "Wtf is this guy doing, this t is useless and I'll remove it!". When I used t I got sensible results.


How to change Windows 10 Device Manager so Arduino NANO COM3 can operate on COM4 The Arduino ATmega328 NANO uses COM3 on my WINDOWS 10 computer,
but COM3 is NOT available.
QUESTION:
Please explain in detail how I can change this Arduino NANO
to operate on COM4

In device manager, right click on the device and select "Properties". Then go to the tab "Connection properties" and click on "Advanced". There you can change the COM port number assignment for a particular device.


Using all ten capacitive touch inputs on the ESP32 I am using a Wemos Pro ESP32 development board and would like to be able to use all ten of the available capacitive touch inputs. I am able to get readings from nine of them but not T1. Here is the pin diagram for the board I have.

Running this code on my board produces no difference in reading for T1...

#define numTouchPins 10
byte touchPins[] = { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9 };
byte touch[10] = {};

void setup() {
    Serial.begin(115200);
    delay(1000);
}

void loop() {
    for( byte pin = 0; pin < numTouchPins; ++ pin ) {
        touch[pin] = touchRead( touchPins[pin] );
    }
    for( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print( "\t" );
    }
    Serial.println();
}

So the reason for this is that T1 is on GPIO0 which is also connected to a button labeled 0 on the board. Now I realise this is needed in order to select between the ROM serial bootloader mode and the normal execution mode... But, is there a way to change the pinmode from digital-in to touch-in once normal boot has completed? Is there something I can write in the Arduino setup() method that would make this pin behave like the other touch pins?

is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.

You cannot have touch inputs connected to anything else.  The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.