WifiClient and aREST on esp32 - loop until new instructions recieved? I've created a simple sketch for an esp32 that hosts a REST API that can be accessed via HTTP. Based on the instructions received from the client, the esp32 controls some neopixels with some various animations I've written.

Everything worked as expected until I got to an animation that runs in a while loop. The loop breaks when a new client is detected so that the light can switch functions. However, when the new client is detected, the client seems to be discarded or consumed, and i just end up back in the loop() function until I make a second HTTP request, then the changes to show up.

I'm sure it's something obvious, but what have I done wrong?

Code:

#include "WiFi.h"
#include "FastLED.h"
#include "aREST.h"
#include "ArduinoJson.h"

#define NUM_LEDS 64
#define DATA_PIN 18

CRGB leds[NUM_LEDS];
int LED_COUNT = 64;
int MAX_BRIGHTNESS = 200;

const char* ssid = "wifi";
const char* password = "password";
aREST rest = aREST();
WiFiServer server(80);
WiFiClient client;

void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, LED_COUNT);
  flashAll(CRGB::Black);
  // Bind urls to the handling functions
  rest.function("random-strobe", randomStrobe);
  rest.function("solid-color", solidColor);
  rest.function("reset", reset);

  // Connect to WiFi and wait until we're connected to continue
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    flashAll(CRGB::Cyan);
    delay(500);
    flashAll(CRGB::Black);
    delay(500);
  }
  server.begin();
  flashAll(CRGB::Green);
  delay(2000);
  flashAll(CRGB::Black);
}

void loop() {
  if (checkForTask()) {
    rest.handle(client);
  }
}

boolean checkForTask() {
  // I have tried making this reassignment conditional
  // when the global 'client' is false, but it did not help
  //if (!client) { client = server.available(); }
  client = server.available();
  if (client) {
    return true;
  }
  return false;
}

int randomStrobe(String params){
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:application/json");
  client.println();
  client.stop();
  StaticJsonDocument<200> jsonDoc;
  Serial.println(params);
  Serial.println("params recieved. parsing...");
  auto error = deserializeJson(jsonDoc, params);
  if (!error) {
    // some setup stuff
    while(!checkForTask()){
      // do stuff in here
    }
    return 0;
  }
}

server.available() doesn't return an already 'claimed' connection again. It returns a new connection or an empty WiFiClient object.

The esp8266 and esp32 Arduino core WiFi library close the underlying connection if the last referring WiFiClient instance is freed. The assignment of empty WiFiClient object frees the previous reference to underlying socket and if it was the last referrence, the library closes the socket.

You get a client with server.available() in checkForTask() and then you call server.available() again. It returns an empty WiFiClient object and you assign it to your WiFiClient object. The library closes the referred connection.

The solution is not to check server.available until WiFiClient is valid.

if (!client) {
  client = server.available();
}


Start to build a robot I would like to start with a very simple robot, which should be based on an arduino uno.
I already have an uno and made the decision fpr my robot chassie:
https://www.roboter-bausatz.de/en/diy-electronics/kits/robotic-kits/97/2wd-motor-smart-car-chassis-fuer-roboter-mit-getriebemotor-und-batteriebox

Additionally I want to by an ultrasonic distance sensor and a infrared sensor.
What else do I need to start ? Only a DC motor driver or anything else?

Thanks in advance
LStrike

You'll need:

Emergency switch (it should be easy to cut the power off, even for small robots)
A chassis (you've found one already)
Motors (Obviously)
Motor control (Probably a dual H-bridge, think if you need reverse or not.)
Power (powering on (single use) batteries may not be your best option)
Controller (Arduino Uno, or something smaller or faster)
Sensors (Can be anything, depending on the requirements)

A way to communicate with the robot is also nice, often wireless (bluetooth/wifi/443mhz).

And also, it will be nice if the robot fits some kind of purpose, but this could be added later.
You could think of the robot having to pick up and carry something, extinguish a flame etc.

I advise to check out one of the many tutorials on building a robot, they often have a detailed parts list (sometimes even shopping links).


What's the difference between a clone and a counterfeit Arduino? I've been hearing a lot about clones and counterfeits. What are the differences between the two?

The difference is simple:

Clones don't say "Arduino," where counterfeits do

If I were to create 200 boards all labeled "Arduino UNO R3," it would be a counterfeit. If I were to call them "Happyduino," it would be a clone.

Note: You can still write Happyduino (Arduino Compatible) on your product. Here's a quote from the Arduino FAQ section

  Not okay:

  Arduino Xxxxxx
  Xxxxxx Arduino
  Arduino Compatible Xxxxxx - use "Xxxxxx (Arduino-Compatible)" instead

  Okay:

  Xxxxxx for Arduino - products that work with official Arduino boards    (e.g. shields or kits)
  Xxxxxx (Arduino-Compatible) - variations and clones which are    software and hardware compatible

  Note that while we don't attempt to restrict uses of the "duino"
  suffix, its use causes the Italians on the team to cringe (apparently
  it sounds terrible); you might want to avoid it. (It's also
  trademarked by a Hungarian company.)


Transistor switching problem With my team we constructed a circuit using Arduino. The circuit works on the Proteus simulator. It worked fine with LEDs connected directly to Arduino outputs.

However, when I used Arduino output to trigger a BC 337 transistor to try and actuate a 12 V DC coiled relay, it wouldn't trigger. I measured voltage across transistor collector and emitter, it reads 12 V, just like the source I gave... (The transistor is not switched on I guess).

Supply for the Arduino is a constant 5 V DC.

Where have I gone wrong? Picture as uploaded.

Furthermore, we are trying to build a controller for an ice making machine. The power circuit (12 V) is to be controlled by Arduino through the transistors.

I am uploading the codes we used and the full circuit diagram.

const int start = 13;
const int comp= 2;
const int cond=3;
const int hGas=4;
const int wbut=12;
const int watersol=5;
const int dumper=6;
const int iced=11;

int startButton=0;
int waterButton=0;
int dumperlimswitch=0;

void setup() {

  pinMode(start, INPUT);
  pinMode(comp, OUTPUT);
  pinMode(cond, OUTPUT);
  pinMode(hGas, OUTPUT);
  pinMode(wbut,INPUT);
  pinMode(watersol, OUTPUT);
  pinMode(dumper, OUTPUT);
  pinMode(iced, INPUT);
}

void loop() {

startButton = digitalRead(start);
waterButton = digitalRead(wbut);

 if (startButton == HIGH) {

    digitalWrite(comp, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
     delay(800);
    digitalWrite(hGas,HIGH);
    digitalWrite(cond, LOW);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(500);
    digitalWrite(hGas, LOW);
    digitalWrite(dumper, HIGH);
    digitalWrite(cond, HIGH);

    waterButton = digitalRead(wbut);
    if (waterButton == HIGH){
      digitalWrite(watersol,HIGH);
      }
    else{
      digitalWrite(watersol,LOW);
      }
    delay(800);
    digitalWrite(dumper, LOW);
  }
else {
    digitalWrite(comp, LOW);
    digitalWrite(cond, LOW);
  }
}

TL/DR: Your LEDs without resistors are diverting all the current away from the transistors so they are unable to switch.

In detail:

Let's take a quick look at just one small portion of your circuit in more detail:

simulate this circuit – Schematic created using CircuitLab

I have added an extra resistor into the circuit - Rw - which represents the resistance of the wires and pins of the LED, and I have given it a nominal 0.1Ω value.

Now, let's say you set the GPIO HIGH, so it outputs 5V. The LED, D1, is a typical red LED with a forward voltage of, say, 2V.  Let's calculate the current through the LED.

I = (VCC - VF)/R = (5 - 2) / 0.1 = 3 / 0.1 = 30A

30A?! But the GPIO can't provide more than 40mA absolute maximum. So all that can come from the GPIO is being sent straight through the LED leaving nothing (much) for the transistor.

Oh and yes, all that current demand is doing unspeakable damage to the Arduino's GPIO pin.

The transistor's Base-Emitter junction has about a 0.7V drop across it, and, if it weren't for the LED, with the 1kΩ resistor that gives (5-0.7)/1000 = 4.3mA. Which with a hFE of around 100, would give a collector current of around 430mA. And that should be fine for most small relays.

But with all the current being dumped through the LED what can get through to the transistor won't be enough to turn on the relay.

So increasing the resistance of the wire to the LED will decrease the current demands of the LED. And of course you do that by adding a resistor. So let's make that 1kΩ - a decent enough value for a simple indicator LED:

simulate this circuit

Now let's do the calculation for the LED's current:

I = (VCC - VF) / R = (5 - 2) / 1000 = 3 / 1000 = 3mA

Add that to the 4.3mA that wants to go through the transistor, and we have 7.3mA in total.

Now that is way below what the Arduino's GPIO can provide, so the IO pin is happy, the LED is happy and, most importantly, the transistor is happy.


Making servo spin and able to detect angle After researching other posts I can see how to make a servo spin continually and remove the ability to set to a specific angle.

What I'm trying to do is make a small project that has a spinning 'game wheel', each segment of the wheel has a prize on it (think almost wheel of fortune). The catch is when someone has landed on a prize once it cannot be landed on again so I want to manipulate the spin slightly so it doesn't stop on the same prize. Do do this I need to be able to get the spin AND know where the needle is pointing.

Is there a component that will allow both a full rotation AND the ability to control the location of the needle at the same time? I suspect servos can do one, or the either but not both.

The way I'd do it is the following:

use an optical encoder with an endstop, they come @ 1€ on ebay, bought 4 today :-) - this will tell you the angular speed and incremental position
use a photo transistor to detect a specific point on the wheel (make a small hole or paint a spot in a different colour) - this will give you
the absolute position of the wheel, to calibrate the previous step.

With this solution you do not even need a step motor, a DC motor will do it and probably has better characteristics, for the same cost.
So you could explore the DC option if it turns out that the stepper is not good enough.


Motor shields in arduino what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?

Servos require power and PWM. Servo shields come in two main forms:

Simple distribution
Active control

The first kind just provides convenient 3-pin headers to the Ardino's PWM pins, and sometimes a dedicated power supply for powering the servos. They're simple and cheap, but can only provide as many servo ports as the Arduino has PWM pins.

The second kind, more expensive, has a PWM chip on it to provide many more PWM pins than the Arduino can natively provide. Again there is sometimes a power supply as well, along with the convenient 3-pin headers. You usually interface with this kind using either I2C or SPI.  These are the ones people usually mean when they talk about a servo shield - a shield designed for powering and controlling many more servos than an Arduino by itself can manage.

Servo Motor Shields should not be confused with Motor Shields, which provide a number of H-Bridge drivers for powering and controlling (both the speed and direction) of a brushed DC motor.


Arduino resets variable every loop im new to arduino and have a problem currently with my project on sun tracking. The problem is that every loop it resets my variable back to 1 or whatever i set it. I have 4 photodiodes working properly but using only 2 on one axis. Code example:

void loop(){
    int stop1 = 1;
    senzor read1  //this is just code example
    senzor read2
    senzor read3
    senzor read4
    if (senzor1>senzor2){stop1=senzor1 - senzor2}
    if (senzor2>senzor1){stop1= senzor2 - senzor1}
    if (stop<5){stop motors}
}

this is simple example code and the problem is that it doesn't stop, it keeps looking for light (successfuly) and doesn't stop. Sorry for bad English if any and thanky in advance.

If you mean the variable stop1, it's true every loop it's set to 1.

If you don't want this, make it global, set it in setup (and change in loop when needed).

E.g.

int stop1 = 0;

void setup()
{
    stop1 = 1;
}

void loop()
{
    // Use stop and/or change it
}


Able to make continous music loop in Arduino and control the volume of the music with light sensor reading? I'm new to Arduino and am planning on making a simple program in Arduino that will play and loop a sound file on the computer whilst controlling the loudness of the music based on reading from a light sensor.

I was wondering if the first part, playing and looping the music on the computer is possible, because the second part of controlling the volume with the light sensor seems more straight forward if I had the first part down.

Thanks!

Having the Arduino play the audio doesn't really make sense for the scenario you describe.

I would suggest you write an application on the PC that plays music and takes in input from and external source that is used to control the volume. You could then use the Arduino (connected via USB) to relay the light sensor readings to your PC application. The PC application then does all the "heavy lifting" since it has significantly more resources available than compared to the Arduino.


Arduino Micro: Why am I getting 6.00 as a result instead of 6.66? Basically, on the TWR calculator page, when I entered 20 as the initial value and 3 as the value that comes after, I somehow get 6.00 as a result instead of 6.66 in the computeTWR() function. How can I fix this?
// ------------------- DIVIDER ---------------------
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 1.1
   An Open-Source Project by John Seong
*/

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void computeTWR(int thrustR, int weightR) {
  float result = thrustR / weightR;
  lcd.print(result);
}

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcdShow("Jeb's Launch", "Control System");
  delay(3000);
  lcdShow("Alpha Build 1.1", " STUDIO HORIZON");
  delay(3000);
  lcdShow("Welcome, Kerman", "Press any key...");
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, SET_THRUST, SET_WEIGHT, TWR_COMPUTE} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count, thrust, weight;             // countdown, thrust, weight value
  static float ratio;

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. Countdown", "2. TWR");
      state = MENU;
    /* fallthrough */
    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("Countdown Timer", "Seconds: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("TWR Calculator", "Thrust: ");
        thrust = 0, weight = 0, ratio = 0;
        state = SET_THRUST;
      }
      break;
    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("Lift off in", "     seconds");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;
    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count == 0) {
          Serial.println("Lift off!");
        } else if (count < 0) {
          state = START;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count < 10 ? "  " : count < 100 ? " " : ""); // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;
    case SET_THRUST:
      if (key >= '0' && key <= '9' && thrust <= 9999) {
        lcd.print(key);
        thrust = 10 * thrust + (key - '0');
      } else if (key == '#') {
        lcdShow("TWR Calculator", "Weight: ");
        state = SET_WEIGHT;
      } else if (key == '*') {
        state = START;
      }
      break;
    case SET_WEIGHT:
      if (key >= '0' && key <= '9' && weight <= 9999) {
        lcd.print(key);
        weight = 10 * weight + (key - '0');
      } else if (key == '#') {
        lcdShow("Thrust-to-weight", "ratio: ");
        computeTWR(thrust, weight);
      } else if (key == '*') {
        state = START;
      }
      break;
  }
}

(community wiki answer derived from comments - takes Q off unanswered list)

Why am I getting 6.00 as a result instead of 6.66?

because integer arithmetic discards fractional parts of results, including intermediate results
static int count, thrust, weight;             // countdown, thrust, weight value

If some of these are intended to have decimal values you need to use a more suitable data type (e.g. float)


what happens on Arduino power-on, and how long does it all take? Here's what I think happens and how long it takes (FIXME means I don't know).  I'd like to end up with solid max times for everything if possible.

Power-on, input caps to the 328P begin charging and Vcc to the 328P rising

From the time it first comes to life, internal 328P hardware holds an
internal reset line low.

Vcc to 328P climbs past the power-on reset voltage threshold V_pot, which has
a maximum value of 1.6V (see the ATmega328P_datasheet_revision_DS40002061A.pdf
Table 29-11).  For a 9V battery with a typical internal resistance of 2 ohms,
the time constant with the ~100 uF of input capacitance on the Arduino
is RC = (2 * 0.0001) = 0.0002 s.  So this normally happens pretty fast,
but note that if additional loads are connected to the Arduino Vcc or Vin
things might take longer.

A reset timer on 328P begins running.  When it expires the internal reset
line will be released.  How long this timer will run depends on fuse settings.
For the default Arduino fuse settings the timer will run for about 65 ms.
For a 3.3V Arduino variant the typical time will be slightly longer (~69 ms).
See ATmega328P_datasheet_revision_DS40002061A.pdf Table 29-11 Chapter 9
for details.

The PD7 line of the ATMEGA16U2 chip on on the Arduino holds the external
reset line low past the point in time at which the internal reset is released,
which causes the EXTRF bit of the MCUSR register on 328P the 328P to end up
set (indicating an external reset).  FIXME: does it actually work like this
(hold it low longer)?  FIXME: How long exactly?

The external reset is released by the ATMEGA16U2

The bootloader on the 328P begins executing

The bootloader examines the MCUSR and finds that EXTRF is set, but WDRF
of MCUSR is not set.  It therefore quickly flashes the on-board LED several
times and the attempts to download a new program over the serial line.
This process takes about 1.6 s total.

The download attempt terminates with a watchdog timer timeout and consequent
watchdog timer reset.  The EXTRF bit of MCUSR remains set (it is sticky and
is only cleared by a power-on reset or explicit 0 write).  Time: pretty quick

The bootloader starts executing (again).  Time: pretty quick

The bootloader examines the MCUSR and finds that the EXTRF and WDRF bits
of the MCUSR are both set.  It interprets this to mean that the bootloader
just executed and terminated due to a watchdog timeout, i.e. it decides that
an upload attempt has already been made.  It therefore clears the WDRF flag
(since it thinks it probably set it itself) and jumps to the start of the
application flash instead of making an upload attempt.  Time: pretty quick

All the setup code required to provide the C environment your main()
program requires runs.  This includes for example copying global variable
intial values from flash to RAM, etc.  Time: FIXME?

main() begins executing.

This is something that is far far easier to measure than to try and calculate.
Here's an Arduino Uno R2 with a simple sketch that just turns on D2.  Green is the power (7V to the barrel jack) and yellow is D2.

As you can see it takes 1.544 seconds (according to the resolution of my oscilloscope which, over those time scales, isn't that great) before D2 is driven high.
The sketch is simply:
void setup() {
  pinMode(2, OUTPUT);
  digitalWrite(2, HIGH);
}

void loop() {
}


I can't get code transferred to my Arduino Mini Pro About 3 years ago Sparkfun had a sale on Arduino Minis, so I bought 6 of them (3 x 3.3 V @ 16 MHz and 3 x 5 V @16 MHz). I used two of them for separate projects (everything worked flawlessly) then stored the rest. Then last night I grabbed one of the 5 V and 3.3 V Minis and tried to upload the Blinking LED program to them. But I kept getting this error:

avrdude: stk500_recv(): programmer is not responding

I'm getting similar results on all of these computers: Mac OS X 10.10, Mac OS X 10.7, and Windows 7. I tested with default drivers and I tried installing fresh drivers based on the HardwareID's of the devices. I used both the newest version of Arduino IDE and a few older versions.

I've tried two different USB devices: Sparkfun Basic FTDI and a Generic USB to Serial PL2303 similar to this one. They both produce the same error, however the FTDI seems to be somewhat able to communicate since the RX & TX lights are flashing as well as the Arduino LED. With PL2303, the LED is lit constantly.

While searching last night, I found a few forums where people suggested things like hitting the reset button and selecting different Arduino boards in the IDE.

Things have changed in the three years since you last used your FTDI board.

Most importantly avrdude has changed.

You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.

What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.

The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.

The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.


RF receiver becomes weakened after motor turns on I recently bought a simple SMAKN 315MHz RF receiver and transmitter, and I got everything working so that the transmitter transmits the value of a joystick, and the receiver receives that and uses it to set the analogWrite() of a motor on a PWM pin.

However, the moment the motor turns on, the receiver just weakens tremendously. At that point it only gets a message when I stick the receiver right against the transmitter. I’m powering the arduino and motor with a 3.7v LiPo battery btw.

Any help? I’ve tried with a 9V alkaline and a 9V adapter and nothing significantly changed.

That behaviour is to be expected. Motors are very noisy and cause massive amounts of interference in radio signals.

The best thing you can do is to try and suppress that interference. For this you will need three 0.1µF (100nF) ceramic capacitors.

One capacitor is connected between the terminals of the motor to reduce noise transferred down the wires (wires make good antennae). The other two connect between each of the terminals and the metal body of the motor.

The metal body of the motor then becomes a shield to trap the noise.


Explanation of the formula of the map funtion Can someone please explain (mathematically) how the formula for the map function actually came to light?
I have given the code of the map function below. You can see that it uses a formula to "map" values in a given range from a certain range. I don't quite understand how it came (not good at maths) :| So, I would like an explanation to how this formula came to light.

long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

map() implements linear interpolation.

  In mathematics, linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points.


LB1847 stepper controller :how to connect to grbl atmega based board with step ,direction,enable , limit? I like to use an LB1847 chip with stepper motor "both salvaged from old copier". I made a GRBL AtMega board, this board gives step, direction, enable and limit leads.

So I tried to find the corresponding pins on the LB1847, but the data sheet only shows enable1 and enable2 pins and phase1 and phase2 pins?

So how can I connect the step and direction and enable pins of AtMega to these pins of LB1847?

There are other logic pins on LB1847 chip to control current and decay.
If the data sheet is required i can upload it.

Thanks in advance

It seems that most people use an Arduino CNC Shield to connect their Arduino Uno (running GRBL software) to the drivers of the stepper-motors. Via Google you find plenty of them, for example: here and here. The schematics of the latter example are published here. You could use the information from this schematic to make your own 'interface' between the Arduino and the LB1847 driver chips.


Unrecognizable Message From PROGMEM char* I'm using a PROGMEM char* to store a massive array. When I try to print a certain part of the array, the message comes out mangled. How do I fix this?

The output should be "Poliwag", but it comes out as "arow".

#include <TrueRandom.h>
#include <EEPROM.h>
#define numPokemon 151
PROGMEM char* nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
"Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
"Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
"Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
"Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
"Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
"Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
"Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
"Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
"Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
"Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
"Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew"
};
int a = 0;
int b = 0;
int value;
String pokemonName = "Missingno";
int currentID = TrueRandom.random(1,numPokemon+1);
// a = CurrentID
void setup(){
  Serial.begin(9600);
  if (EEPROM.read(a)!=0){
    currentID = EEPROM.read(a);
    Serial.print("The Stored ID is ");
    Serial.println(EEPROM.read(a));
    Serial.println("Stored = true");
  }else{
    value = EEPROM.read(a);
    Serial.println(value);
    EEPROM.write(a,currentID);
    value = EEPROM.read(a);
    Serial.println(value);
    Serial.println("Stored = false");
  }
  pokemonName = nameArray[currentID];
  Serial.println(pokemonName);
}
void loop(){

}

The way you've written in, the pointer is stored in flash, but the strings are stored in SRAM. Read the appropriate documentation (also found in the Arduino reference) more closely, and do as it says.

char nmPokemon0[] PROGMEM = "MISSINGNO";
char nmPokemon1[] PROGMEM = "Bulbasaur";
 ...

PGM_P nameArray[] PROGMEM =
{
  nmPokemon0, nmPokemon1, ...
};

And don't forget to copy the string to SRAM as shown further down before outputting it, since Serial.println() can't work directly with flash.


What is the output of Software Serial .read() function Hi I am new to arduino development i was using esp8266 using software serial library

  here is the code

#include<stdlib.h>
#include <SoftwareSerial.h>

SoftwareSerial monitor(2, 3); // RX, TX

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

  sendDebug("AT");
  delay(5000);
  Serial.println("Hello");
  if(monitor.find("OK"))
  {
   Serial.println(monitor.available());
   Serial.println((int)monitor.read());
   Serial.println((int)monitor.read());
    Serial.println(monitor.available());
   Serial.println("RECEIVED: OK");
    //connectWiFi();
  }
  else
  {
    Serial.println("RECEIVED: None");
  }
}

void loop(){

}

void sendDebug(String cmd){
  monitor.println(cmd);
  Serial.println("Command: "+cmd);
}

  Output

Command: AT
Hello
2
13
10
0
RECEIVED: OK

All I know is monitor.available() return the available bytes that can be read and i can also deduce that these two bytes are O and K but the integer value doesn't corresponds to the ascii value of O and K

can anyone explain what is actually getting printed on the serial monitor what is 13 and 10 ? ??

It is just like https://www.arduino.cc/en/Serial/Read :

The monitor.find("OK"); already consumed the 'O' and the 'K' bytes, (see https://www.arduino.cc/en/Serial/Find ) then there were two bytes .available(), a 13=CarriageReturn and a 10=LineFeed, both returned by successive monitor.read()s, then zero more bytes in monitor.available().


Adding WiFi to my Arduino Keypad Lock I'm a really passionate beginner with arduino and electronics and I've built a Keypad lock for my room's door (inside the house).

I've used an arduino that activates a motor using a transistor to open the door if the correct pin is entered.

I want to add wifi control to my project. I have a few transistors, relays and ESP01s lying around for the upgrade. I want to use the blynk app and use the ESP01 independently without disturbing or modifying the arduino code. I'll program the ESP01 directly.

These are my requirements:

-A failsafe so I can open the lock via blynk if I forget the pin

-A kill switch that will turn off the arduino if I suspect somebody knows my PIN.

These are my ideas:

-Can I directly connect an ESP GPIO pin to the base of the transistor where the arduino is connected? By doing this can I control the transistor to switch the motor via both the arduino and the ESP 01?

-Can I put a relay module between the arduino and the battery pack and connect it to the ESP? I will connect the relay so that it will disconnect power to the arduino only when powered on. Is this a viable solution for a kill switch?

Any suggestions and ideas about how to go about this will be highly appreciated.

Can I directly connect an ESP GPIO pin to the base of the transistor where the arduino is connected?

No. You will effectively be connecting two outputs together, and that is very bad.

Instead you will need to add a second transistor in parallel to the first - one controlled by the Arduino and one controlled by the ESP-01.

  Can I put a relay module between the arduino and the battery pack and connect it to the ESP?

Sure. No problem with that.

  I will connect the relay so that it will disconnect power to the arduino only when powered on. Is this a viable solution for a kill switch?

As long as the kill switch doesn't also shut off power to the ESP-01 - otherwise it will just switch on again straight away...


SoftwareSerial error I have arduino , upon arduino I have Arduino GSM shield (Tx-2, Rx-3, Modem reset-7) and upon it, I have the Adafruit GPS Logger shield. I am trying to send sms of Latitude  from the GPS Logger shield to my numer through GSM shield. I am getting a error ..

SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_3'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_4'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here
SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::SoftwareSerial(unsigned char, unsigned char, bool)':
/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/SoftwareSerial/SoftwareSerial.cpp:335: multiple definition of `__vector_5'

GSM/GSM3SoftSerial.cpp.o:/home/thiyagu/Downloads/arduino/arduino-1.0.5/libraries/GSM/GSM3SoftSerial.cpp:148: first defined here

What is the meaning of this error ? what should I do to solve it?

This error means, that there is library overlapping on a vectors. To solve this error, you need to modify your Library file :

STEPS :

Remove the Softserial Library
Download AltSoftSerial library
if you have shield then you need to replace AltSoftSerial in place of SoftwareSerial in both .cpp as well as .h files.
Import AltSoftSerial library in place of SoftwareSerial in the sketch.

Execute .


exit status 1 'mySerial' does not name a type I just can't make it work for some reason. I tried #include <SoftwareSerial.h> and I tried #include "SoftwareSerial.h". Can someone help me?

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
}
  mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

simple mistake mySerial.begin(4800);
  mySerial.println("Hello, world"); lines was out of void {}

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
   mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I
}

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}


Serial.write printing blank values I've got an Adafruit Bluefruit NRF52 hooked up to the Adafruit BNO055 9-axis orientation sensor, but when I use Serial.write to send the data, serial monitor displays blank values only. The scroll bar drops so something I definitely appearing, it just seems to be empty.

Serial.print works fine, but I cannot use this for my application, as it uses too much memory.

I'm gathering 3 axis of absolute orientation plus 3 axis of acceleration (6 floats in total) plus a three digit number representing the calibration of each sensor.

Each line should look something like

303 68.69   4.19    -2.19   -0.12   0.14    -0.40

My code:

void displayCalStatus(void)
{

  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;
  bno.getCalibration(&system, &gyro, &accel, &mag);

  /* Display the individual values */
  Serial.write(gyro);
  Serial.write(accel);
  Serial.write(mag);
  Serial.write("\t");
}

void loop()
{
  imu::Vector<3> accel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);

  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  displayCalStatus();

  /* Display the floating point data */
  Serial.write(event.orientation.x);
  Serial.write("\t");
  Serial.write(event.orientation.y);
  Serial.write("\t");
  Serial.write(event.orientation.z);
  Serial.write("\t");

    /* Display the floating point data for Linear Acceleration */
  Serial.write(accel.x());
  Serial.write("\t");
  Serial.write(accel.y());
  Serial.write("\t");
  Serial.write(accel.z());
  Serial.write("\n");
}

Problem 1:

You wish to send/display on the Serial Monitor the int and float values generated by your sensor, but Serial.print() uses too much memory.

Solution 1:

Optimize your sketch to use less memory.

Problem 2:

Serial.write() doesn't cause the values to show up on Serial Monitor, but something is getting sent, because I see scrolling activity.

Solution 2:

Serial.write() sends raw bytes, whereas Serial.print() converts a variable to a string (or series of ASCII bytes) and sends that string. For example, Serial.write(65) sends A to the Serial Monitor because the ASCII value of A is 65; Serial.print(65) sends 65 to the Serial Monitor because it converts the numeric value 65 into a string containing the character 6 and the character 5, and sends that string to Serial Monitor.

The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.

Serial.write() comes in a few forms. One is Serial.write(val) which sends a single byte (named val, of type byte or compatible). Another is Serial.write(buf, len) which sends a series of len bytes, starting at the address of memory pointed by by buf. (This is often when buf is an array of bytes, so buf points to the first element of the array.)

If you wanted to send the 4 bytes of a float using Serial.write(), you could call:

Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

As an alternative, you can use bit shifting to send one byte at a time of the 4-byte float:

Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
Serial.write((byte)((event.orientation.x & 0x000000FF)      );

On the receiving end, you need to reconstruct your float by doing the reverse.

But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.

This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.

I did a quick search and found this arduino library that facilitates packet-based serial communication:

https://github.com/bakercp/PacketSerial

Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.


Is arduino suitable for high frequency application? Can I use the arduino for an application with a frequency of 4 MHz?

I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.

If it is not suitable, is it technically possible?

Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you can generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It may be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.

The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.


Arduino (Or Raspberry Pi) As HID Device I have an Arduino Uno and A Raspberry Pi B+. I was wandering how I could use either as a Programbel HID Device (EX: https://srlabs.de/badusb/). The Reason I ask under the arduino section is I want to preferably use it. If not I can use either.

The Uno cannot be used as a HID device through the on board USB. You might be able to use the V-USB Library to be a HID device using the digital IO pins. See this tutorial.

There are several arduino compatible boards that do can act as a HID device natively. Most boards built around the ATMega32u4 can be a HID device.  For example the Arduino Micro

See this question about the Raspberry Pi.


WEMOS: How to install it? I have been using an Arduino Uno for a year now, and I bought a WEMOS D1 Mini and a NodeMCU. I want to select WEMOS or NodeMCU from the Arduino Web Editor but it doesn't appear on the list:

I think I need to install a driver but it's only for the Arduino desktop editor (not for the web editor).

I just read that it can't. It's a shame:

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


Reading Serial String Gives Null Lines with JSSC I need to send serial data to my Arduino UNO from within a java application. I am using JSSC for this.
I wanted to verify that my data actually arrives correctly to the arduino before going to the next step of my application. For this I tried to just return the string I am sending, however when I send "test", this is what is returned:
t
null
est

I am wondering if this is a problem on the Java side with sending/reading the string, or that it's a problem with sending/reading on the arduino, and how I could possibly fix this.
This is my java code to read the data:
try {
    port.addEventListener(event -> {
        try {
            System.out.println(port.readString());
        } catch (SerialPortException e) {
            e.printStackTrace();
        }
    });
} catch (Exception e) {
    e.printStackTrace();
}

This is my java code to send the data:
try {
    port.writeString("test");
} catch (SerialPortException e) {
    e.printStackTrace();
}

And this is the code on my arduino:
void loop() {
  while (Serial.available() > 0) {
    Serial.print(Serial.readString());
  }
}

I hope someone can help :)

This is a common misconception about how serial communication works.
You're "sending" the "string" test. Except you're not.
What you're actually doing is you're placing the string test into the send buffer. Another routine then takes each byte from that send buffer in turn and sends it out through serial.
The Arduino then receives that byte and places it into its internal receive buffer.
You then get around to reading from the serial and you just get whatever is in the receive buffer at that moment in time - however many bytes that happens to be.
Then you "send" those bytes back - except again, you don't. You place those bytes into the internal transmit buffer in the Arduino and another routine takes each byte in turn from that transmit buffer and sends it out through the serial.
Again the Java program gets around to reading from the serial, and all it gets is what happens to be in its receive buffer at the time, however many bytes that may be at the time.
There is no such thing as "a string" or "a line" in serial. All there is is bytes - one after another.
It is up to you to receive those bytes and reconstitute them back into the form you want as each byte happens to arrive.
As it stands you have no way of knowing what that form should be, since you just send four bytes with no meaning attached to them.
It's common to add a "terminator" to a string when sending so that the receiver knows when all the bytes have arrived.  For us humans the simplest to use is a "line feed" or \n character.
Your receiving routine would then receive each character in turn appending it to the target String up until it receives the terminating character, at which point it knows that it has finished receiving this chunk of data and can act on it.
I have a popular blog post all about reading serial on the Arduino here, and the same principle can be applied to any other language.


Can't upload the program to Arduino Uno My Arduino Uno R3 is not detected by any laptop (I tried 3 laptops). Under devices there is no Arduino port or other devices option. It does not make sound on inserting USB cable. On plugging the USB LED 13 doesn't blink. I is just continuously on. Reset also didn't blink LED 13. Even on external power also it's not resetting.

I checked the USB cable but it's working for my friend's Arduino in my laptop too.

5V Pin giving voltage around 4.96 v, and 3.3 also giving voltage around 3.27 v.

Now I don't have access to any other Arduino for testing. Is there any way to figure out whether the ATmega chip is fried or whether it's a bootloader problem? And how to fix them? Thanks in advance.

While installing the Arduino software,
there are several window pop ups which occur to install the  drivers needed for the operating system to communicate with the device.
Click install to all of them.


How to sense snow and ice? We are building an outdoor snow melting system for the pavement. It would be nice if it could turn on itself only when it is needed: if there is snow, ice in the surface or the pavement is wet and the temperature is below the freezing point. Is there a good way to detect if the surface of something is snowy, icy or wet?

If the pavement is black, you could detect snow by infrared reflectivity. You might detect wet by resistivity. That leaves ice. Reflectivity might work there, too, at a different threshold. You'd need to experiment.

Another possibility might be a short-range sonar. If the measured distance changes, something is there. Ice would probably read as nearer. You'd probably need to average a number of measurements to increase the measurement resolution; you care about very thin ice coatings. Snow might well read as no return - but again, experiment.

A combination of the reflectivity and sonar might be the most reliable.


How many transistors are there in an H Bridge? I've controlled a motor going one direction using only one transistor. With an H Bridge, I can make a motor go forward, backward and brake. Does an H Bridge have only three transistors inside it to perform these functions, or does it take a larger number?

The absolute minimum number of transistors in a H bridge is 4 (one in each leg of the "H" and the motor in the middle), but there may be more depending on what voltage and control scheme is desired.


Average response time of Esp8266 module I'm planning a project where I'd like to control an RC car with Arduino and an Esp8266 module.

A software running on a computer would read the input from an USB analog controller and send the data to the Esp8266 module through the wifi network, and the Arduino would read this data and send signal to the ports accordingly.

What I'd like to know is: would ping/delay be an issue? Considering a dedicated wifi network for this, so the only devices connected to it would be the computer and the Esp8266 module.

I need to know what is the average response time of the Esp8266 module before I buy it, because if it is too high I'll think of something else since for this project I'd need a reasonably high response time.

I think response time would be a big problem. I used the ESP8266 with a temperature and humidity sensor, complete with a small web server on the ESP8266, and it works fine. But I wouldn't want to control an RC car with it. But if you buy it on ebay from China, it is only a few dollars, so buy one anyway.

Use Bluetooth, either a couple of HC-05 modules, or the Bluetooth Low Energy HM-10 modules. Both can communicate at 115200 baud. The HM-10 modules may be a bit tricky, because some Chinese sellers put a stripped down version of firmware on the module, and forces you to search online how to flash a usable firmware version.


Expected Initializer? I keep getting the error "Expected initializer" at different points in my code whenever I try to verify it. Currently, the error exists before "void setup." How can I fix this error and not allow it to happen in the future?

int ledPins[] = {9, 8, 7, 6};
int index;
int currentLED

void setup();
  {
  pinMode(Led1Pin, OUTPUT);
  pinMode(Led2Pin, OUTPUT);
  pinMode(Led3Pin, OUTPUT);
  pinMode(Led4Pin, OUTPUT);
  pinMode(Led5Pin, OUTPUT);
  pinMode(ButtonPin, INPUT);

  Serial.begin(9600);

  //Start a new game.

 for(index = 0; index <= 4; index++)
  {
    pinMode(ledPins[index],OUTPUT);
    // ledPins[index] is replaced by the value in the array.
    // For example, ledPins[0] is 2
  }
}

void loop()
{

  oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

}

void oneAfterAnotherNoLoop()
{
  int delayTime = 200; // time (milliseconds) to pause between LEDs
                   // make this smaller for faster switching
  // turn all the LEDs on:
  int Index;

for (Index = 0; Index <=3; Index++) {
  digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
for (Index = 3; Index >= 0; Index--) {
    digitalWrite(ledPins[Index], HIGH);
  delay(delayTime);
  digitalWrite(ledPins[Index], LOW);
}
}

void loop();
{
    // Check if the button is pressed at the right moment

   if (digitalRead(10) == 0)
   {
    if (currentLED == 8)
    {
      // Blink the orrect (green) LED
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
      delay(200);
      digitalWrite(8, HIGH);
      delay(200);
      digitalWrite(14, LOW);
    }
    }
  }

int currentLED

You are missing a semicolon there.

void setup();

There should not be a semicolon here.

Do some tutorials on the C or C++ language. They will help you.


#define above static const int? I see a lot of people, but also libraries, defining constants (like pin numbers, length of items etc) as #define:

#define LENGTH 5

While it is recommended to use in this case static const int:

static const int LENGTH = 5;

I did a test and for memory it does not make a difference.

Is there some specific Arduino reason why #define is (mis)used so often?

For numbers, certainly, const <type> is preferred.  This is chiefly because it imposes a type (which would only be optional for a #define), which can have a knock-on effect for mathematics.

That's not to say that you should always use const <type> instead of #define.  #define has its place.

One of the benefits of #define over const <type> is that it is a direct literal text replacement. The replacement is done before the compilation, so anything that is valid in your code can be put in a #define, whereas only things which evaluate to the correct type at runtime can be placed in a const <type>.

Take strings for example.  Yes, you can use:

const char *foo = "This is text";

And you can use that wherever a const char * is expected.  However, if you use:

#define FOO "This is text"

you can use it anywhere a string literal is expected.  That makes for useful things such as C's way of concatenating string literals at compile time:

Serial.println("I say: " FOO);

The two string literals "I say: " and FOO (which expands to "This is text") are concatenated into a singe string literal at compile time into:

Serial.println("I say: This is text");

You can't do that with const char *.

Another big difference with const <type> compared with #define is when expressions are evaluated.  Take for example:

const float sinpi = sinf(3.141592653);

That will calculate the sine of PI once at startup. However:

#define SINPI sinf(3.141592653);

will calculate the sine of PI every time it is used.

So in this instance const float not only gives you an imposed type of float for all calculations, it also reduces calculation overhead by only running the calculation once and saving the result.

So as you can see there are pros and cons to each.  But in general, for numbers:

const <type> is preferred for storing internal numerical data that doesn't change, and
#define is most often used for user-configurable data, since it doesn't impose the ; at the end of the line which often gets forgotten by (newer) users.


Noise in Analog Read Serial from an instrumentation amplifier(ina122p) I am trying to read the values from a simple EMG circuit (with an INA122P) using the analogRead() and plotting in the plotter using an Arduino nano v3. I am powering the ina1222p from the 5v pin of the Arduino. But no matter what I do, the signal comes out very noisy most of the time(i can rarely make out the EMG). The bandpass filter is also not really helping. I am using regular solid core wire and alligator clips to connect to the electrodes.
Can someone please tell me what I am doing wrong? or tell me how to make a simple EMG circuit that uses the Arduino's analogRead().
I am also getting ac sine waves when my laptop is plugged to power, so I tried removing the power. The distinguishable sine wave wasn't really showing up, but it was still just as noisy...
I am a beginner to both Arduinos and designing Analog circuits.

I found this design from here: https://greenhecktech.wordpress.com/2016/09/19/improving-the-emg-amplifier/

"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.
"bandpass filter is also not really helping" - INA122P circuit likely has something wrong.  check any resistors involved. Edit: if this was about U2.2, see below as that doesn't look like a band pass...
"regular solid core wire and alligator clips to connect to the electrodes" -
basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires.
Eventually you will want something better than gator clips.
My main recommendation is that as far as wire goes, if you form twisted pairs they tend to be pretty darn good at rejecting noise at least for that part of the wire.  You will want to twist a signal along with its reference (such as a +V and a ground).
Some explanation of the circuit:
U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1.  Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis.  (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)
U2.2 is a capacitor shy of an active band pass.  It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.
If possible, you may also wish to look into operating at a higher voltage.  This can help improve your signal to noise ratio.  If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.


Does delay() pause the counting of millis()? If I add a delay for a few seconds, and then will the value given by millis () be equal just before and after delay?

Or to put it in other words, does the internal clock of Arduino stop during delay?

Delay uses millis. It just waits examining millis until a certain time has passed.

Millis is driven by an interrupt. The only thing that stops it working is another interrupt (you can only have one interrupt executing at once), which is why you can't use delay in an interrupt.


Arduino losing connection to Serial port after running function For some reason when I loop my code through a separate function the serial port hangs up. The serial connection appears fine when I call cases within the loop but not when I call outside.

I tried to figure out where the problem is and for some reason using the Serial.print(ComControlValue); and the output is

  -1

But the error still persists.

Previous it was this before I changed the baudrate

  -b⸮⸮⸮⸮ Waiting for Command

It's not printing out the -1 I'm using as the main case. Could this be the problem?

#include <Wire.h>
/* RPi Army variables */
int RPi[3] = {3,6,9};                                        // SDA/SCL code names for the different Raspberry pi's

/* Define parameters for computer control */
int ComControlValue = -1;

void setup() {
  Serial.begin(115200);                                     // Establish Serial connection to computer
  Wire.begin();                                             // join i2c bus as master
}

void loop() {
 switch(ComControlValue){
  /* -1 : nothing happened yet */
  case -1:
     Serial.println("Waiting for Command");
     while (Serial.available()==0){}
     ComControlValue=Serial.parseInt();                             // Pull value from serial port
     break;

  case 111:
     Serial.println("Eat more Toast");
     ComControlValue = -1;
     break;

  case 210:
     Sendsignals(RPi[0],333);
     Sendsignals(RPi[1],333);
     Sendsignals(RPi[2],333);
     ComControlValue= -1;
     Serial.print(ComControlValue);
     break;
  }
}

void Sendsignals(int Rpi, int code){
   char str[4];
   sprintf(str, "%3d\n", code);
   Wire.beginTransmission(Rpi);                                 // transmit to device of choice
   Wire.write(str);                                             // sends 16 bytes
   Wire.endTransmission();                                      // stop transmitting
}

Your str variable in function Sendsignals is short. sprintf writes 5 bytes to it, 3 digits, the \n and terminating zero. The terminating zero is written outside of the allocated array and causes the crash.


Use same ground with 2 wires? So I have 3 ground pins, but I need 4 motors on my Arduino. Can I connect multiple motors to the same ground pin?

You can do it as long as the current isn't excessive. I don't think there are any specs available, but the connector and the width / thickness of the copper tracks on the PCB will be the limiting factor.


Will this sketch eventually fail because of integer limit issue? I am a novice in Arduino programming and I'm setting up an Arduino controlled, underwater time-lapse camera to take a picture every 2 hours.  It's going in the ocean for a month and I want to be sure that the code will not fail because of the upper limit that normal integers can go.
The Arduino simply switches on a relay (connected to the LED_PIN 11) and the camera does the rest, using a script from the awesome Canon Hackers Development Kit C.H.D.K.

I've tried several variations of sketch, some using simple delay, some with millis and some with counters that print what increment the loop it up to.

One of my fast running test sketches, that used a counter, stopped prematurely, I suspect due to hitting the integer limit but I'm not sure if this only occurred due to the fact that it had a counter in the sketch.  So I've gone back to the simplest sketch I can find hoping it will not have this issue.

I think I read that once the integer limit is reached, the sketch will simply restart.  Or maybe it will become unpredictable.  I'd rather the  former than the latter.

Any suggestions would be welcome.

I am sure there are many ways to go about this but I'm looking for the simplest and most robust one I can find, so that I can adjust the async timing easily ie.
loop starts
CameraOn for 10 seconds
CameraOff for 2 hours
Loop repeats

thanks in advance for your consideration

Here's the sketch I'm testing right now.

#define LED_PIN 11
#define LED_OFF 7200000     // 2 hours in millis
#define LED_ON  8000       // 6 seconds in millis

unsigned long ms;        //time from millis()
unsigned long msLast;    //last time the LED changed state
boolean ledState;        //current LED state

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

void loop(void)
{
    ms = millis();
    blinkLED();
}

void blinkLED(void)
{
    if (ms - msLast > (ledState ? LED_OFF : LED_ON)) {
        digitalWrite(LED_PIN, ledState = !ledState);
        msLast = ms;
    }
}

==================================================================

Okay, I've come up with a new, much simpler sketch based on delay.
Can someone please tell me if this is more robust in terms of continued looping for weeks on end?

#define LED_PIN 11

void setup()
{
   Serial.begin(9600);
   pinMode(LED_PIN, OUTPUT);
   digitalWrite(LED_PIN, HIGH);
}

void loop()
   {
       delay(7200000);                 // 2 hours in millis
       digitalWrite(LED_PIN, LOW);
       delay(8000);                    // 8 seconds in millis
       digitalWrite(LED_PIN, HIGH);

   }

No, the sketches will not fail or work incorrectly. The Arduino "delay()" function calls the "micros()" function for timing. The "micros()" function uses the Atmel's TIMER0 clock and waits for 1000 microseconds (1 milliseconds) each iteration. The TIMER0 overflows about every 70 minutes, but the program code used in the "delay()" function handles that overflow correctly.


Lego / Meccano style blocks for 'serious' projects What can be used like Lego or other construction sets, but is more serious and 'professional'?  E.g. what comes with gears and screws and things like that, but is geared to serious modelling or more permanent projects?

Here is what comes to mind (by no means exhaustive):

billed as "the Industrial erector set", 8020 is legitimately used in industry for that kind of purpose, and if I remember correctly, pretty expensive. It is the most "professional" thing I can think of.

OpenBeam styles itself as the the cheaper, "open sourced" 8020. I've frequently heard of it being used in 3d printers.

These are not as serious or professional, but might be worth mentioning:

MINDSi is pretty close to the mindstorms, but tries to be more rigid/durable. It's aimed at robotics.

Servo City's actobotics is an aluminum modular building system. It is also sold on sparkfun.

I have not used these enough to give good comparisons, but I hope one of these will be what you are looking for.


How cold or hot can my Arduino Uno get? The Arduino Uno Page doesn't say the temperatures that it can operate in. I'm thinking about placing it outdoors. How can I make sure my Arduino Uno is safe in weather that can reach -20 to 105 degrees Fahrenheit? (-26 to 40 degrees Celsius).

It's not that big of deal. The ATmega 328p datasheet states this:

  Temperature range: -40 to 85 degrees celsius.

The same goes for the USB chip on the Uno (ATmega 16u2 for UNO R3).

That's inside your limits. It probably could go a bit colder than mentioned, but it'll shorten the length of the board a little bit.

However, there are some things that may go wrong:

EEPROM might not be stored as long in extreme temperatures. Keep this in mind if you're storing critical data.
The voltage regulator may not perform as well in hot conditions
The crystal oscillator may not produce exact values. However, I would imagine that a few hertz more or less wouldn't affect a 16 MHz processor. The tolerance is actually a little less than 1%. You may have some issues with serial (baud rate not correct). I would look into any communications like I2C also. (I don't know exactly how the clock line works... it might be fine for I2C.)
Resistors/capacitors may not produce the exact values. I'd imagine that the tolerance won't be more than 8% on resistors: most resistors are rated at 5% for normal temperatures. It does depend on the manufacturer. Capacitors do have a bigger tolerance, but their main purpose is to "smooth" a signal.
Extreme cooling/warming may cause minor expansion problems. (Note: it's fine once in a while, but not on an hourly basis of dropping 30 degrees.)
Other components (LCDs, etc.) should be kept in mind also when looking at the viability of keeping it outdoors.

So as long as all the other components not on the board will happily run in the temperatures that you need, you should be fine. Also, as with all engineering, values often have added "padding" built in. (i.e. 5% tolerance is often 3-4%, maximum 12V it can run on 12.5V, etc.)*

*What I mean by that is your Arduino won't explode when it's -41 degrees C. It's not great for it, but most likely you should be fine as long is it isn't a regular occurrence.


LCD scrolling down problem I have a list of set-ups and I only have 2 rows in the lcd , I'm trying to scroll down for the moment and I'm doing this by changing the row in the setcursor function to either 0 or 1.

However since that I'll be having about 10 set-ups I used an equation that will change the rows to 0 and one for the ones I want to display and a negative number for those that I don't want to appear.
The problem is when setting the cursor's row to -1 or 2, it will ignore the one with row one (which is the 2nd row).

Is there a way that I can overcome this problem ? by setting it to a row that will not appear on my LCD?
I'm using #include <LiquidCrystal.h>
and I already set lcd.begin(16, 2);

int  colom[5] = {
    0-goDown,1-goDown,2-goDown,3-goDown,4-goDown  };
for (int i = 0; i < 4; i++) {
    if (colom[i] > 1) colom[i] = -1;
}

  lcd.setCursor(0, colom[0]);
  lcd.print("choise 1 ");
  lcd.setCursor(0, colom[1]);
  lcd.print("choise 2 ");
  lcd.setCursor(0, colom[2]);
  lcd.print("choise 3 ");
  lcd.setCursor(0, colom[3]);
  lcd.print("choise 4 ");
  lcd.setCursor(0, colom[4]);
  lcd.print("choise 5 ");

So here goDown is 0 so choice 1 and 2 should appear, but I'm only getting choice 1 and in the second row it's changing quickly between 2 and 5, it's not constant.

I thought about doing an if condition for each choice but that will be a lot of code to write and it won't be efficient for my application.

This is a bad strategy in general. You should not be issuing print calls for things you don't want to print and relying on the lcd library to filter for you because they're out of bounds.

Call print for only the choices you want to display.

char* menu[] = {
    "choice 1",
    "choice 2",
    "choice 3",
    "choice 4",
    "choice 5",
};
const int numMenuItems = sizeof menu / sizeof *menu;
const int numLcdRows = 2;

// start out at the top of the menu
int scrollPos = 0;

void drawMenu() {
    for (int i=0; i < numLcdRows; ++i) {
        lcd.setCursor(0, i);
        lcd.print(menu[i + scrollPos]);
    }
}

To scroll up or down, just adjust the scroll offset:

inline void scrollUp() {
    if (scrollPos > 0)
        scrollPos--;
}

inline void scrollDown() {
    if (scrollPos < numMenuItems - numLcdRows)
        scrollPos++;
}

Note this is untested code written for a library I've never seen (just inferring how it works from your post); it's for illustration purposes only.


How to user timer interrupts for times longer than can TNCTx can keep track of? I am trying to program my Arduino Mega 2560 to effectively create a PWM signal on any digital pin using timer interrupts and timer1. The pins will pulse a finite amount of times (not indefinitely). I am first trying this with a 256-prescaler value, which I believe means that each increment of my TCNT1 is 16.0 microseconds, and since it is a 16-bit register, it can reach a max. value of 1048567 microseconds.

I am designing the program so that the period and duty cycle are changed by Serial commands that the user can send (I already have that part figured out). I am using clear timer on compare mode and OCR1A and OCR1B to toggle the digital pin between HIGH and LOW.

If the desired period is less than 1048567 microseconds, I can divide the period by the modified clock (modified by the prescaler) to figure out the OCR1A value, and then based on the desired duty cycle, calculate OCR1B. Then I set the ISR vectors for A and B to toggle the pin and count down until the desired number of cycles is completed.

What I would like to also allow the user to do is set periods/duty cycles that would be longer than 1048567 microseconds, but I'm not sure how to accomplish that. For example, if I wanted to have the pin be HIGH for 2 seconds with a total period of 10 seconds, I would choose values for OCR1B and OCR1A that, through the ISR(TIMER1_COMPA_vect) and ISR(TIMER1_COMPB_vect), I could keep track (through a counter variable) of how many interrupts had occurred. If enough interrupts had occurred to equal the time of that the pin had to be HIGH and/or LOW, the ISRs would actually trigger the toggling of the pin (instead of just counting the number of interrupts).

How could I choose the OCR1B and OCR1A values that would accomplish this optimally? Is it reasonable to keep track of time this way as a workaround to the limitation of the timer counter max value? I am open to any suggestion and I appreciate any input. Thank you.

By maintaining your own second-level prescaler you can quite easily keep track of longer periods.

The most efficient method is to use a "divide and multiply by two" scheme.

Start with a custom pre-scaler of 1.
While the count period is > 65535:

Multiply the pre-scaler by 2.
Divide the count period by 2

uint16_t ps = 1;
uint32_t period = 429864;

while (period > 65535) {
    ps <<= 1;
    period >>= 1;
}

Then you can load the count period register with the now divided count period and use a variable to count the number of times the interrupt has been triggered. When it equals your custom pre-scaler value you reset the count to 0 and run your actual interrupt routine.

The left and right shifts multiply by two and divide by two respectively in a very efficient manner. Far more than multiplying by 10, or dividing the period by 65536 and using that as a prescaler.


How many Infrared sensor modules can be added to a single Arduino (eg;Uno) I am looking to add block detection to my model railroad. I need approx. 40 infrared sensors to power 40 LED's on my control panel. No signals or other logic required yet, just the LED indications -LED- on=occupied  off=vacant.
How many Uno boards would I need to do this? I may, in the future, look at integrating several two (or three) aspect signals down the track. I am an absolute novice here, never having used an Arduino, nor done any coding of any sort.

You just want to know how many you can attach to an Arduino board or how many Arduino Uno boards you need, but it does not work like that.

Some sensors with a led require 5mA or 10mA or 20mA. The reflective optical sensors use a IR (InfraRed) led. The Arduino Uno 5V pin can probably not supply enough current for 40 leds. Therefor you might need a seperate power supply.
I think the TCRT5000 is typically set at 10mA.

The Arduino Mega 2560 and the Arduino Due have many pins. But with 40 TCRT5000 sensors, the total current is too close to the limit.

In such situation often extra hardware is added. You can use one Arduino Uno board, with extra hardware for multiple inputs or outputs.

An "expander" is a chip or a module that connects to the Arduino with a few wires, but has many input and/or output pins. For example a "expander" with I2C interface to the Arduino Uno as mentioned by @matsk. Although a I2C expander has a slow I2C interface, they are sometimes smart and can tell which pin has changed by reading a single byte.

"Shift registers" are chips with for example 8 input pins or 8 output pins. The data of the pins is shifted into the chip with a data and clock signal. There are many examples for that: ShiftOut with a 74HC595.

A analog "multiplexer" or "mux" is a chip that can connect one common pin to one of 8 pins. The signal can go both ways. Nick Gammon about a multiplexer.

A "ADC" is short for "Analog to Digital Converter". The Arduino Uno has an internal ADC, but also a external ADC can be used. They have often more than one analog input.

"Polling" is when an Arduino is reading many inputs continuously one by one. If for example it takes 5ms to read a sensor, then 40 sensors take 200ms. That means that every sensor is read once per 200ms. If a train would pass within that 200ms, then it might be not detected.
The opposite of polling is with interrupts. If an external event happens, it could trigger an interrupt and the Arduino can react right then at that very moment. However, 40 interrupts is not possible.

Conclusion:
The best way depends on your hardware and software skills, on the maximum interval that you want to read the sensors, on the sensors themself, and how far apart the sensors are, and if you want 40 wires to a Arduino board.
The best Arduino board also depends on what you want to do with the data and what else the Arduino has to do.
Some sensors have a analog output and some a digital output. It depends on your situation and the way the train is detected.
If possible, then I would choose a solution where all the hardware can be easily be replaced. If the sensor has digital outputs, then I would connect them to a Arduino Mega 2560 or Arduino Due.


Intializing Serial crashes UNO I have a somewhat large sketch that uses the Adafruit_ssd1306(I2C) library for a 128X64 LCD. The sketch is a designed to be an alarm clock. When I upload the sketch with out initializing serial, it works as designed. However if I do intialize serial:

Serial.begin(9600);

the program fails to run on my UNO. After many hours of troubleshooting I noticed I have several large char arrays that may be the culprit.

const char *menusDisplay[] = {"1. Alarm-is Off", "2. Month", "3. Hour", "4. Minute", "5. Exit", "6. Alarm Set", NULL};
const char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep" , "Oct", "Nov", "Dec", NULL};
const int days[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The months array as 12 elements. If I shorted it down to 2 elements and upload the programs with serial initialized, the program runs. At first I thought is was a memory leak in perhaps the Adafruit_ssd1306. But I also have another LCD library Adafruit_ssd1306syp that the issue occurred too. So that ruled out those libraries.

When I compile the sketch without Serial:

Sketch uses 16,846 bytes (52%) of program storage space. Maximum is 32,256 bytes.
Global variables use 737 bytes (35%) of dynamic memory, leaving 1,311 bytes for local variables. Maximum is 2,048 bytes.

With Serial:

Sketch uses 17,862 bytes (55%) of program storage space. Maximum is 32,256 bytes.
Global variables use 910 bytes (44%) of dynamic memory, leaving 1,138 bytes for local variables. Maximum is 2,048 bytes.

Any ideas of what may be going on? I would load the sketch but its very large. If needed, I can try to cut it down and reproduce the issue.

Since no other code is posted, I am going to guess that you're performing a loop on months[], which has 13 elements (last one is NULL).

You are likely also trying to walk the days[] array (or some other array), which only has 12 elements.

Since days[] or the other (not pasted) array doesn't have 13 elements, you're probably overriding a critical bootloader memory which causes a crash.


Arduino 101 MIT App Inventor extension Can the Arduino 101 extension by MIT App inventor be used in sending data through Bluetooth by an Arduino Uno/Mega?

Neither the Uno nor the Mega have the hardware required for Bluetooth. I have no idea what “The Arduino 101 extension” is (you don’t provide a link - and you should.)

If that’s only software, it can’t possibly provide a feature that requires hardware support. You’ll need to add a Bluetooth module to your Arduino.

After doing some searching, I found this link: https://randomnerdtutorials.com/getting-started-with-mit-app-inventor-2-and-arduino/

It discusses using the MIT app inventor 2 and a hardware Bluetooth module to communicate between an Arudino and an Android device. I don’t know if they support other desktop or mobile device platforms or not.


Arduino Uno and ESP01: can't issue AT commands [Solved] I would like to connect an Arduino Uno and an ESP 01 module. I use the Arduino IDE and I tried to test communication via serial monitor. I get the "ready" message from the ESP 01, but I am not able to issue AT commands from the serial monitor. It only displays random characters on the console.

It seems that no newline character is issued, because if I try to insert commands, they are inserted next to previous characters. I use "Both NL & CR" and 115200 baud settings in Arduino IDE. I tried 9600 baud too, but then the text is unreadable.

I used the following pins on my ESP-01:

Vcc -> 3,3V
Gnd -> Gnd
Rx  -> Tx(pin 0) of my Arduino, used voltage divider to make it 3.3V.
Tx  -> Rx(pin 1) of Arduino
CH_PD -> 3.3V

Please see serial monitor screenshot:

EDIT: PROBLEM RESOLVED:

My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Just to have an answer instead of just an edit/addition to the question:

  EDIT: PROBLEM RESOLVED:

  My Arduino is connected to my PC via USB, so I changed pins for communication with the ESP by SoftwareSerial to pins 10 and 11. Now it works. Thank you.

Ok... sure... your Uno's Atmega384 was talking with pins 0 and 1 to the USB adaper chip (Atmega16u2 on Uno R3) and at the same time to the ESP-01.

Read the fine schematic: Arduino Uno R3


How to return a message when calling by a TCP connection? I am working on a communication between Android and Arduino board.

The Android makes a TCP connection with the board and successfully sends some strings to the board.

The problem is, there is an int in my Arduino code (e.g. int distance) and I would like to pass that back to my Android device.

I have handled the Android side already, but I do not know how to return a message from Arduino.

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

This is the Android side code but I think that it is not a specific Android problem, there should be some way for Arduino to make a response of an integer variable (without concern what is the source device)?

What I should do in Arduino for making that response?

I'm assuming that you are using an Ethernet shield, as nothing about this is stated. But solution is really similar between many network solution.

Once a TCP connection has been established, it can be used like you would use the Serial;

you'll probably end up having something similar to:

EthernetClient client = server.available(); //accept a new connection
if (client) { //if valid connection
  client.print(distanceValue);
  client.close(); //close connection
}

look at the official API reference for a more detailed list of available command.


ESP8266 as I2C client I've got an ESP8266 that takes instructions from a web page and sets a series of NeoPixels to flash in different sequences.

I noticed that when the Wi-Fi got data and parsed it, my LEDs would "stutter" as the processor ignored them for a moment while processing the incoming instructions.

So I added a 2nd ESP8266. This one just handles the LEDs. So the 1st ESP gets the Wi-Fi data and parses it. It then sends an interrupt to the 2nd ESP which breaks out of the LED display loop, checks the interrupt pin for HIGH or LOW and sets the LEDS based on HIGH/LOW.

However, I would like to send more data from the Wi-Fi ESP to the LED driving ESP. e.g. Colour data, transition speed, rotation direction etc. All of these settings I can send to the ESP from a web page.

I thought I2C (the wire library) would help but all comments seem to say that the ESP8266 cannot act as a slave so I can't send to it.

So it appears I'm left with Serial comms (the interrupt is over by the time comm start because I realize Serial does not work in an interrupt).

So my questions are:

Am I right that I2C will not work?
If I am wrong does anyone have a working end to end example?
If I am right is there an approved way to do ESP to ESP serial comms?

I assume that you are using the Arduino core for the ESP8266 (https://github.com/esp8266/Arduino)

  Am I right that ic2 will not work?

I am not certain, but I get the same impression as you.  It seems that the Expressif SDK only supports master mode.

  If I am right is there an approved way to do ESP to ESP serial comms.

There is no "approved way", but there are many ways you can do it.  A direct serial link will give you a simple pipe of data - what you put in at one end comes out the other.  It's up to you to decide how you format and interpret that data.

My ICSC library may help you with that - I use it to connect an ESP8266 to an BeagleBone Black through serial: https://github.com/MajenkoLibraries/ICSC


Properly using separate tabs with Arduino IDE I'm trying to split up a large project of mine into separate tabs in the Arduino IDE and I'm having more than a few troubles with it. My main trouble is finding a way to have routines in extra tabs access the Serial object; because it's really hard to debug things with Serial.println() otherwise. All I get, though, is "'Serial' was not declared in this scope".
There appears to be some kind of trick to this? I've noticed that "byte" or "bool" needs to be declared in .cpp tabs and .h tabs but not on the main one?
Is there some kind of easy way to set this up so that I don't need to constantly #include <stdbool.h> and typedef unsigned char byte;?

Current issue: Main file:

void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

driver.ino file:

byte PrintMessge () {
  Serial.println("printin");
}

and on compiling:

error: 'PrintMessage' was not declared in this scope

EDIT: Found a silly typo. Problem solved.

This question is more about C/C++ header basics rather than Arduino. Anyways, you should have the following file structure: Code in .cppfiles, Header in .h files. Main sketch either .ino or .cpp (for cpp remember that you must explicitly write out the function prototypes!)

So for your small example that would be:

main.ino:

#include "driver.h"
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

driver.cpp

#include "driver.h"
byte PrintMessage () {
  Serial.println("printin");
  return 0; //previously had no return although returning 'byte'.
}

driver.h

 //Always use include guards
 #ifndef DRIVER_H
 #define DRIVER_H

 #include <Arduino.h>
 //All function prototypes from driver.cpp.
 byte PrintMessage();

 #endif /* DRIVER_H */

Also corrected a typo from PrintMessge to PrintMessage. This is the "professional" way to do it, seperate implementation and header files.


if/else on digitalRead not executing on 'else' portion I am a beginner with C++ but used to be good with BASIC (2 decades ago lol). I'm building a peristaltic metered doser that allows you to input desired mL on a 4x4 keypad and then when 'fill' button is pressed it doses the desired mLs through the peristaltic.

I'm still drafting/printing the peristaltic housing and all of that but in the meantime I want to get as much of the coding done as possible. It's still incomplete, but one of the functions I want the doser to have is a 'PRIME/FLUSH' button.

Originally I wanted the button to run the pump as long as the button is held down to prime the tubing with solution or flush the tubing with DI water. But I haven't had luck figuring out how to use a 4x4 button in momentary switch mode.

A workaround I had was to have the button be an on/off button. So press it once, pump turns on, press it again, pump turns off. Since the pump isn't printed yet I've been using the onboard LED as a tester for the coding (hence the LED_BUILTIN).

The issue, from my research I figured what I would need was an if/else statement. When the button is pressed (in this case the 'a' button), it reads the LED_BUILTIN status and if its HIGH it turns it off and if its LOW it turns it on.

But the 'if' part is working, it turns it on, but the 'else' part is not. When the LED is already on and the 'a' button is pressed, it stays on and doesn't rewrite to LOW.

Code below, any advice?

#include <KeypadShield.h>

KeypadShield keypad;

#include <LiquidCrystal_I2C.h>
#include <Wire.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

char Data[15];
byte data_count = 0;

int x;

char customKey;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  keypad.begin();
  lcd.begin(20,4);
    lcd.setCursor(4,0);
    lcd.print("Let's Fill!");
    lcd.setCursor(4,1);
    lcd.print("Designed by");
    lcd.setCursor(4,2);
    lcd.print("JP");
    lcd.setCursor(5,3);
    lcd.print("2019 v1.0");

    delay (2000);

    lcd.clear();

    lcd.setCursor(1,0);
    lcd.print("Enter volume in mL");
    lcd.setCursor(3,1);
    lcd.print("on keypad then");
    lcd.setCursor(5,2);
    lcd.print("press DONE");
    lcd.setCursor(0,3);
    lcd.print("mL:");
}

void softReset()
{
asm volatile ("  jmp 0");
}

void loop()
{
    customKey = keypad.getNextKeypress();

    if (customKey)
    {
      if (customKey == 'a')
      {
        if (digitalRead(LED_BUILTIN == LOW))
        {
          digitalWrite(LED_BUILTIN, HIGH);
          lcd.clear();
          lcd.setCursor(5,1);
          lcd.print("FLUSHING");
        }
        else
        {
          digitalWrite(LED_BUILTIN, LOW);
          lcd.clear();
          lcd.setCursor(1,0);
          lcd.print("Enter volume in mL");
          lcd.setCursor(3,1);
          lcd.print("on keypad then");
          lcd.setCursor(5,2);
          lcd.print("press DONE");
          lcd.setCursor(0,3);
          lcd.print("mL:");
        }
      }

      if (customKey == 'd')
      {
       softReset();
      }

      if (customKey != 'p' && customKey != 'a' && customKey != 'b' && customKey != 'c' && customKey != 'd' && customKey != 's')
      {
        Data[data_count] = customKey; // store char into data array
        lcd.setCursor(data_count+3,4); // move cursor to show each new char
        lcd.print(Data[data_count]); // print char at said cursor
        data_count++; // increment data array by 1 to store new char, also keep track of the number of chars entered
        x = atoi (Data); //convert string to integer 'x' for use in equations
      }

     if (customKey == 'p')
      {
       lcd.clear();
       lcd.setCursor(7,0);
        lcd.print(x);
        lcd.setCursor(Data[data_count]+13,0);
        lcd.print("mL");
        lcd.setCursor(0,1);
        lcd.print("FILL --> fill");
        lcd.setCursor(0,2);
        lcd.print("RESET --> change mL");
        lcd.setCursor(0,3);
        lcd.print("FLUSH --> finish");

      }
    }
};

(Heh... before even seeing the code I guessed you'd done this...)

You are comparing a pin number, not the results of digitalRead(), and then passing the results of that comparison to digitalRead():

if (digitalRead(LED_BUILTIN == LOW))

It should read:

if (digitalRead(LED_BUILTIN) == LOW)

Note the order of the brackets:  LED_BUILTIN is passed to digitalRead(), and then the result of calling that function is compared to the value LOW.


Correct connections: 7-segment, 4-digit display with common anode I see this connections for 4-digit display.

All used pins set up on output. But, really, is it correct connections?

Why it used A* input pins, and, digital pins set up on output, it is right?

Maybe all pins need used by digital pins with NPN transistors? Collector is 5V, Base - Arduino digital pin, emitter - resistor with display anode, next, collector is display segment pin,  Base - Arduino digital pin, emitter - Ground.

What resistance is needed for the resistor? I think, more than 220 Ohm?

Sorry, but I'm really a beginner in electronics.

That circuit looks OK to me.  It will allow you to light (reliably) a single segment at a time.  The A* pins will be used in digital output mode.

The A* pins are connected to the four anodes of the digits - each digit has common anodes for all the segments.  They should be driven HIGH to 'select' a digit.

The D* pints are connected to the cathodes of each segment.  They should be driven LOW to light that segment.

For example, to light the 'A' segment of the first digit, you would set:

A1 HIGH, to drive the anode of the first segment
A2, A3, A3 LOW, so that the other three segments are not driven
D5 LOW, so that current flows from A1 to D5, lighting the digit
D6-D12 HIGH so that no current flows from A1 through any of the other segments.

The expectation is that you will cycle around (very fast), lighting each required segment on each required digit in turn.

Without a (proper) data sheet we can't tell you what the correct resistor value is, but the 220R shown is probably OK.


Arduino + DS18B20 array I want to connect 24 DS18B20 sensors to arduino by onewire library in the same digital pin .

Can anyone post an example code ?

Thanks

Use the OneWire and the DallasTemperature libraries. They are both in the Arduino IDE in the Library Manager.

The DallasTemperature library has the example "Multiple". You need to make an array of DeviceAddress.

To tell them apart, you have to label each temperature sensor with its device address (a unique identifier inside each DS18B20). Therefor you have to connect them one-by-one and write down the device address.

Start with one sensor, and if that works, try to make arrays.

For 24 temperature sensors, you need a lot of wires. That could make it less reliable. You can use two or three or more pins as well. Then you have to create more than one "OneWire" bus in the sketch.

There are many examples for multiple DS18B20 sensors. For example this one is with an array: Arduino forum: "multiple temp sensors ds18b20".


How to add more inputs on Arduino? I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?

If it makes any difference, the max number of buttons that can be pressed at once is 10.

There is a whole concept you need to learn:

Matrix

By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.

This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial

To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time.  That reduces it down to just 12 IO pins for the whole shebang.


Millisecond timestamp (13 digits) in Arduino How can I store a 13 digits int in Arduino?

For example, current timestamp is:
1500666822235

An uint32_t can only hold 10 digits max.

64 bits integer does not seem to be supported on RFduino.

18446744073709551615
That 20 digits. It is the maximum value of a uint64_t. Even the Arduino Uno can use the uint64_t. Perhaps the Serial.print does not support it, but the compiler supports it.

Which processor does your RFduino have ?

Where does the timestamp come from ? Perhaps you are asking the wrong question. Perhaps this is a xy-problem.


Is it support to use Infrared radiation module in ESP12E? I have a IR module -->image as shown

is it possible to use the IR module in esp8266?

how to do(sent and receive)?

what is the packet format of IR module?

please explain.

Thanks

is it possible to use the IR module in esp8266?

Yes.

  how to do(sent and recive)?

You send by pressing a button on your remote control. You receive by measuring the timing of the changes in the pin state.

  what is the packet format of IR module?

Whatever packet format your remote control sends.

It's no different using IR on an ESP8266 compared to an Arduino. There's a library that everyone uses (IRRemote.h), and there are plenty of examples and tutorials on the web (or on YouTube if you can't be bothered to read). I suggest you ask Google for some.


How to "implement" an Arduino prototype? I am starting with Arduinos, coming from the world of Linux (with the RPi as a bridge) and after having tested some setups I now wonder where to go next in implementation.

What I am trying to understand is whether it is recommended (time and cost-wise)

to create a standalone, circuit-board based version of whatever I prototyped on the breadboard, with a micro-controller with connections trimmed down to what is needed for that specific setup?
or rather just look at neatly packaging the Arduiono with the breadboard and wires in a case?

I expect to build 5 or 6 of the same simple setups (to put in various places in my house).

Note: there is a similar question (with almost the same title) but it deals with the legal aspects of commercializing a setup.

with the breadboard

That phrase right there makes the solution a non-starter. Solderless breadboards are good for prototyping, but are too fragile for use in a final project.

As for whether or not you should use an actual Arduino or reduce the circuit to a minimum, that is between you and your wallet. It is possible to make a basic AVR board (including MCU) for under $6 in parts, but the time investment is not entirely trivial.


Does baud rate for HC-05 Bluetooth module need to match the Serial Monitor? I have this sketch that I got as a sample.  I have the two HC-05s connected.  What I type in one serial monitor shows up on the other, but as question marks.  The most common reason for this I find is baud rate doesn't match.   I didn't change the baud rate on the HC-05s when I got them, so I assume they are set to default.  I can put them in command mode and ensure the baud rate is set.

Does the baud rate of the HC-05s have to match the baud rate of the Serial monitor?  I would assume not.  I am also wondering if this is a problem with formatting a char[] when writing to the serial display.

#include <SoftwareSerial.h>
SoftwareSerial BTserial(7, 8); // RX | TX
// Connect the HC-05 TX to Arduino pin 7 RX.
// Connect the HC-05 RX to Arduino pin  8 TX through a voltage divider.
//

char c = ' ';

void setup()
{
Serial.begin(9600);
Serial.println("Arduino is ready");
Serial.println("Remember to select Both NL & CR in the serial monitor");

// HC-05 default serial speed for AT mode is 38400
BTserial.begin(38400);
}

void loop()
{

// Keep reading from HC-05 and send to Arduino Serial Monitor
if (BTserial.available())
{
    c = BTserial.read();
    Serial.println(c);
}

// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
{
    c =  Serial.read();
    BTserial.write(c);
}
}

No, they do not need to match.

You are talking about two separate serial port connections.

The baud rate between the HC-05 and the Arduino (BTserial) has to match.

The baud rate between the Arduino and your PC (Serial) has to match.

BTserial and Serial can use different baud rates.

An overflow problem can arise if a lot of data arrives from the HC-05 and there is not enough memory to store it until it can be forwarded to Serial.

simulate this circuit – Schematic created using CircuitLab